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

ch5C++ Loops

tyetsdczxczx

Uploaded by

Mohammed Ibrahim
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

ch5C++ Loops

tyetsdczxczx

Uploaded by

Mohammed Ibrahim
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

C++

PROGRAMMING
C++ for Loop
C++ FOR LOOP
 In computer programming, loops are used to repeat a block of code.

 For example, let's say we want to show a message 100 times. Then instead of
writing the print statement 100 times, we can use a loop.

 That was just a simple example; we can achieve much more efficiency and
sophistication in our programs by making effective use of loops.

 There are 3 types of loops in C++.

 for loop

 while loop

 do...while loop
C++ FOR LOOP
 The syntax of for-loop is:

 for (initialization; condition; update) {


 // body of-loop
 } for (initialization; condition; update) {
 // body of-loop
}
 Here,

 initialization - initializes variables and is executed only once


 condition - if true, the body of for loop is executed
 if false, the for loop is terminated
 update - updates the value of initialized variables and again checks the
condition
FLOWCHART OF FOR LOOP IN C++
EXAMPLE 1: PRINTING NUMBERS FROM 1
TO 5
 #include <iostream>

 using namespace std;

 int main() {
 for (int i = 1; i <= 5; ++i) {
 cout << i << " ";
 }
 return 0;
 }
EXAMPLE 2: DISPLAY A TEXT
5 TIMES
 // C++ Program to display a text 5 times

 #include <iostream>

 using namespace std;

 int main() {
 for (int i = 1; i <= 5; ++i) {
 cout << "Hello World! " << endl;
 }
 return 0;
 }
EXAMPLE 3: FIND THE SUM OF FIRST N NATURAL NUMBERS
 / C++ program to find the sum of first n natural numbers

 // positive integers such as 1,2,3,...n are known as natural numbers

 #include <iostream>

 using namespace std;

 int main() {

 int num, sum;


 sum = 0;
 cout << "Enter a positive integer: ";
 cin >> num;

 for (int count = 1; count <= num; ++count) {


 sum += count;
 }
 cout << "Sum = " << sum << endl;
 return 0;
 }
NOTE THAT WE HAVE USED A FOR LOOP.

 for(int count = 1; count <= num; ++count)


 Here,

 int count = 1: initializes the count variable


 count <= num: runs the loop as long as count is less than or equal to num
 ++count: increase the count variable by 1 in each iteration
 When count becomes 11, the condition is false and sum will be equal to 0
+ 1 + 2 + ... + 10.
EXAMPLE 4: RANGE BASED FOR LOOP

 #include <iostream>

 using namespace std;

 int main() {

 int num_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

 for (int n : num_array) {
 cout << n << " ";
 }

 return 0;
 }
C++ WHILE AND
DO...WHILE LOOP
 In computer programming, loops are used to repeat a block of code.

 For example, let's say we want to show a message 100 times. Then instead of
writing the print statement 100 times, we can use a loop.

 That was just a simple example; we can achieve much more efficiency and
sophistication in our programs by making effective use of loops.

 There are 3 types of loops in C++.

 for loop
 while loop
 do...while loop
C++ WHILE LOOP

 The syntax of the while loop is:

 while (condition) {
 // body of the loop
}
 Here,

 A while loop evaluates the condition


 If the condition evaluates to true, the code inside the while loop is
executed.
 The condition is evaluated again.
 This process continues until the condition is false.
 When the condition evaluates to false, the loop terminates.
FLOWCHART OF WHILE LOOP
EXAMPLE 1: DISPLAY NUMBERS FROM 1 TO 5

 // C++ Program to print numbers from 1 to 5

 #include <iostream>
 using namespace std;
 int main() {
 int i = 1;
 // while loop from 1 to 5
 while (i <= 5) {
 cout << i << " ";
 ++i;
 }

 return 0;
 }
