0% found this document useful (0 votes)
115 views

Lesson 3 Control Structures C++ For Students

1. The document discusses various control structures in C++ including selection structures like if, if else, nested if else and switch case statements as well as loop structures like for, while and do while loops. 2. If statements execute code only if a test condition is true, if else statements execute one code block if the condition is true and another if it is false, and nested if else can check multiple conditions. 3. Examples are provided to demonstrate how to use if, if else and nested if else statements to make decisions based on positive/negative numbers or other conditions.

Uploaded by

Samwel Otieno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Lesson 3 Control Structures C++ For Students

1. The document discusses various control structures in C++ including selection structures like if, if else, nested if else and switch case statements as well as loop structures like for, while and do while loops. 2. If statements execute code only if a test condition is true, if else statements execute one code block if the condition is true and another if it is false, and nested if else can check multiple conditions. 3. Examples are provided to demonstrate how to use if, if else and nested if else statements to make decisions based on positive/negative numbers or other conditions.

Uploaded by

Samwel Otieno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Contents

C++ if Statement................................................................................................................................1
Working of if Statement................................................................................................................1
Flowchart of if..................................................................................................................................2
Example 1: C++ if Statement......................................................................................................3
C++ if...else.........................................................................................................................................4
Working of if...else Statement....................................................................................................4
Flowchart of if...else......................................................................................................................5
Example 2: C++ if...else Statement..........................................................................................5
C++ Nested if...else...........................................................................................................................6
Syntax of Nested if...else.............................................................................................................6
Example 3: C++ Nested if...else Statement............................................................................7
Conditional/Ternary Operator ?:....................................................................................................8
C++ switch Statement...........................................................................................................................8
Syntax of switch....................................................................................................................................8
Flowchart of switch Statement........................................................................................................9
Example 1: C++ switch Statement................................................................................................10
C++ for Loop Syntax....................................................................................................................12
How for loop works in C++ Programming?............................................................................12
Flowchart of for Loop in C++.....................................................................................................12
Example 1: C++ for Loop...........................................................................................................13
C++ break and continue Statement................................................................................................14
C++ break Statement......................................................................................................................14
Syntax of break.............................................................................................................................15
Working of break Statement......................................................................................................15
Example 1: C++ break................................................................................................................15
C++ continue Statement.................................................................................................................16
Syntax of continue.......................................................................................................................16
Working of continue Statement................................................................................................17
Example 2: C++ continue...........................................................................................................17
C++ goto Statement............................................................................................................................18
Syntax of goto Statement...................................................................................................................18
Example 1: goto Statement............................................................................................................18
Reason to Avoid goto Statement................................................................................................19

Control structure- is structure that controls the flow of a program.

Types of Control structures

1. Selection control structure:


 if , 
 if...else
 nested  if...else  ,
 switch case
2. Loop/iterative /repetition control structures
 for Loop
 while Loop
 do...while Loop

Selection control structure:

The  if ,  if...else  and nested  if...else  statement are used to make one-time decisions in
C++ Programming, that is, to execute some code/s and ignore some code/s depending upon
the test condition. Without decision making, the program runs in similar way every time.
Decision making is an important feature of every programming language using C++
programming. Before you learn decision making, you should have basic understanding of
relational operators.

C++ if Statement
The  if  statement checks whether the test condition is true or not. If the test condition is
true, it executes the code/s inside the body of  if  statement. But it the test condition is false,
it skips the code/s inside the body of  if  statement.

Working of if Statement
The  if  keyword is followed by test condition inside parenthesis ( ). If the test condition is
true, the codes inside curly bracket is executed but if test condition is false, the codes
inside curly bracket { } is skipped and control of program goes just below the body of   if  as
shown in figure above.

Flowchart of if
 

Example 1: C++ if Statement


C++ Program to print integer entered by user only if that number is positive.

#include <iostream>
using namespace std;

