






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A program is a precise sequence of steps to solve a particular problem. This course includes basic programming structure like loops, operator, memory allocation, reference, pointers etc. It teaches how to be a good programmer. This lecture handout is about: Do, while, Statement, Loop, Increment, Decrement, Operators, Sample, Program, While, Condition, False, Execution, Control, Syntax, Structure
Typology: Study notes
1 / 11
This page cannot be seen from the preview
Don't miss anything!







Reading Material
Deitel & Deitel – C++ How to Program Chapter 2
2.11, 2.12, 2.14, 2.15, 2.
Summary
Do-While Statement Example for Statement ample Program 1 crement/decrement Operators
while loop does le time. This occurs when the condition in while is false. In the statements in the body are executed nly w ue. If the condition is false, then the control goes directly while loop. So we can say that in while can execute zero or more times. There may be situations where we
this case, the task of guessing the ents is once, C provides a do-while structure. The syntax of do-while
statement(s);
while ( condition ) ;
re w is tested after executing the statements of the loop dy. Thus, the loop body is executed at least once and then the condition in do while tatement is tested. If it is true, the execution of the loop body is repeated. In case, it proves otherwise (i.e. false), then the control goes to the statement next to the do
In Sample Program 2 Tips
We have seen tha t there may be certain situations when the body of not execute even a sing w hile loop, the condition is tested first and o hen this condition is tr to the statement after the closed brace of the structure, the loop may ne ed that some task must be performed at least once. For example, a computer program has a character stored from a-z. It gives to user five chances or tries to guess the character. In character must be performed at least once. To ensure that a block of statem executed at least structure is as under:
do
He e see that the condition bo s
while statement. This structure describes ‘execute the statements enclosed in braces in do clause' when the condition in while clause is true. Broadly speaking, in while loop, the condition is tested at the beginning of the loop before the body of the loop is performed. Whereas in do-while loop, the condition is tested after the loop body is performed. Therefore, in do-while loop, the body of the loop is executed at least once. The flow chart of do-while structure is as follow:
Let’s consider the example of guessing a character. We have a character in the guessed by the user. Let’s call it ‘z’. The program allows five tries user to guess the character. We declare a variable tryNum to store character for guessing. e store this character in a variable c. eclare the variable c of type char. The data type char is used to store a single aracter. We assign a character to a variable of char type by putting the character in ngle q ent statement to assign a value to a char variable will as c = ‘a’. Note that there should be a single character in single quotes. The tement like c = ‘gh’ will be a syntax error.
re we use the do-while construct. In the do clause we prompt the user to enter a haracter.
er, we compare it with our character i.e e as ours e add 1 to tryNum variable. yNum is less than or equal true, then the body of the do clause is repeated gain. We do this only when the condition ( tryNum <= 5 ) remains true. If it is therwise, the control goes to the first statement after the do-while loop.
hed in first or second try, then we should exit the loop. We know that e loop is terminated when the condition tryNum <= 5 becomes false, so we assign a value which is greater than 5 to tryNum after displaying the message. Now the
program to be (chances) to the the number of tries. The program prompts the user to enter a W We d ch si uotes. Thus the assignm be sta
He c
After getting character in variable c from us ‘z’. We use if\else structure for this comparison. If the character is the sam then we display a message to congratulate the user else w And then in while clause, we test the condition whether tr to 5 ( tryNum <= 5 ). If this condition is a o
If guess is matc th
There is an elegant way to exit the loop when the correct number is guessed. We change the condition in while statement to a compound condition. This condition will check whether the number of tries is less than or equal to 5 and the variable c is not equal to ‘z’. So we will write the while clause as while (tryNum <= 5 && c != ‘z’ ) ; Thus when a single condition in this compound condition becomes false, then the control will exit the loop. Thus we need not to assign a value greater than 5 to variable tryNum. Thus the code of the program will be as:
This p z sed to allow five tries for guessing
tream.h>
ain ( )
e variables
ng : “ ;
ut << “Congratulations, Your guess is correct” ;
// rogram allows the user to guess a character from a to //do-while construct is u
//check the entered character for equality if ( c == ‘z’) { co } else { tryNum = tryNum + 1; } } while ( tryNum <= 5 && c != ‘z’ ); }
The output of the program is given below.
Please enter a character between a-z for guessing : g Please enter a character between a-z for guessing : z Congratulations, Your guess is correct
he body of the loop. If there is a
x of for loop is given below.
incrementing condition )
tement(s) ;
at a ' for statement' consists of three parts. In initialization condition, we me variable while in continuation condition, we set a condition for the n of the loop. In third part, we increment the value of the variable for ermination condition is set. se, we have a variable counter of type int. We write for loop in our
r ( counter = 0 ; counter < 10 ; counter = counter +1 ) { out << counter << endl;
e
ow let's see how this loop executes. When the control goes to for statement first ts the condition (i.e. counter < 10 ). If is true, then executes the body of the loop. In this case, it displays the value of g statement (i.e. ow, the control goes for statement and tests the condition of continuation. If it is true, then the body of d which displays 1 on the screen. The increment statement is gain executed and control goes to for statement. The same tasks are repeated. When of counter becomes 10, the condition counter < 10 becomes false. Then the p is terminated and control goes out of for loop.
Let’s see what we do in a loop. In a loop, we initialize variable(s) at first. Then we set a condition for the continuation/termination of the loop. To meet the condition to terminate the loop, we affect the condition in t variable in the condition, the value of that variable is changed within the body of the loop. If the value of the variable is not changed, then the condition of termination of the loop will not meet and loop will become an infinite one. So there are three things in a loop structure i.e. (i) initialization, (ii) a continuation/termination condition and (iii) changing the value of the condition variable, usually the increment of the variable value. To implement these things, C provides a loop structure known as for loop. This is the most often used structure to perform repetition tasks for a known number of repetitions. The synta
for ( initialization condition ; continuation condition ; { sta }
We see th initialize so continuatio which the t Let's suppo program as
fo
c }
This ' for loop' will print on the screen 0, 1, 2 …. 9 on separate lines (as we use endl in our cout statement). In for loop , at first, we initialize the variable counter to 0. And in the termination condition, we write counter < 10. This means that the loop will continue till value of counter is less than 10. In other words, the loop will terminat when the value of counter is equal to or greater than 10. In the third part of for statement, we write counter = counter + 1 this means that we add 1 to the existing value of counter. We call it incrementing the variable.
N time, it sets the value of variable counter to 0, tes it counter which is 0 for the first execution. Then it runs the incrementin counter = counter + 1 ). Thus the value of counter becomes 1. N to the loop is again execute a the value loo
t
2 x 1 = 2
gain
2 = 4 he same action will be repeated 10 times with values of counter from 1 to 10. When
x 7 = 14
In the body of the for loop , we write a single statement with cout. This single statement involves different tasks. The portion ‘ << “2 x “’ displays the string “2 x “ on the screen. After this, the next part ‘ << counter’ will print the value of counter. The ‘ << “ = ”’ will display ‘ = ‘ and then the next part ‘ << 2 * counter’ will display the result of 2 multiply by counter and the last <<”\n” ( the new line character) will start a new line. Thus in the first iteration where the value of counter is 1, the cou statement will display the following line
After the execution of cout statement, the for statement will increment the counter variable by 1. Thus value of counter will be 2. Then condition will be checked which is still true. Thus the body of for loop (here the cout statement) will be executed a having the value of counter 2. So the following line will be printed. 2 x T the value of counter is 11, the condition ( counter <= 10 ) will become false and the loop will terminate.
The output of the above program is as the following.
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10 2 x 6 = 12 2 2 x 8 = 16 2 x 9 = 18 2 x 10 = 20
Now what will we do, if some one says us to write a table of 3, or 4 or 8 or any other ere comes the point of re-usability and that a program should be generic.
a table. We store this number
For this, we use a ariable maxMultiplier and execute the loop for maxMultiplier times by putting the
input from user and displays its table
number. H We write a program in which a variable is used instead of a hard code number. We prompt the user to enter the number for which he wants in the variable and then use it to write a table. So in our previous example, we now use a variable say number where we were using 2. We also can allow the user to enter the number of multipliers up to which he wants a table. v condition counter <= maxMultiplier. Thus our program becomes generic which can display a table for any number and up to any multiplier.
Thus, the code of our program will be as below:
//This program takes an integer //The table is displayed up to the multiplier entered by the user
ain ( )
er for input want a table : “ ;
you want a table : “ ; in >> axMultiplier
//the for loop
cout << number << “ x “ << counter << “ = “ << number * counter << “\n” ;
m { int counter, number, maxMultiplier ;
// Prompt the us cout << “Please enter the number for which you cin >> number ; cout << “Please enter the multiplier up to which c m ;
for ( counter = 1 ; counter <= maxMultiplier ; counter = counter + 1) {
} }
The output of the program is shown as follows:
Please enter the number for which you want a table : 7 Please enter the multiplier up to which you want a table : 8 7 x 1 = 7
x 4 = 28
7 x 2 = 14 7 x 3 = 21 7 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56
Here is a guideline for programming style. We should avoid using constant values in ur calculations or in long routines. The disadvantage of this is that if we want to e later, then we have to change every occurrence of that the program. Thus we have to do a lot of work and there may be some places here we do not change that value. To avoid such situations, we can use a riable at the start and assi use the constant value, we can assign the new ble and the remaining code will remain the same. So in our program here e table of 2, we can use a variable (say number) and assign it the alue 2 stead of constant 2. If we want ust change the value of the es instead of xplici alues.
o change that constant valu value in in code w va gn that constant value to it and then in the program that variable. Thus, if we need to change value to that varia w we wrote th v. And in cout statement we use this variable in that the program should display a table of 5, then we j variable. So for good programming, use variables for constant valu e t constant v
action (i.e. +, -, *, / and %). The use of these operators is explained by the following
et’s say we have an expression, counter = counter + 5;. The equivalent of this expression is counter += 5 ;. The statement counter += 5 ; does two tasks. At first, it ounter and then assigns this result to counter. Similarly the llowing expressions x + ;
in equivalent short statements using the operators ( +=, -=, *=, /=, %= )
x += 4 ; x -= 3 ; x *= 2;
ote th here is no space between these operators. These are treated as single signs. operator %=. This operator assigns the remainder to the variable. alternate in short hand for an assignment statement. The use of r of
riables
and construct a for loop ive number for sum of squares: ” ;
examples.
L
adds 5 to the value of c fo x = 4 x = x - 3 ; x = x * 2 ; x = x / 2 ; x = x % 3;
can be written as follows
x /= 2; x %= 3 ;
N at t Be careful about the These operators are these operators is not necessary. A programmer may use these or not. It is a matte style.
Let’s write a program using for loop to find the sum of the squares of the integers from 1 to n. Where n is a positive value entered by the user (i.e. Sum = 1^2 + 2 2 + 3 2 + ……+ n 2 )
The code of the program is given below:
//This program displays the sum of squares of integers from 1 to n
main ( ) { //declare and initialize va int i, n, sum; sum = 0 ;
//get input from user cout << “Please enter a posit cin >> n;
i ++)
sum += i * i ;
for ( i = 1 ; i <= n ; {
} cout << “The sum of the first ” << n << “ squares is “ << sum << endl ; }
In the program declared three variables i , n and sum. We prompted the user to enter a oop.
ment
ent sum += i * i ;. This statement takes the square of the counter ariable ( i )and adds it to the variable sum. This statement is equivalent to the tatement sum hus in each iteration the square of the counter iteration ) is added to the sum. Thus loop uns n times and the squares of numbers from 1 to n are summed up. After omple ng the is executed which displays the sum of the
er 5 is entered.
lease ter a of squares: 5 he su of the
positive number. We stored this number in the variable n. Then we wrote a for l In the initialization part, we initialized variable i with value 1 to start the counting from 1. In the condition statement we set the condition i less than or equal to n (number entered by the user) as we want to execute the loop n times. In the incre statement, we incremented the counter variable by 1. In the body of the for loop we wrote a single statem v s = sum + ( i * i ) ; T variable (which is increased by 1 in each r c ti for loop the cout statement squares of number from 1 to n.
Following is the output when the numb
P en positive number for sum T m first 5 squares is 55
Comments should be meaningful, explaining the task
is
ons
Don’t forget to affect the value of loop variable in while and do-while loops Make sure that the loop is not an infinite loop Don’t affect the value of loop variable in the body of for loop, the for loop does th by itself in the for statement Use pre and post increment/decrement operators cautiously in expressi