EXAMPLE 2: SUM OF POSITIVE NUMBERS ONLY
 // program to find the sum of positive numbers
 // if the user enters a negative number, the loop ends
 // the negative number entered is not added to the sum
 #include <iostream>
 using namespace std;
 int main() {
 int number;
 int sum = 0;
 // take input from the user
 cout << "Enter a number: ";
 cin >> number;
 while (number >= 0) {
 // add all positive numbers
 sum += number;
 // take input again if the number is positive
 cout << "Enter a number: ";
 cin >> number;
 }
 // display the sum
 cout << "\nThe sum is " << sum << endl;
 return 0;
 In this program, the user is prompted to enter a number, which is stored in
the variable number.

 In order to store the sum of the numbers, we declare a variable sum and
initialize it to the value of 0.

 The while loop continues until the user enters a negative number. During
each iteration, the number entered by the user is added to the sum
variable.

 When the user enters a negative number, the loop terminates. Finally, the
total sum is displayed.
 The do...while loop is a variant of the while loop with one important
C++ DO...WHILE LOOP

difference: the body of do...while loop is executed once before the


condition is checked.
 Its syntax is:
 do {
 // body of loop;
}
 while (condition);
 Here,

 The body of the loop is executed at first. Then the condition is evaluated.
 If the condition evaluates to true, the body of the loop inside the do
statement is executed again.
 The condition is evaluated once again.
 If the condition evaluates to true, the body of the loop inside the do
statement is executed again.
FLOWCHART OF DO...WHILE LOOP
EXAMPLE 3: DISPLAY NUMBERS FROM 1 TO 5

 / C++ Program to print numbers from 1 to 5

 #include <iostream>

 using namespace std;

 int main() {
 int i = 1;

 // do...while loop from 1 to 5


 do {
 cout << i << " ";
 ++i;
 }
 while (i <= 5);

 return 0;
 }
EXAMPLE 4: SUM OF POSITIVE NUMBERS ONLY
 / program to find the sum of positive numbers
 // If the user enters a negative number, the loop ends
 // the negative number entered is not added to the sum
 #include <iostream>
 using namespace std;
 int main() {
 int number = 0;
 int sum = 0;
 do {
 sum += number;
 // take input from the user
 cout << "Enter a number: ";
 cin >> number;
 }
 while (number >= 0);
 // display the sum
 cout << "\nThe sum is " << sum << endl;
 return 0;
 }
INFINITE WHILE LOOP
 If the condition of a loop is always true, the loop runs for infinite times (until the memory is
full). For example,

 // infinite while loop


 while(true) {
 // body of the loop
 }
 Here is an example of an infinite do...while loop.

 // infinite do...while loop

 int count = 1;

 do {
 // body of loop
 }
 while(count == 1);
C++
Lessons
C++ BREAK STATEMENT
 In C++, the break statement terminates the loop when it is encountered.
 The syntax of the break statement is:
 break;
WORKING OF C++ BREAK STATEMENT
EXAMPLE 1: BREAK WITH FOR LOOP
 / program to print the value of i

 #include <iostream>
 using namespace std;

 int main() {

 for (int i = 1; i <= 5; i++) {


 // break condition
 if (i == 3) {
 break;
 }
 cout << i << endl;
 }

 return 0;
 }
EXAMPLE 2: BREAK WITH WHILE LOOP
 / program to find the sum of positive numbers

 // if the user enters a negative numbers, break ends the loop


 // the negative number entered is not added to sum

 #include <iostream>
// add all positive numbers
sum += number;
 using namespace std;
}

 int main() {
// display the sum
 int number; cout << "The sum is " << sum << endl;
 int sum = 0;
return 0;
 while (true) { }
 // take input from the user
 cout << "Enter a number: ";
 cin >> number;

 // break condition
 if (number < 0) {
 break;
 }
C++ CONTINUE
STATEMENT
 In computer programming, the continue statement is used to skip the
current iteration of the loop and the control of the program goes to the
next iteration.

 The syntax of the continue statement is:

 continue;
WORKING OF C++ CONTINUE STATEMENT
EXAMPLE 1: CONTINUE WITH FOR LOOP

 In a for loop, continue skips the current iteration and the control flow jumps to the
update expression.
 / program to print the value of i
 #include <iostream>
 using namespace std;
 int main() {
 for (int i = 1; i <= 5; i++) {
 // condition to continue
 if (i == 3) {
 continue;
 }
 cout << i << endl;
 }

 return 0;
 }
 This means
 When i is equal to 3, the continue statement skips the current iteration and
starts the next iteration
 Then, i becomes 4, and the condition is evaluated again.
 Hence, 4 and 5 are printed in the next two iterations.
 Note: The continue statement is almost always used with decision-making
statements.
EXAMPLE 2: CONTINUE WITH WHILE LOOP

 In a while loop, continue skips the current iteration and control flow of the
program jumps back to the while condition.
 // program to calculate positive numbers till 50 only
 // if the user enters a negative number,
 // that number is skipped from the calculation

 // negative number -> loop terminate


 // numbers above 50 -> skip iteratio
EXAMPLE
 // program to calculate positive numbers till 50 only
 // if the user enters a negative number,
 // that number is skipped from the calculation
/ continue condition
 // negative number -> loop terminate if (number > 50) {
 // numbers above 50 -> skip iteration
cout << "The number is greater than 50
and won't be calculated." << endl;
 #include <iostream>
number = 0; // the value of number is

made 0 again
using namespace std;
continue;

}
int main() {
}
 int sum = 0;
 int number = 0;