int main() {
int number;
cout<< "Enter an integer: ";
cin>> number;

if ( number > 0) { // Checking whether an integer is positive or not.


cout << "You entered a positive integer: "<<number<<endl;
}

cout<<"This statement is always executed because it's outside if statement." ;


return 0;

Output 1

Enter an integer: 5

You entered a positive number: 5

This statement is always executed because it's outside if statement.

Output 2

Enter a number: -5

This statement is always executed because it's outside if statement.

C++ if...else
The  if...else  executes body of  if  when the test expression is true and executes the body
of  else if test expression is false.

Working of if...else Statement


The if statement checks whether the test expression is true or not. If the test condition is
true, it executes the code/s inside the body of if statement. But it the test condition is false,
it executes the code/s inside the body of  else .

Flowchart of if...else
Example 2: C++ if...else Statement
C++ Program to check whether integer entered by user is positive or negative
(Considering 0 as positive)

#include <iostream>
using namespace std;

int main() {
int number;
cout<< "Enter an integer: ";
cin>> number;

if ( number >= 0) {
cout << "You entered a positive integer: "<<number<<endl;
}

else {
cout<<"You entered a negative integer: "<<number<<endl;
}

cout<<"This statement is always executed because it's outside if...else statement." ;


return 0;
}

Output

Enter an integer: -4

You entered a negative integer: -4

This statement is always executed because it's outside if...else


statement.

C++ Nested if...else


Nested if...else are used if there are more than one test expression.

Syntax of Nested if...else


if (test expression1){

statement/s to be executed if test expression1 is true;

else if(test expression2) {

statement/s to be executed if test expression1 is false and 2


is true;

else if (test expression 3) {

statement/s to be executed if text expression1 and 2 are false


and 3 is true;

else {
statements to be executed if all test expressions are false;

The nested  if...else  statement has more than one test expression. If the first test
expression is true, it executes the code inside the braces{ } just below it. But if the first test
expression is false, it checks the second test expression. If the second test expression is
true, if executes the code inside the braces{ } just below it. This process continues. If all the
test expression are false, code/s inside else  is executed and the control of program jumps
below the  nested if...else

Example 3: C++ Nested if...else Statement


C++ Program to check whether the integer entered by user is positive, negative or
zero.

#include <iostream>
using namespace std;

int main() {
int number;
cout<< "Enter an integer: ";
cin>> number;

if ( number > 0) {
cout << "You entered a positive integer: "<<number<<endl;
}
else if (number < 0){
cout<<"You entered a negative integer: "<<number<<endl;
}
else {
cout<<"You entered 0."<<endl;
}

cout<<"This statement is always executed because it's outside nested if..else statement." ;
return 0;

Output

Enter an integer: 0

You entered 0.

This statement is always executed because it's outside nested if..else


statement.

Conditional/Ternary Operator ?:
Conditional operators are the peculiar case of  if...else  statement in C++ Programming.
Consider this  if..else  statement:

if ( a < b ) {

a = b;

else {

a = -b;

The above code can be written using conditional operator as:

a = (a < b) ? b : -b;

Both codes above check whether a is less than b or not. If a is less than b, value of b is
assigned to a if not,  -b  is assigned to a.

C++ switch Statement

Consider a situation in which, only one block of code needs to be executed among many blocks.
This type of situation can be handled using nested  if...else  statement but, the better way of
handling this type of problem is using  switch...case  statement.

Syntax of switch
switch (n) {

case constant1:

code/s to be executed if n equals to constant1;

break;

case constant2:

code/s to be executed if n equals to constant2;

break;
.

default:

code/s to be executed if n doesn't match to any cases;

The value of n is either an integer or a character in above syntax. If the value of  n matches constant
in  case , the relevant codes are executed and control moves out of the  switch  statement. If
the ndoesn't matches any of the constant in case, then the default statement is executed and control
moves out of  switch  statement.

Flowchart of switch Statement


Example 1: C++ switch Statement
/* C++ program to demonstrate working of switch Statement */
/* C++ program to built simple calculator using switch Statement */

#include <iostream>
using namespace std;
int main() {
char o;
float num1,num2;
cout<<"Select an operator either + or - or * or / \n";
cin>>o;
cout<<"Enter two operands: ";
cin>>num1>>num2;

switch(o) {
case '+':
cout<<num1<<" + "<<num2<<" = "<<num1+num2;
break;

case '-':
cout<<num1<<" - "<<num2<<" = "<<num1-num2;
break;
case '*':
cout<<num1<<" * "<<num2<<" = "<<num1*num2;
break;
case '/':
cout<<num1<<" / "<<num2<<" = "<<num1/num2;
break;
default:

/* If operator is other than +, -, * or /, error message is shown */


printf("Error! operator is not correct");
break;
}

return 0;
}
Output

Select an operator either + or - or * or /

Enter two operands: 2.3

4.5

2.3 - 4.5 = -2.2

The  break  statement at the end of each  case  cause  switch  statement to exit. If break statement is
not used, all statements below that case statement are also executed.

Loop Control structures


In computer programming, loop cause a certain piece of program to be executed a certain
number of times.  Consider these scenarios:

 You want to execute some code/s certain number of time.


 You want to execute some code/s certain number of times depending upon input from user.

These types of task can be solved in programming using loops.

There are 3 types of loops in C++ Programming:

 for Loop
 while Loop
 do...while Loop

C++ for Loop Syntax


for(initialization statement; test expression; update statement) {

code/s to be executed;

How for loop works in C++ Programming?


The initialization statement is executed only once at the beginning of the for loop. Then the
test expression is checked by the program. If the test expression is false, for loop is
terminated. But if test expression is true then the code/s inside body of   for  loop is executed
and then update expression is updated. This process repeats until test expression is false.

Flowchart of for Loop in C++


Example 1: C++ for Loop
C++ Program to find factorial of a number (Note: Factorial of positive integer n = 1*2*3*...*n)
#include <iostream>
using namespace std;

int main() {
int i, n, factorial = 1;

cout<<"Enter a positive integer: ";


cin>>n;

for (i = 1; i <= n; ++i) {


factorial *= i; // factorial = factorial * i;
}

cout<< "Factorial of "<<n<<" = "<<factorial;


return 0;
}
Output

Enter a positive integer: 5

Factorial of 5 = 120

In this program, user is asked to enter a positive integer which is stored in


variable n (supposed user entered 5). Here is the working of  for  loop in this program:

1. Initially,  i = 1 , test expression is true, factorial becomes 1.


2. Variable i is updated to 2, test expression is true, factorial becomes 2.
3. Variable i is updated to 3, test expression is true, factorial becomes 6.
4. Variable i is updated to 4, test expression is true, factorial becomes 24.
5. Variable i is updated to 5, test expression is true, factorial becomes 120.
6. Variable i is updated to 6, test expression is false,  for  loop is terminated.

In the above program you can see that, variable  i is not used outside  for  loop. In such
9case, it is better to define variable at the time of initialization statement.

for (int i = 0; i <= n, ++i){

... .. ...

In the above C++ code, i is local to  for  loop, that is, you cannot use it outside  for  loop but
makes program more readable.

C++ break and continue Statement

There are two statements ( break;  and  continue; ) built in C++ programming to alter the
normal flow of program.

Loops are used to perform repetitive task until test expression is false but sometimes it is
desirable to skip some statement/s inside loop or terminate the loop immediately with
checking test condition. On these type of scenarios,   continue;  statement
and  break;  statement is used respectively. The break;  statement is also used to terminate
switch statement.

C++ break Statement


The break; statement terminates the loop(for, while and do..while loop) and switch
statement immediately when it appears.

Syntax of break
break;

In real practice, break statement is almost always used inside the body of conditional
statement(if...else) inside the loop.

Working of break Statement

Example 1: C++ break


C++ program to add all number entered by user until user enters 0.

// C++ Program to demonstrate working of break statement

#include <iostream>
using namespace std;
int main() {
float number, sum = 0.0;

while (true) { // test expression is always true


cout<<"Enter a number: ";
cin>>number;

if (number != 0.0) {
sum += number;
}
else {
break; // terminating the loop if number equals to 0.0
}

}
cout<<"Sum = "<<sum;
return 0;
}

Output

Enter a number: 4

Enter a number: 3.4

Enter a number: 6.7

Enter a number: -4.5

Enter a number: 0

Sum = 9.6

In this C++ program, the test expression is always true. The user is asked to enter a
number which is stored in variable number. If the user enters any number other than 0, that
number is added to sumand stored to it and again user is asked to enter another number.
When user enters 0, the test expression inside   if  statement is false and body of  else  is
executed which terminates the loop. Finally, the sum is displayed.

C++ continue Statement


It is sometimes necessary to skip some statement/s inside the loop. In that
case,  continue; statement is used in C++ programming.

Syntax of continue
continue;

In practice,  continue;  statement is almost always used inside conditional statement.


Working of continue Statement

Example 2: C++ continue


C++ program to display integer from 1 to 10 except 6 and 9.

// C++ Program to demonstrate working of continue statement

#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; ++i) {
if ( i == 6 || i == 9) {
continue;
}
cout<<i<<"\t";
}
return 0;
}

Output

1 2 3 4 5 7 8 10

In above program, when i is 6 or 9, execution of statement  cout<<i<<"\t";  is skipped


inside the loop using  continue;  statement.
C++ goto Statement

In C++ programming, goto statement is used for altering the normal sequence of program execution
by transferring control to some other part of the program.

Syntax of goto Statement


goto label;

... .. ...

... .. ...

... .. ...

label:

statement;

... .. ...

In syntax above, label is an identifier. When  goto label;  is encountered, the control of program
jumps to  label:  and executes the code below it.

Example 1: goto Statement


/* C++ program to demonstrate the working of goto statement. */
/* This program calculates the average of numbers entered by user. */
/* If user enters negative number, it ignores that number and
calculates the average of number entered before it.*/

# include <iostream>
using namespace std;
int main() {
float num, average, sum = 0.0;
int i, n;
cout<<"Maximum number of inputs: ";
cin>>n;

for(i=1; i <= n; ++i) {


cout<<"Enter n"<<i<<": ";
cin>>num;

if(num < 0.0) {


goto jump; /* Control of the program moves to jump; */
}
sum += num;
}

jump:
average=sum/(i-1);
cout<<"\nAverage = "<<average;
return 0;
}

Output

Maximum number of inputs: 10

Enter n1: 2.3

Enter n2: 5.6

Enter n3: -5.6

Average = 3.95

You can write any C++ program with use of  goto  statement and it is generally considered good idea
not to use  goto  statement.

Reason to Avoid goto Statement


The goto statement gives power to jump to any part of program but, makes the logic of the program
complex and tangled. In modern programming, goto statement is considered a harmful construct and
a bad programming practice.

The goto statement can be replaced in most of C++ program with the use of break and continue
statements.

You might also like