CSC 113 COMPUTER PROGRAMMING THEORY 03 LAB 01
CSC 113: COMPUTER PROGRAMMING (THEORY = 03, LAB = 01) Momina Moetesum Computer Science Department Bahria University, Islamabad
INTRODUCTION TO C++ PROGRAMMING Week # 2
3 BASICS OF A TYPICAL C++ ENVIRONMENT Phases of C++ Programs: 1. Edit 2. Preprocess 3. Compile 4. Link 5. Load 6. Execute C++ systems generally consist of three parts: • Program-development environment • Language • C++ Standard Library
BASICS OF A TYPICAL C++ ENVIRONMENT Editor Program is created in the editor and stored on disk. Disk Preprocessor program processes the code. Disk Compiler Disk Linker Disk Primary Memory Loader Disk . . . CPU Compiler creates object code and stores it on disk. Linker links the object code with the libraries, creates an executable file and stores it on disk Loader puts program in memory. Primary Memory . . . CPU takes each instruction and executes it, possibly storing new data values as the program executes.
5 BASICS OF A TYPICAL C++ ENVIRONMENT Input/output � cin Standard input stream Normally keyboard � cout Standard output stream Normally computer screen � cerr Standard error stream Display error messages Execution time errors � Fatal runtime error � Non-fatal runtime error
INTRODUCTION Before writing a program: � Have a thorough understanding of problem � Carefully plan your approach for solving it While writing a program: � Know what “building blocks” are available � Use good programming principles 6
ALGORITHMS All computing problems � can be solved by executing a series of actions in a specific order Algorithm �A procedure determining the Actions to be executed Order in which these actions are to be executed Program control � Specifies the order in which statements are to executed 7
PSEUDOCODE Pseudocode � Artificial, informal language used to develop algorithms � Similar to everyday English � Not actually executed on computers � Allows us to “think out” a program before writing the code for it � Easy to convert into a corresponding C++ program � Consists only of executable statements 8
INTRODUCTION TO C++ PROGRAMMING C++ language � Facilitates a structured and disciplined approach to computer program design 9
1 // Fig. 1. 2: fig 01_02. cpp 2 // A first program in C++ Comments Written between /* and */ or following a //. 3 #include <iostream> 1. Comments 4 5 int main() Improve program readability and do not cause the computer to perform any action. 2. Load <iostream> 6 { preprocessor directive 3. main Message to the C++ preprocessor. 7 std: : cout << "Welcome to C++!n"; Lines beginning with # are preprocessor 3. 1 Print "Welcome to 8 directives. C++n" #include <iostream> tells the preprocessor 9 return 0; // indicate that program to include the contents of the file <iostream>, ended successfully 10} C++ programs one oroperations more functions, 3. 2 exit (return 0) which includescontain input/output (such as one of which must be main printing to the screen). Parenthesis are used to indicate a function Welcome to C++! int means that main "returns"Program an integer value. Output Prints the string of characters contained More in Chapter 3. between the quotation marks. return is a way to exit a function from a function. A leftstd: : cout, brace { begins The entire line, including thethe << body of every return 0, in this case, means function andto a right brace and } ends it. operator, the string "Welcome C++!n" that the program terminated the semicolon (; ), is called a statement. normally. All statements must end with a semicolon. 10
PARTS OF PROGRAM Comments: � // single-line comment � /* ---- */ multi-line comment Good programming practice � Every program should begin with a comment that describes the purpose of the program, author, data and time.
PARTS OF PROGRAM Preprocessor Directives: � Lines that begin with # are processed by the preprocessor before the program is compiled. � E. g. including header files Common programming error � Forgetting to include required headerfiles.
PARTS OF PROGRAM White spaces: � Blank lines / space characters / tab characters � Ignored by compiler Good programming practice: � Use white spaces to enhance program readability.
PARTS OF PROGRAM Main function: � C++ programs begin executing at main. � Int main () Return statement mandatory Return 0 // indicates that program ended successfully � Void main () Return not required � Delimiters {} � Statements & Semicolon (; ) Common Programming Error � Missing a semicolon after statements � Adding semicolons where not required
PARTS OF PROGRAM std: : cout � Standard output stream object � “Connected” to the screen � std: : specifies the "namespace" to which cout belongs std: : can be removed through the use of using statements << � Stream insertion operator � Value to the right of the operator (right operand) inserted into output stream (which is connected to the screen) � std: : cout << “Welcome to C++!n”; � Escape character � Indicates that a “special” character is to be output 15
ESCAPE CHARACTERS & ESCAPE SEQUENCE 16
MODIFYING C++ PROGRAM Printing a single line of text with multiple statements
1 // Fig. 1. 4: fig 01_04. cpp 2 // Printing a line with multiple statements 3 #include <iostream> 4 5 int main() 6 { 7 std: : cout << "Welcome "; 8 std: : cout << "to C++!n"; 9 10 return 0; // indicate that program ended successfully 11} 1. Load <iostream> 2. main 2. 1 Print "Welcome" 2. 2 Print "to C++!" 2. 3 newline 2. 4 exit (return 0) Welcome to C++! Program Output Unless new line 'n' is specified, the text continues on the same line. 18
MODIFYING C++ PROGRAM Printing multiple lines of text with a single statement
1 // Fig. 1. 5: fig 01_05. cpp 2 // Printing multiple lines with a single statement 3 #include <iostream> 4 1. Load <iostream> 2. main 5 int main() 6 { 2. 1 Print "Welcome" 7 std: : cout << "Welcomentonn. C++!n"; 2. 2 newline 8 9 return 0; // indicate that program ended 2. 3 Print "to" successfully 10} 2. 4 newline Welcome to C++! 2. 5 newline 2. 6 Print "C++!" Multiple lines can be printed with one statement. 2. 7 newline 2. 8 exit (return 0) 20 Program Output
SELF PRACTICE EXAMPLES Print the message “This is a C++ program” on one line. Print the message “This is a C++ program” on two lines, end first with C++. Print the message “This is a C++ program” with each word on a separate line. Print the message “This is a C++ program”. Separate each word from the next by a tab.
ADDING TWO INTEGERS Variables � Location in memory where a value can be stored for use by a program � Must be declared with a name and a data type before they can be used � Some common data types are: int - integer numbers char - characters double - floating point numbers � Example: Declares a variable named myvariable of type int � Example: int myvariable; int variable 1, variable 2; Declares two variables, each of type int 22
MEMORY CONCEPTS Variable names Correspond to locations in the computer's memory � Every variable has a name (identifier), a type, a size and a value � Whenever a new value is placed into a variable, it replaces the previous value - it is destroyed � Reading variables from memory does not change them � number 1 45 number 2 72 sum 117 Common Programming Errors � � Forgetting to declare a variable Using C++ keywords as identifiers 23
C++ KEYWORDS � Cannot be used as identifiers or variable names. 24
1 // Fig. 1. 6: fig 01_06. cpp 2 // Addition program 3 #include <iostream> 1. Load <iostream> 4 5 int main() 2. main 6 { 7 integer 1, integer 2, sum; // 2. 1 Initialize variables 8 declaration integer 1, 9 std: : cout << "Enter first integern"; // integer 2, and sum Notice how std: : cin is used to get user 10 std: : cin >> integer 1; // prompt input. 11 std: : cout << "Enter second integern"; // 2. 2 Print "Enter read an integer first integer" 12 std: : cin >> integer 2; // prompt 13 sum = integer 1 + integer 2; // 2. 2. 1 Get input read an integer 14 std: : cout << "Sum is " << sum << std: : endl; assignment of sum 2. 3 Print "Enter 15 // print sum second integer" std: : endl flushes the buffer and 16 return 0; // indicate that program ended prints a newline. 2. 3. 1 Get input 17} successfully 2. 4 Add variables and Enter first integer Variables can be output using std: : cout << variable. Name. put result into sum 45 2. 5 Print "Sum is" Enter second integer 2. 5. 1 Output sum 72 Sum is 117 25 2. 6 exit (return 0) Program Output
PARTS OF PROGRAM >> (stream extraction operator) � When used with std: : cin, waits for the user to input a value and stores the value in the variable to the right of the operator � The user types a value, then presses the Enter (Return) key to send the data to the computer � Example: int my. Variable; std: : cin >> my. Variable; Waits for user input, then stores input in my. Variable = (assignment operator) � Assigns value to a variable � Binary operator (has two operands) � Example: sum = variable 1 + variable 2; 26
SELF PRACTICE EXAMPLES Declare the variables c, this. Is. AVariable, q 76354 and number to be of type int. Prompt the user to enter an integer. End your prompting message with a colon (: ) followed by a space. Read an integer from the user at the keyboard and store it in an integer variable age.
ARITHMETIC Arithmetic calculations Single-line form � Use * for multiplication and / for division � � Integer division truncates remainder � Modulus operator returns the remainder 7 / 5 evaluates to 1 7 % 5 evaluates to 2 Operator precedence � Some arithmetic operators act before others (i. e. , multiplication before addition) � Be sure to use parenthesis when needed Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: (a + b + c ) / 3 28
ARITHMETIC OPERATORS Rules of operator precedence: 29
ALGEBRA VS C++ EXPRESSIONS Example 1 Example 2 Algebra � z-=pr%q � Y=mx+b C++ Expression � Y=m*x +b Algebra + w/x - y C++ Expression � Z=p � 1 * � 2 % � 3 / � 4 + � 5 – � 6 = *r%q+w/x–y
ALGEBRA VS C++ EXPRESSIONS Example 3 Algebra � Y= a x^2 + bx + c C++ Expression � Y= a*x*x +b*x+c � Redundant parenthesis � Y = (a * x) + (b * x) + c
STATE ORDER OF EVALUATION A) x = 7 + 3 * 6 / 2 – 1; B) x = 2 % 2 + 2 * 2 – 2 / 2; C) x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) );
ASSUME X = 2 AND Y = 3 PRINT OUTPUT IF ANY ELSE WRITE NO OUTPUT Code 1. 2. 3. 4. 5. 6. 7. 8. 9. cout << x; cout << x + x; cout << “x = “<<x; cout << x + y <<“ = “ << y+x; z = x + y; cout << z; // cout << “ x+y = “ << x + y; cout<< x <<“n”<<y; Output
SELF PRACTICE PROGRAMMING EXAMPLE Algorithm C++ Program State that program calculates the product of three integers. Declare the variables x, y, z and result to be of type int. Prompt the user to enter three integers. Read the three integers from the keyboard and store them in variables x, y, z. Compute the product of the three variables and assign it to the variable result. Print “The product is “ followed by the value of result. Return a value from main indicating that the program terminated successfully.
INTRODUCTION TO TYPE CASTING A character can be printed by enclosing it in single quotes. � cout << ‘A’; Or store it in char variable. � char var; � var = ‘A’; In order to print its ASCII equivalent integer value we use static_cast: � cout << int(‘A’); � cout<< int(var); � cout << (int)‘A’; � cout<< (int)var; 65 65
- Slides: 35