// display the sum
cout << "The sum is " << sum << endl;
 while (number >= 0) {
 // add all positive numbers return 0;
 sum += number; }

 // take input from the user


 cout << "Enter a number: ";
 cin >> number;
CONTINUE WITH NESTED LOOP

 When continue is used with nested loops, it skips the current iteration of the
inner loop. For example,

// using continue statement inside


// nested for loop // first loop
for (int i = 1; i <= 3; i++) {
#include <iostream> // second loop
using namespace std; for (int j = 1; j <= 3; j++) {
if (j == 2) {
int main() { continue;
int number; }
int sum = 0; cout << "i = " << i << ", j = " << j <<
endl;
// nested for loops }
}

return 0;
}
C++ SWITCH..CASE STATEMENT

 The switch statement allows us to execute a block of code among many


alternatives
 The syntax of the switch statement in C++ is:
switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;

case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}
HOW DOES THE SWITCH
STATEMENT WORK?
 The expression is evaluated once and compared with the values of each
case label.

 If there is a match, the corresponding code after the matching label is


executed. For example, if the value of the variable is equal to constant2,
the code after case constant2: is executed until the break statement is
encountered.
 If there is no match, the code after default: is executed.
 Note: We can do the same thing with the if...else..if ladder. However, the
syntax of the switch statement is cleaner and much easier to read and
write.
FLOWCHART OF SWITCH STATEMENT
EXAMPLE: CREATE A CALCULATOR USING THE SWITCH STATEMENT

// Program to build a simple calculator using switch


Statement
#include <iostream>
using namespace std;
cout << num1 << " * " << num2 << " = " <<
int main() { num1 * num2;
char oper; break;
float num1, num2; case '/':
cout << "Enter an operator (+, -, *, /): "; cout << num1 << " / " << num2 << " = "
cin >> oper; << num1 / num2;
cout << "Enter two numbers: " << endl; break;
cin >> num1 >> num2; default:
// operator is doesn't match any case
switch (oper) { constant (+, -, *, /)
case '+': cout << "Error! The operator is not
cout << num1 << " + " << num2 << " = " correct";
<< num1 + num2; break;
break; }
case '-':
cout << num1 << " - " << num2 << " = " return 0;
<< num1 - num2; }
break;
case '*':
HOW THIS PROGRAM WORKS
 We first prompt the user to enter the desired operator. This input is then stored in
the char variable named oper.
 We then prompt the user to enter two numbers, which are stored in the float
variables num1 and num2.
 The switch statement is then used to check the operator entered by the user:
 If the user enters +, addition is performed on the numbers.
 If the user enters -, subtraction is performed on the numbers.
 If the user enters *, multiplication is performed on the numbers.
 If the user enters /, division is performed on the numbers.
 If the user enters any other character, the default code is printed.
 Notice that the break statement is used inside each case block. This terminates
the switch statement.

 If the break statement is not used, all cases after the correct case are executed.
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;
EXAMPLE: GOTO STATEMENT

// This program calculates the average of numbers


entered by the user. for(i = 1; i <= n; ++i)
// If the user enters a negative number, it ignores {
the number and cout << "Enter n" << i << ": ";
// calculates the average number entered before it. cin >> num;

# include <iostream> if(num < 0.0)


using namespace std; {
// Control of the program move to jump:
int main() goto jump;
{ }
float num, average, sum = 0.0; sum += num;
int i, n; }

cout << "Maximum number of inputs: "; jump:


cin >> n; average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}
REASON TO AVOID GOTO
STATEMENT
 The goto statement gives the power to jump to any part of a program but,
makes the logic of the program complex and tangled.

 In modern programming, the 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.
END

You might also like