Computer Programming Slide 4
Computer Programming Slide 4
Lecture 1V
Anup Majumder
Assistant Professor
Department Of Computer Science and Engineering
Jahangirnagar University
Very brief history of C++
2
Display 1.1
A Sample C++ Program (1 of 2)
▪ cout is the object that writes to the stdout device, i.e. the console
window.
▪ It is part of the C++ standard library.
▪ Without the “using namespace std;” line this would have been called as
std::cout. It is defined in the iostream header file.
▪ << is the C++ insertion operator. It is used to pass characters from the
right to the object on the left. endl is the C++ newline character.
Header Files
1-10
Data Types:
Display 1.2 Simple Types (2 of
2)
1-11
Assigning Data: Shorthand
Notations
• Display, page 14
Display 1.3
Some Escape Sequences (1 of 2)
1-13
Display 1.3
Some Escape Sequences (2 of 2)
1-14
Arithmetic Operators:
Display 1.4 Named Constant (1
of 2)
• Standard Arithmetic Operators
– Precedence rules – standard rules
1-15
Arithmetic Operators:
Display 1.4 Named Constant (2
of 2)
1-16
17
Conditional Structure
18
Conditional Structure
19
The while Repetition
Structure
• Repetition structure
– Programmer specifies an action to be repeated while
some condition remains true
– Psuedocode
while there are more items on my shopping list
Purchase next item and cross it off my list
– while loop repeated until condition becomes false.
• Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;
The while Repetition
Structure
• Flowchart of while loop
true
condition statement
false
int x = 2;
while (x >= 0){
if ( x == 2){
cout << “Value of x is : “ << x <<
endl;
}
x = x – 1;
}
• Common errors:
– infinite loop
– unitialized variables
char s;
while (!cin.eof( )) {
cin >> s;
cout << s << endl;
}
Formulating Algorithms
(Counter-Controlled
Repetition)
• Counter-controlled repetition
– Loop repeated until counter reaches a certain value.
• Definite repetition
– Number of repetitions is known
• 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.
Formulating Algorithms
(Counter-Controlled
Repetition)
• Pseudocode for example:
Set total and grade counter to zero
While grade counter <= 10
Input the next grade
Add the grade into the total
grade counter++
average = total divided / 10
Print the class average
Program Output
Assignment Operators
• Assignment expression abbreviations
c = c + 3; can be abbreviated as c += 3; using the
addition assignment operator
• Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
• Examples of other assignment operators include:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
Increment and Decrement
Operators
• Increment operator (c++) - can be used instead of
c += 1
• Decrement operator (c--) - can be used instead of
c -= 1
• Preincrement
• When the operator is used before the variable (++c or –c)
• Variable is changed, then the expression it is in is evaluated.
• Postincrement
• When the operator is used after the variable (c++ or c--)
• Expression the variable is in executes, then the variable is changed.
• If c = 5, then
– cout << ++c; prints out 6 (c is changed before cout is
executed)
– cout << c++; prints out 5 (cout is executed before the
increment. c now has the value of 6)
• When Variable is not in an expression
– Preincrementing and postincrementing have the same effect.
++c;
cout << c;
and
c++;
cout << c;
have the same effect.
Essentials of
Counter-Controlled
• Repetition
Counter-controlled repetition requires:
– The name of a control variable (or loop counter).
– The initial value of the control variable.
– The condition that tests for the final value of the control
variable (i.e., whether looping should continue).
– The increment (or decrement) by which the control variable
is modified each time through the loop.
• Example:
int counter =1; //initialization
while (counter <= 10){ //repetitio
// condition
cout << counter << endl;
++counter; //increment
}
The for Repetition Structure
Initialize variable
Condition true
statement
Test the variable Increment variable
false
• Program to sum the even numbers from 2 to 100
1 // Fig. 2.20: fig02_20.cpp
2 // Summation with for
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 int sum = 0;
11
12 for ( int number = 2; number <= 100; number += 2 )
13 sum += number;
14
15 cout << "Sum is " << sum << endl;
16
17 return 0;
18 }
Sum is 2550
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:
statement if (expression == val1)
break; statement
case val2: else if (expression==val2)
statement statement
break; ….
….
else if (expression== valn)
case valn: statement
statement else
break; statement
default:
statement
break;
}
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)
1 // Fig. 2.22: fig02_22.cpp
2 // Counting letter grades
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int main()
10 {
11 int grade, // one grade
12 aCount = 0, // number of A's
13 bCount = 0, // number of B's
14 cCount = 0, // number of C's
15 dCount = 0, // number of D's
16 fCount = 0; // number of F's
17
18 cout << "Enter the letter grades." << endl
19 << "Enter the EOF character to end input." << endl;
20
21 while ( ( grade = cin.get() ) != EOF ) {
22 Notice how the case statement is used
23 switch ( grade ) { // switch nested in while
24
25 case 'A': // grade was uppercase A
26 case 'a': // or lowercase a
27 ++aCount;
28 break; // necessary to exit switch
29
30 case 'B': // grade was uppercase B
31 case 'b': // or lowercase b
32 ++bCount;
33 break;
34
35 case 'C': // grade was uppercase C
36 case 'c': // or lowercase c
37 ++cCount;
38 break;
39
40 case 'D': // grade was uppercase D
break causes switch to end and
41 case 'd': // or lowercase d
42 ++dCount; the program continues with the first
43 break; statement after the switch
44 structure.
45 case 'F': // grade was uppercase F
46 case 'f': // or lowercase f
47 ++fCount;
48 break;
49
50 case '\n': // ignore newlines,
51 case '\t': // tabs,
52 case ' ': // and spacesNotice the default
in input statement.
53 break;
54
55 default: // catch all other characters
56 cout << "Incorrect letter grade entered."
57 << " Enter a new grade." << endl;
58 break; // optional
59 }
60 }
61
62 cout << "\n\nTotals for each letter grade are:"
63 << "\nA: " << aCount
64 << "\nB: " << bCount
65 << "\nC: " << cCount
66 << "\nD: " << dCount
67 << "\nF: " << fCount << endl;
68
69 return 0;
70 }
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
} while ( condition );
• Example (letting counter = 1):
true
do {
condition
cout << counter << " ";
} while (++counter <= 10); false
Enter grade, -1 to end: 75 ios::showpoint - forces decimal point and trailing zeros, even
gradeCounter is an
Enter grade, -1 to end: 94 if but
int, it gets promoted
unnecessary: to
setprecision(2)
66 printed as 66.00 - prints only two digits
double.
Enter grade, -1 to end: 97 past decimal point.
Enter grade, -1 to end: 88
Enter grade, -1 to end: 70 | - separates multiple option.
Enter grade, -1 to end: 64 Programs that use this must include
Enter grade, -1 to end: 83 <iomanip>
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50
Nested control structures
• Problem:
A college has a list of test results (1 = pass, 2 = fail)
for 10 students. Write a program that analyzes the
results. If more than 8 students pass, print "Raise
Tuition".
• We can see that
– The program must process 10 test results. A
counter-controlled loop will be used.
– Two counters can be used—one to count the number
of students who passed the exam and one to count the
number of students who failed the exam.
– Each test result is a number—either a 1 or a 2. If the
number is not a 1, we assume that it is a 2.
Nested control structures
using std::cout;
using std::endl;
using std::ios;
#include <iomanip>
using std::setw;
using std::setiosflags;
using std::setprecision;
#include <cmath>
int main()
{
double amount, // amount on deposit
principal = 1000.0, // starting principal
rate = .05; // interest rate
return 0;
}