Week 1: What it’s All About!

 

CS 161: Introduction to Computer Science 1

 

 

 

Programming Languages

• A program is an expression of a series of instructions that the computer (CPU) must perform. Programs are written in precise languages, that are understandable to a computer. These languages are called programming languages.

 

• In this course, we will be learning about what programs are all about. We will see examples all term of various high level programming languages – mostly C, C++ and Java. Other programming languages are Pascal, Modula-2, C#, FORTRAN, ASSEMBLY LANGUAGE, MACHINE LANGUAGE.

 

      Programming languages such as C++, C, Java, Modula-2, Pascal, and Fortran are easier for a human to read, write and understand, than machine language; these are called high level languages.  Machine language, on the other hand, is based on ones and zeros that the computer directly understands. Higher level languages are turned into machine language for the computer to understand by another computer program.

 

 

Problem Solving, Abstraction, Program Engineering

• A computer language allows you to translate ideas into a specific language that the computer will understand. This is not the most difficult part of computing. Instead, the most difficult part is figuring out how to design a method to solve a particular problem. Once the method is designed, it is generally a fairly easy task to go and translate this into a high level computer language, such as C or C++.

 

• This means that when you are first designing a program so that the computer can solve a particular problem, it is first best to ignore the actual programming language that is being used and fire out instead the steps you will need to go thru to actually solve the problem. Write these steps down even in English or an English like form (we call this pseudo code...it isn't a language but it is a tool for creating the instructions as if you were to tell the instructions to another person). These steps -- to solve a problem -- are in their entirety called an algorithm.

 

      An Algorithm is a sequence of step by step instructions for performing some task -- usually for computation.

 

      For example, to direct a friend to PSU from Washington square you have to give them a series of instructions that will step them street by street from Beaverton to Portland. You can't just say get on 217! You need to say where to go straight, right, left, the street names, etc.

 

      To do this, the steps that you tell your friend must:

            1. Accomplish the task

            2. Be clear and easy to understand

            3. Must define the sequence of steps needed to accomplish the task in the order specified.

 

            These rules apply just the same to algorithms!

 

• Examples of algorithms are recipes, methods, directions. They may be expressed in a programming language or in an English-like language.

 

• An algorithm expressed in a language the computer can understand is called a PROGRAM!

 

• Sample algorithm:  Compute your income tax (in simple terms).

1)      Find out what your income is (as input)

2)      Find out what your number of exemptions is

3)      Find out many deductable itemized expenses you have

4)      Calculate adjusted gross income

  5) Calculate exemption amount (number of exemptions times standard rate/exemption)

  6) Subtract exemption amount from adjusted gross income

  7) Calculate itemized deductions (input is expenses)

  8) If itemized deductions greater than standard deduction then use itemized deductions otherwise use standard deductions

  9) Subtract deductions from amount in step 3 giving taxable income

  10) Look up taxes in table based on taxable income

  11) Provide the resulting tax (possibly as output)

 

• Another algorithm:  Convert from Fahrenheit to Celsius

 

1)  Find out what the temperature is that you want to convert

2)  Subtract 32 from Fahrenheit (input is temp in Fahrenheit)

  2) Multiply result by 5/9

  3) Provide the results (maybe output it?)

 

 

 

 

Designing Programs

• Programming is a creative process. First you get a problem that needs to be solved. An algorithm must be designed and you should walk thru it with pseudo code to do some "desktop verification". Once you feel confident that you have figured out a good algorithm, then the next step is to code the algorithm as a program in a high level programming language; this phase is called the implementation phase. Once the program is written, you need to test it to create a working program.

 

• So, first you solve the problem, then you implement it, and then you test it! BUT...hold on...before you try to solve the problem, make sure that the task is completely and precisely specified. Do you know what the output of your programs is supposed to be? Do you know what data is to be input into your program? 

 

• When solving a problem, you first need to understand the problem and how it should be solved...how the user should be allowed to interact with it...what type of results it should produce. One you have totally thought out the input, output, and processing steps, you have created an algorithm. It isn't until after all of this is done that you should begin to program. If these steps are not followed, you will be spending a great deal of time in the computer lab working at the terminals finding and removing bugs (errors).

 

      In addition, desk-checking your algorithm and program is an essential phase that we will be talking about frequently this term. Desk checking means to simulate the result of each program instruction with some sample data that you have selected...to see if your program really does the job. Desk checking is an important step...even for experienced programmers!

 

 

