You are on page 1of 30

Lecture 8

Introduction to Computer
Programming

Jehangir Arshad Meo

Mechanical Engineering Department


COMSATS Institute of Information and Technology Sahiwal
Repetition Structures:
 Loop/ Repetition:
 Group of instructions computer executes repeatedly while some condition remains true
 Counter-controlled repetition:
 Definite repetition - know how many times loop will execute
 Control variable used to count repetitions
 Sentinel-controlled repetition:
 Indefinite repetition
 Used when number of repetitions not known
 Sentinel value indicates "end of data“.
Suppose problem becomes:
Develop a class-averaging program that will process an arbitrary number
of grades each time the program is run
– Unknown number of students
– How will program know when to end?
Sentinel value
– Indicates “end of data entry”
– Loop ends when sentinel input
– Sentinel chosen so it cannot be confused with regular input
• -1 in this case
“While” Repetition structure:
Format:

name of a control variable (or loop counter).

initial value of the control variable.

condition that tests for the final value of the control variable
(i.e., whether looping should continue).

increment (or decrement) by which the control variable is


modified each time through the loop.
“While” Repetition structure
Example (counter):
int counter =1; //initialization name/ value

while (counter <= 10) //repetition condition


{
cout<<“The value of Counter is: ”<<counter;
++counter; //increment
}

int counter = 1;

names counter, declares it to be an integer, reserves space for it


in memory, and sets it to an initial value of 1
// code1.cpp
// Class average program with counter-controlled repetition.
#include <iostream>
#include <conio.h>
using std::cout;
using std::cin;
using std::endl;
// function main begins program execution
int main()
{
int total; // sum of grades input by user
int gradeCounter; // number of grade to be entered next
int grade; // grade value
int average; // average of grades
// initialization phase
total = 0; // initialize total
gradeCounter = 1; // initialize loop counter
// processing phase
while ( gradeCounter <= 5 )
{ // loop 5 times
cout << "Enter grade: "; // prompt for input
cin >> grade; // read grade from user
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter
}
// termination phase
average = total / 5; // integer division

// display result
cout << "Class average is " << average << endl;
getch();
return 0; // indicate program ended successfully
} // end function main
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
// code2.cpp
// Class average program with sentinel-controlled repetition.
#include <iostream>
#include <conio.h>
#include <iomanip> // parameterized stream manipulators
using std::cout; using std::cin; using std::endl; using std::fixed;
using std::setprecision; Data type double also used// to
sets numeric output precision
represent floating point numbers.
//function main begins program execution
main()
{
int total, gradeCounter, grade; / / sum of grades

double average; // number with decimal point for average


// initialization phase
total = 0; // initialize total
gradeCounter = 0; // initialize loop counter
// processing phase
// get first grade from user
cout << "Enter grade, -1 to end: "; // prompt for input
cin >> grade; // read grade from user
// loop until sentinel value read from user
while ( grade != -1 )
{
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter
cout << "Enter grade, -1 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 = total / gradeCounter;
// display average with two digits of precision
cout << "Class average is " << setprecision( 2 ) << fixed << average << endl;
} // end if part of if/else
else // if no grades were entered, output appropriate message
cout << "No grades were entered" << endl;
getch();
} // end function main
OUTPUT:
Enter grade, -1 to end: 75
Enter grade, -1 to end: 94
Enter grade, -1 to end: 97
Enter grade, -1 to end: 88
Enter grade, -1 to end: 70
Enter grade, -1 to end: 64
Enter grade, -1 to end: 83
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50
The for Repetition Structure
Format when using for loops
  for ( initialization; loop Continuation Test; increment )
No
statement semicolon
after last
expression
Example:
for( int counter = 1; counter <= 10; counter++ )
cout<<“value of counter is:“<<counter;

Prints the integers from one to ten.


Counter program by using for loop:
// code6.cpp
// Counter-controlled repetition with the for structure.
#include <iostream>
#include <conio.h>
using std::cout;
using std::endl;

// function main begins program execution


main()
{
// Initialization, repetition condition and incrementing
// are all included in the for structure header.

for ( int counter = 1; counter <= 10; counter++ )


cout << counter << endl;

getch();

} // end function main


While or for ???
 The while loop is the more general one  One first basic rule is that you should
because its loop condition is more flexible use the for loop when the number of
and can be more complicated than that of iterations is known.
a for loop. It is used when number of
iterations are not known.

 Syntex  Syntex

initialization; for ( initialization; loop Continuation Test;


while ( loop Continuation Test) increment )
{
statement statement
increment;
}
Assignment operator:
• Assignment expression abbreviations
– Addition assignment operator
c = c + 3; abbreviated to
c += 3;
• Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
• Other assignment operators
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
// code2.cpp
// Program to show the sum of even numbers
#include <iostream.h>
#include <conio.h>
main()
{
int sum=0, number;
for ( number = 2; number <= 100; number +=2)
sum += number;
cout<<"Sum of even number for given condition is:"<<sum;
getch();
}

 
Sum is 2550
The switch/case Multiple-Selection Structure:
Switch:
Useful when a variable or expression is tested for all the values it can
assume and different actions are taken.
Format
 
