Intro To Computer Programming Lecture 4
Intro To Computer Programming Lecture 4
Programing
ECEG-1052
Lecture 04
1 / 17
Recap
• Variables: definition, naming,
declaration, initialization
• Data types in C++
• Operators in C++: definition,
types
• Expressions: definition, types,
precedence of operators in
expressions
• Characters and strings
• Type casting ( data type coercion)
2 / 17
1 // basic structure of C++ program
6 {
preprocessor directive
7 cout << "Welcome to C++!\n"; Do not use ; at end of #include statement
8 Message
C++ to thecontain
programs C++ preprocessor
one or more functions,
9 return 0; // indicate that exactly
Lines
program one of which
beginning
ended must bepreprocessor
with # are
successfully main directives
10 }
Parenthesis
#include used to indicate a function
<iostream> tells the preprocessor
to include
int means the
thatcontents of the file
main "returns" an integer value.
<iostream>,
which
More in includes input/output operations (such as
functions.
Welcome to C++! printing to the screen).
Prints the string of characters contained between the
return is one a way toquotation
exit a marks.
function. Left brace { begins the body of every function
The entire line, including cout, the << operator, the
return 0, in this case,string
means"Welcome
that and a right brace } ends it
to C++!\n" and the semicolon
the program terminated normally.
(;), is called a statement.
5
namespace and Using cin
and cout in a Program
• cin and cout are declared in the header file
iostream, but within std namespace
• To use cin and cout in a program, use the
following two statements:
#include <iostream>
using namespace std;
6
A Simple Program: Printing a Line of
Text
• std::cout
• standard output stream object
• “connected” to the screen
• <<
• stream insertion operator
• value to the right of the operator (right operand) inserted into
output stream (which is connected to the screen)
cout << " Welcome to C++!\n"
•\
• escape character
• indicates that a “special” character is to be output
A Simple Program: Printing a Line of
Text (II)
Escape Sequence Description
3 #include <iostream>
5 int main()
6 {
11 }
Welcome to C++!
3 #include <iostream>
5 int main()
6 {
10 }
Welcome
to
C++!
3 #include <iostream>
using namespace std;
4
5 int main()
6 {
7 cout << “\” Time is’t the main thing. It’s the only thing\” Miles Davis. \n";
10 }
11 / 17
Another Simple Program: Adding Two
Integers (II)
Enter first integer Variables can be output using cout << variableName
45
Enter second integer
72
Sum is 117
Example Program – Use of cout to prompt user to enter some data
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "What is your name? ";
cin >> name;
#include <iostream>
#include <string>
using namespace std;
int main() {
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
return 0;
}
Types of Errors
• 3 types of Errors
1 #include <iostream>
2
3 using namespace std;
4
5 int main()
6 {
7 cout << "Hello, World!" << endl
8 return 0;
9 }
Issues due to case changing or dropping characters:
You must define a variable before you use it for the first time.
cout << "Please enter your last three test scores: ";
int s1;
int s2;
int s3;
cin >> s1 >> s2 >> s3;
double average = (s1 + s2 + s3) / 3;
cout << "Your average score is " << average << endl;
(-(b * b - 4 * a * c) / (2 * a)
Syntax Error – un-initialization of constants
return 0;
}
How you fix it?
Basics of Control Structures in
Programing
• Sequential execution
• Statements executed in order
• Transfer of control
• Next statement executed not next one in sequence
• 3 control structures
• Sequence structure
• Programs executed sequentially by default
• Selection structures
• if, if/else, switch
• Repetition structures
• while, do/while, for
• Design Issues:
• “if-then-else” statement
• syntax:
if (boolean_expr)
statement;
else
statement;
• The statements could be single or compound
if Selection Structure Example
• Example code fragment using C++
If student’s grade is greater than or equal to 60
Print “Passed”
if ( grade >= 60 )
cout << "Passed";
if Selection Structure Example
contd…
• if/else
• A different action is performed when condition is true
and when condition is false
• Psuedocode
if student’s grade is greater than or equal to 60
print “Passed”
else
print “Failed”
• C++ code fragment
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
32 / 17
if/else Selection Structure
false true
grade >= 60
if ( grade >= 60 )
cout << "Passed.\n";
else {
cout << "Failed.\n";
cout << "You must take this course
again.\n";
}
• Without braces,
cout << "You must take this course again.\
n";
always executed
• Block
• Set of statements within braces
Nested if statement
statement1
Statement 2b Statement 2a
else
statement2b
statement3
Statement 3
37
Nested if statement
if (a==1) if (a==1)
if (b==2) if (b==2)
cout << “***\n”; cout << “***\
else n”;
cout << “###\n”; else
cout << “###\
n”;
38
More Example on Nested-if
40
The switch Multiple-Selection Structure
• switch
• Useful when variable or expression is tested for
multiple values
• Consists of a series of case labels and an optional
default case
• break is (almost always) necessary
switch (expression) {
case val1:
break;
}
The switch Statement
5-43
flowchart
true
case a case a action(s) break
false
true
case b case b action(s) break
false
.
.
.
true
case z case z action(s) break
false
default action(s)
Example
#include <iostream>
using namespace std;
void main(){
int x=0;
switch (x){
case 0:
cout << “Zero”;
x=1;
break; /* no braces is needed */
case 1:
cout << “One”;
break;
case 2:
cout << “Two”;
break;
default:
cout << “Greater than two”;
} //end switch
}
45
1 // example code to demonstrate swich statement
2 // Counting letter grades
3 #include <iostream>
4 using namespace std;
5 int main()
6 {
7 int grade, // one grade
8 aCount = 0, // number of A's
9 bCount = 0, // number of B's
10 cCount = 0, // number of C's
11 dCount = 0, // number of D's
12 fCount = 0; // number of F's
13
14 cout << "Enter the letter grades." << endl
15 << "Enter the EOF character to end input." << endl;
16
17 while ( ( grade = [Link]() ) != EOF ) {
18
Notice how the case statement is used
19 switch ( grade ) { // switch nested in while
20 case 'A': // grade was uppercase A
21 case 'a': // or lowercase a
22 ++aCount;
23 break; // necessary to exit switch
27 break;
28 case 'C': // grade was uppercase C
29 case 'c': // or lowercase c
30 ++cCount;
31 case 'D': // grade was uppercase D
32 case 'd': // or lowercase d break causes switch to end and
33 ++dCount; the program continues with the first
34 break; statement after the switch
35 structure.
case 'F': // grade was uppercase F
36 case 'f': // or lowercase f
37 ++fCount;
38 break;
39 case '\n': // ignore newlines,
40 case '\t': // tabs,
41 Notice the default
case ' ': // and spaces in input statement.
42 break;
43 default: // catch all other characters
44 cout << "Incorrect letter grade entered."
45 << " Enter a new grade." << endl;
46 break; // optional
47 }
48 }
49 cout << "\n\nTotals for each letter grade are:"
50 << "\nA: " << aCount
51 << "\nB: " << bCount
52 << "\nC: " << cCount
53 << "\nD: " << dCount
54 << "\nF: " << fCount << endl;
55 return 0;
Enter the letter grades.
Enter the EOF character to end input.
a
B
c
C
A
d
f
C
E
Incorrect letter grade entered. Enter a new grade.
D
A
b
Program Output
A: 3
B: 2
C: 3
D: 2
F: 1
Repetition structures (LOOPs)
49 / 17
The while Loop
• The general form of the while statement is:
while (expression)
statement;
while is a reserved word
• Statement can be simple or compound
• Expression acts as a decision maker and is usually a
logical expression
• Statement is called the body of the loop
• The parentheses are part of the syntax
50
The while Loop
(continued)
• Expression provides an entry condition
51
The while Loop (continued)
52
Counter-Controlled while Loops
• If you know exactly how many pieces of data need
to be read, the while loop becomes a counter-
controlled loop
• Example
56
Sentinel-Controlled while
Loops
• Sentinel variable is tested in the condition and
loop ends when sentinel is encountered
57
Flag-Controlled while
Loops
• A flag-controlled while loop uses a bool variable to
control the loop
• The flag-controlled while loop takes the form:
58
Infinite Loops
• The body of a while loop eventually must make the
condition false
• If not, it is called an infinite loop, which will execute
until the user interrupts the program
• This is a common logical error
• You should always double check the logic of a program
to ensure that your loops will terminate normally
5-59
Infinite Loops
• An example of an infinite loop:
int count = 1;
while (count <= 25)
{
cot<<count;
count = count - 1;
}
5-60
Nested While Loops
• How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
cout<<"Here \n";
count2++;
}
count1++;
}
5-61
The for Loop
statement;
• The initial statement, loop condition, and update
statement are called for loop control statements
62
The for loop executes as follows:
1. The initial statement executes.
2. The loop condition is evaluated. If the loop condition
evaluates to true
i. Execute the for loop statement.
ii. Execute the update statement (the third expression
in the parentheses).
3. Repeat Step 2 until the loop condition evaluates to
false.
67
Multiple variable
initialization
• Initialization and increment
• For multiple variables, use comma-separated lists
for (int i = 0, j = 0; j + i <= 10; j++, i++)
cout << j + i << endl;
68
The do…while Loop
• The general form of a do...while statement is:
do
statement;
while (expression);
• The statement executes first, and then the
expression is evaluated
• If the expression evaluates to true, the statement
executes again
• As long as the expression in a do...while
statement is true, the statement executes
70
The do…while Loop
(continued)
• To avoid an infinite loop, the loop body must
contain a statement that makes the expression
false
• The statement can be simple or compound
• If compound, it must be in braces
• do...while loop has an exit condition and
always iterates at least once (unlike for and
while)
71
break & continue Statements
75
break & continue Statements (continued)
76
Break example
• Break Logic
• Execution of a break ; statement at any location in a
loop-structure causes immediate exit from the loop-
structure
• Produces output : 0, 1, 2, 3, 4
break & continue
Statements (continued)
• continue is used in while, for, and do…
while structures
78
Continue Example
• Continue Logic
• Execution of a continue ; statement at any location
in a loop-structure causes execution to continue at
the beginning of the loop structure (at the next loop
iteration) while skipping the remaining statements.
• Produces output : 0, 1, 2, 4
Nested for loop
• Suppose we want to create the following pattern
*
**
***
****
*****
• In the first line, we want to print one star, in the
second line two stars and so on
80
Nested Control Structures (continued)
81
Nested Control Structures
(continued)
• The syntax is:
for (i = 1; i <= 5 ; i++)
{
for (j = 1; j <= i;
j++)
cout << "*";
cout << endl;
}
82
Nested Control Structures
(continued)
• What pattern does the code produce if we replace
the first for statement with the following?
for (i = 5; i >= 1; i--)
• Answer:
*****
****
***
**
*
83
Nested Control Structures
(continued)
• What if you want to display?
*
* *
* * *
* * * *
* * * * *
84
Example code on control structure
• Example
A class of ten students took a quiz. The
grades (integers in the range 0 to 100) for
this quiz are available to you. Determine the
class average on the quiz.
85
// Class average program with counter-controlled repetition.
#include <iostream>
using namespace std;
// initialization phase
total = 0; // initialize total
gradeCounter = 0; // initialize loop counter
86
// processing phase fig02_07.cpp
(2 of 2)
87
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
88
more example on control strucutres
89
// Class average program with sentinel-controlled repetition.
#include <iomanip>
using namespace std;
// initialization phase
total = 0; // initialize total
90
gradeCounter = 0; // initialize loop counter
// processing phase
// get first grade from user
cout << "Enter grade, “ << SENTINEL << “ to end: "; // prompt for input
cin >> grade; // read grade from user
cout << "Enter grade, “ << SENTINEL << ” to end: "; // prompt for input
cin >> grade; // read next grade
} // end while
// termination phase
// if user entered at least one grade ...
if ( gradeCounter != 0 ) {
// calculate average of all grades entered
average = ( double )( total ) / gradeCounter;
91
// display average with two digits of precision
cout << "Class average is " << setprecision( 2 )<< average << endl;
93
// Analysis of examination results.
#include <iostream>
using namespace std;
const int MAX_STUDENTS = 10; const int MIN_PASSES = 8;
const int PASS = 1; const int FAIL = 2;
// function main begins program execution
int main()
{
// initialize variables in declarations
int passes = 0; // number of passes
int failures = 0; // number of failures
int studentCounter = 0; // student counter
int result; // one exam result
} // end while