Using the Computer

• You can either work on your own computer for this class or work with the school computers (either on campus or remotely). There is plenty of free software, so you do not need to buy any software to accomplish our goals this term.

• For you own computers, I recommend downloading DEV C++ and graphics.h. Refer to the separate handout that gives you the web sites and information on how to install this. It will be demonstrated in class.

• When using the school computers, you would be on a timeshared computer named ODIN; The CS department also has multi-user system available for use. You can get an account by going to the basement of the FAB building and the computer science labs. With a multi-user system, there is one CPU (one computer) with many terminals connected allowing many users to access the computer at one time. There is also remote access, so we can access these computers via a broadband or wireless connection. With a UNIX timeshared system, you do not need to boot the computer...as described in our book. Instead, you will need to login.

 

• The first step, after sitting down at the terminal, is to enter your login name (it won't be your real name) and then the system will ask you for your password. You will type this in...even though you won't see the characters as you time (to keep it private). This should be the same password that you use to get onto Blackboard.

 

• The next step in creating your own programs is to use a text processing program (called an editor) where you are able to type in your own program. We will be using pico on the ODIN computer. This is similar to a word processor.

 

      Each text file or program that you create with a word processor will have a name, called a filename. For C++ programs, pick names like: prog1.cpp (the suffix should be ".cpp"). For C programs, pick names like: prog1.c

 

• Once you have typed your program and corrected any typing errors that you may have made, the next step is to use a compiler to translate your programs into machine language.

 

      On unix you will compile your program by typing: (for C++)

                        g++ filename

            i.e.,

                        g++ prog1.cpp

 

            When working with C, we will compile using gcc prog1.c

 

• This will produce an executable program that you can run. By default, the system will produce a file called "a.out". This will wipe out any previously created executables in your working directory.

 

• Now you can run your program, unless syntax errors were encountered. You can do this by typing:

 

                        ./a.out

 

High Level Programming Languages

• There are many high level programming languages. Each has a unique ability to suit special needs. Web design might use Java and/or Perl. Engineering might use C, Fortran, or C++. Business uses gravitate toward Cobol or Visual Basic. Large complex simulations are best done with object oriented languages, such as C++ or Java.

 

Dennis Ritchie built created the C programming language in the 1970’s to have a powerful mix of high-level functionality and the detailed features required to program an operating systems and low level needs. Most of the components of Unix were eventually rewritten in C.

 

• C was used as a defacto standard for many years - as defined by Ritchie for the PDP-11. Starting in 1983, the standards committee started working on establishing an American standard for the definition of C; this standard was approved in 1990. C++ has subsequently been standardization. These standards enable software to be more portable when moving from computer system to computer system...instead of having to re-write your code every time you are dealing with new computers.

 

• C++ was not originally developed as a production language. Instead, it was developed in the early 1980's by Bjarne Stroustrup at Bell Labs to write some complex event-driven simulations, with simplicity and compatibility as important design criteria; the goal was to enable larger programs to be structured in such a way that it would not be unreasonable for a single person to manage 25,000 lines of code. The language has evolved since then, with its first installation in 1983; it is continuing to evolve. The good news is that AT&T Bell Labs has committed to keeping a high degree of stability and are working with companies creating C++ compilers to assist with compatibility.

 

     One of the key design goals for C++ was to keep it upward compatible with C. This ensures that millions of lines of existing C code does not need to be reworked. It also helps C programmers learn C++ without having to start from scratch.

 

• Unlike other high level programming languages, C and C++ are considered to be system programming languages. This is because they are not only useful for writing your applications (with all of the facilities of a high level languages) but they are also useful for writing compilers, and operating systems.

 

The Java programming Language evolved from a language named Oak. Oak was developed in the early 1990’s at Sun Microsystems as a platform-independent language aimed at allowing video games and VCRs to communicate. As the web became a viable entity, Sun shifted their to the Internet, Oak’s name was changed to Java.

• Java compilers do not produce native object code for a particular platform but rather ‘byte code’ instructions for the Java Virtual Machine (JVM). What this l means is that the same compiled code will run unmodified on any platform that supports Java. This made Java particularly attractive to web development with it’s cross platform need for support.

 

Stepping through a Program,

• Our main goal for our first lecture is to understand the syntactic structure of a simple program and to learn how to build simple programs containing one module.

 

• First of all, think of C and C++ programs as consisting of functions and variables. The functions specify the operations to be performed ... and of course, the variables store the information used during computations. There must always be a function called: main in every Java, C and C++ program. And, just like main body of a Pascal program....the main function of a C++ program is where execution begins.

 

• A C++ program consists of compiler directives and an implementation part. To begin with your compiler directives will simply instruct the compiler to insert indicated C++ instructions into your program. Your programs will have the following first line:

            #include <iostream>

            using namespace std;

 

      This means that the C++ library "header file" named iostream is included in your program. This is a standard library file that is included with your C++ system...and it allows your program to perform all Input from a keyboard and output to a terminal. This statement must be included to perform any I/O in your program.

 

      Please notice that compiler directives should not end with a semicolon.

 

• For simple C++ programs, the implementation part will start with:

            int main()

 

      it must be typed in lower case and followed by a pair of parentheses. This is where your main program begins.

 

      A main program consists of declaration statements and executable statements. Our convention and style requirements will be to first have all declarative statements before any executable statements. You will get the hang of this as we get more familiar with how C++ programs work.

 

      Every program that you write must have a main program. This tells the C++ compiler where execution will begin.

 

      The body of a main program is enclosed in curly brackets {}. For those of you familiar with Pascal this is equivalent to the main program's BEGIN...END pair.

 

• Concerning style, it is my preference to have each opening brace ({) and each closing brace (}) on a separate line - and lined up with one another (like the begin and end in Pascal).

 

      A simple program looks like this…notice how much is lower case. This is important!

            //This is a program comment that describes what this program will do

            #include <iostream>

            using namespace std;

 

            int main()

            {

                        //Body of the program

                        return 0;

            }

 

• The declarations are where you define what variables and constants you will be using in your program...more about this later. The executable statements are the instructions that the computer carries out. They tell the CPU which actions to take, step by step.

 

• In the languages we will be learning, the implementation-part is always surrounded by { and }.

 

• C programs are similar, except we use a different library to include (C doesn’t have all of the libraries that C++ has available)

 

      A simple program looks like:

 

           /* This is a block comment to describe the purpose of this program */

            #include <stdio.h>

            int main()

            {

                        //Body of the program

                        return 0;

 

     

            }

 

 

• The specification of an action is called an executable statement. The most elementary statements are assignment statements; this is where you assign a value to a variable. A sample assignment statement is:

 

            my_age = 23;

 

• There must be semicolons at the end of each statement...they are used to separate the statements.

 

·         At this point I want to emphasize that these languages are all case-sensitive. You must enter upper or lower case letters exactly as they appear. “main” can’t be capitalized or in all caps. It must be lower case. In fact, all “commands” (called operations) must be lower case. On the other hand, these languages are free form in their layout. This gives us the opportunity to design them and create a style that works well for us. We are not restricted to putting pieces in certain columns or to count the number of spaces from one item to the next. But, we want to create a format that is easy to read and maintain (so we can make modifications to the program easily in the future). We will look at a variety of styles this term to create a style sheet that makes sense for us!

·         There is a concept of whitespace that we should learn about. Whitespace is either a space, a tab, a newline, etc. Visually it separates one item from the next and is treated all under the category of whitespace.

·         As your first assignment (non-graded). Type in the following C++ program and get it to work: (call it test.cpp)

 

/* This is a test of entering and compiling a program */

/* It will ask for my name and display it with a message */

#include <iostream>

#include <String>

using namespace std;

int main()

{

      //we need some memory to hold our name

      string my_name; 

 

      //Prompt for the user’s name

      cout <<” Please type in your name, followed by the enter key ”;  

      cin >> my_name;                                                                            

 

      //Output the name in a message

     cout <<”Welcome “ <<my_name <<” to CS161!” <<endl;

      return 0;

}

 

·         Let’s talk about style for a minute. The same program without comments or spaces would be: (it would function the same…but who could read it?)

 

#include <iostream>

using namespace std;

int main() { string my_name; 

cout <<” Please type in your name, then hit enter ”; cin >> my_name;              

cout <<”Welcome “ <<my_name <<” to CS161!” <<endl;  return 0; }

 

·         Seriously!  Now play with the spaces inside the double quotes. See how important they are. Does the output look good or is it hard to read?

 

·         Here is another C++ example; you don’t have to type this one in!

 

      //Add comments documenting the purpose of the program

      //Place your name, program number, date, and class here too

 

      #include <iostream>

      using namespace std;

      int main()

      {

            //Declaration part:

            float inches;   //Input: number of inches to convert

            float mm;                   //Output (result): millimeters

 

            //Executable part:

            //First, announce purpose of the program

            cout << "Converting inches to millimeters" << endl;

 

            //Then, Get the number of inches from the keyboard

            cout << "Number of inches?" << endl;

            cin >> inches;

 

            //Process: Convert inches to millimeters

            mm = 25.4 * inches;

 

            //Display the Results

            cout <<inches <<" inches equals " <<mm <<" millimeters" <<endl;

 

            return 0;

      }

 

      Here is some sample output:

      %g++ prog1.cpp

      %./a.out

      Converting inches to millimeters

      Number of inches?

      30                          <-- user enters

      30 inches equals 762 millimeters

 

      %./a.out

      Converting inches to millimeters

      Number of inches?

      10.2                                   <-- user enters

      10.2 inches equals 259.08 millimeters

 

      %./a.out

      Converting inches to millimeters

      Number of inches?

      -5.101                                <-- user enters

      -5.101 inches equals -129.565 millimeters

 

 

• The compiler directive (header file to be included) is:

            #include <iostream >

            using namespace std;

 

      The iostream allows us to access the cout (pronounced "see-out") and cin (pronounced "see-in") C++ functions to output information to the terminal and to read information from the keyboard. Remember that C++ is case sensitive...so to interact with the terminal you use cout and cin not COUT or CIN.

 

• This program only consists of a main program...so we start off with:

            int main()

 

      And, the body of the program is enclosed by { and }.

 

• Next comes the definition part. Here is where we declare our variables. We are using two variables that are real numbers; C++ calls these floats. Their values can be changed by the program while it is running. Each declaration must be followed by a semicolon.

 

      The declaration portion is where you list all of the variables you need in your program. You should pick variable names that have meaning so that you can easily look at your program and quickly understand what it is trying to accomplish.

 

      In this program we are using two real numbers. A real number is something like 3.14 or 40.5 -- a number with a fractional component. Other variables can be integers (whole numbers) or characters (eg., "a" through "z").

 

      In a variable declaration, you first list the data type; this is a reserved work (eg., float, char, int). Then, list the variable names to which you want memory allocated. The reserved word float indicates that the variable names listed after it will have enough memory associated with them to hold a number with a decimal point:

                        float real_one, real_two, real_three;

      Notice, the statement is terminated with a semicolon.

 

      The reserved word int indicates that the variable names listed after it will have enough memory associated with them to hold a whole number...of limited range:

                        int whole_one, whole_two, whole_three;

 

• After the declarations are the executable statements, which are the instructions to the CPU. These statements are executed in the order in which they are listed. The statements that make up the sequence must be separated by semicolons.

 

• Scattered throughout the program are comments (started with //). These tell the programmer (or teacher!) what the next few lines of code are supposed to accomplish. They help the person reading the code understand the program. It is also good to put your pseudo code in comments to let the reader understand your original algorithm.

 

• The computer cannot manipulate information unless we first store data in its memory. One way to do that is to read the data into memory...by entering it in from the keyboard. Then, the results of a program's execution can be displayed on your terminal by an output operation. All input and output in C++ is performed by functions provided for outside of the language itself. In this class we will use the functions provided in the iostream header file; cout is used to print prompts (prompting the user to do something):

                        cout <<"This is a prompt";

 

      To terminate a line, use endl (pronounced end-line); this will cause the cursor to advance to the next line on your screen:

                        cout <<"This is another prompt" <<endl;

 

      The << symbols simply mean that you are directing information out to the screen. You must use them with each prompt you want to appear on the screen.

 

Putting the Pieces Together

• Now you know enough to start writing your own program. Remember to do this, we must design our programs to have all of the right pieces. Programs have:

            1) Compiler Directives        #include <iostream>

                                                            using namespace std;

            2) Main Program                  int main()

            3) Program Body                  {

     

                        Declarations                          float a_real, twice;

                                                                                    int    an_int;

                                                                                    char  a_char;

 

                        Executable Statements:

                                    prompts                                 cout <<"enter a real number\n";

                                    input                                      cin >>a_real;

                                    echo                                        cout <<"you entered: " <<a_real;

                                    output a blank line              cout <<endl;

 

                                    assignment                            twice = a_real * 2.0;

                                                                                    return 0;

                                                                        }

 

            4) The body of the program is surrounded by { and }

                        Each statement must be separated by a semicolon.