Series of case labels and an optional default case
switch ( value ){
case '1':
actions
case '2':
actions
default:
actions
}
break; causes exit from structure
The switch Multiple-Selection Structure:

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)
Switch /case :
/* C program to demonstrate the working of switch...case statement */ /* Program to create a simple calculator for addition, subtraction, multiplication and division */
# include <iostream>
# include <conio.h>
using namespace std;
int main()
{
char a;
float num1,num2;
cout<<"Enter a +, - , * or / :\n";
a = getche();
cout<<"\nEnter two operands:\n";
cin>>num1;
cin>>num2;
switch(a) {
case '+':
cout<<"num1+num2="<<num1+num2;
getch();
break;
case '-':
cout<<"num1-num2="<<num1-num2;
getch();
break;
case '*':
cout<<"num1*num2="<<num1*num2;
getch();
break;
case '/':
cout<<"num1/num2="<<num1/num2;
getch();
break;
default:
break;
}
The do/while Repetition Structure

The do/while repetition structure

Similar to the while structure


Condition for repetition tested after the body of the
 
loop is performed
All actions are performed at least once

Format:
do {
statement
} while ( condition );
Good practice to put brackets in, even if not required
The do/while Repetition Structure

• Example (letting counter = 1)


do {
printf( "%d ", counter );
} while (++counter <= 10);
 

Prints the integers from 1 to 10


The do/while Repetition Structure (III)

action(s)

true
condition

false
Do-While Example:
// code10.cpp
// Using the do/while repetition structure.
#include <iostream>

using std::cout;
using std::endl;

// function main begins program execution


int main()
{
int counter = 1; // initialize counter

do {
cout << counter << " "; // display counter
} while ( ++counter <= 10 ); // end do/while
cout << endl;

return 0; // indicate successful termination

} // end function main


The break Statements:

Break:

Causes immediate exit from a while, for, do/while or


switch structure

Program execution continues with the first statement after the


structure

Common uses of the break statement


Escape early from a loop
Skip the remainder of a switch structure
The continue Statements

• Continue

– Skips the remaining statements in the body of a while, for or


do/while structure

• Proceeds with the next iteration of the loop


1 /* Fig. 4.12: fig04_12.c
2 Using the continue statement in a for structure */
3 #include <iostream.h>
4
5 int main() 1. Initialize variable
6 {
7 int x;
2. Loop
8
9 for ( x = 1; x <= 10; x++ ) {
10 3. Print
11 if ( x == 5 )
12 continue; /* skip remaining code in loop only
13 if x == 5 */
14
15 cout<<"%d “<< x;
16 }
17
18 cout<<"\nUsed continue to skip printing the value 5\n" ;
19 return 0;
20 }

1 2 3 4 6 7 8 9 10 Program Output
Used continue to skip printing the value 5
Logical operators:
• Used as conditions in loops, if statements
• ! (logical NOT, logical negation)
– Returns true when its condition is false, & vice versa
if ( !( grade == -1 ) )
cout << "The next grade is " << grade << endl;
Alternative:
if ( grade != -1 )
cout << "The next grade is " << grade << endl;

• && (logical AND)


– true if both conditions are true
if ( gender == 1 && age >= 65 )
++seniorFemales;

• || (logical OR)
– true if either of condition is true
if ( semesterAverage >= 90 || finalExam >= 90 )
cout << "Student grade is A" << endl;
Structured-Programming Summary
• Structured programming
 

– Programs easier to understand, test, debug and modify

• Rules for structured programming


 

– Only use single-entry/single-exit control structures


– Rules
1) Begin with the “simplest flowchart”.

2) Any rectangle (action) can be replaced by two rectangles (actions) in


sequence

3) Any rectangle (action) can be replaced by any control structure (sequence, if,
if/else, switch, while, do/while or for)

4) Rules 2 and 3 can be applied in any order and multiple times


24
Structured-Programming Summary
Representation of Rule 3 (replacing any rectangle with a control structure)
• .
Rule 3

Rule 3 Rule 3

25
Structured-Programming Summary
• All programs broken down into
– Sequence
– Selection
• if, if/else, or switch
• Any selection can be rewritten as an if statement
– Repetition
• while, do/while or for
• Any repetition structure can be rewritten as a while
statement

26
Assignment 1
How to print

******
*****
****
***
**
*
by using while loop?
Assignment 2
How to print
*
**
***
****
*****
******
by using for loop?
Assignment 3
• Write a program to print the factorial of a number
entered by user?

Precautions
 Submission will be in the form of print screen image with output, code and comments in front
of each line. (1 print page for each assignment, 3 prints in total)

 All files must be shown and saved with your name in screen shot.

 Last Date of Submission for all three assignments is . Monday (2-12-2013) 3:00 Pm

 No handwritten assignments will be accepted


Practice Programs:

• http://www.codingunit.com/c-tutorial-for-loop-w
hile-loop-break-and-continue

• http://www.tutorialspoint.com/cprogramming/c
_loops.htm

• http://www.tenouk.com/clabworksheet/labwork
sheet7_1.html

You might also like