0% found this document useful (0 votes)
38 views55 pages

Unit-2 For While Do-While Loops Y5yLMCrONX

basics of computer science engineering in cpp or c++ undergrad courtesy SVKM's NMIMS

Uploaded by

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

Unit-2 For While Do-While Loops Y5yLMCrONX

basics of computer science engineering in cpp or c++ undergrad courtesy SVKM's NMIMS

Uploaded by

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

Loos in C++

By Prof.Avani Bhuva 1
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++:
1. for loop
2. while loop
3. do...while loop
This tutorial focuses on C++ for loop. We will learn about the other type of loops in the upcoming tutorials.
C++ for loop
The syntax of for-loop is:
Syntax of for loop
for(initialization; condition ; increment/decrement)
{
C++ statement(s);
}
initialization - initializes variables and is executed only once, condition - if true, the statements executed and if condition false, the for loop is
terminated
Increment or decrement it will update the value of variables.
By Prof.Avani Bhuva 2
Flow of Execution of the for Loop
• As a program executes, the interpreter always keeps track of which
statement is about to be executed. We call this the control flow, or the
flow of execution of the program.
• First step: In for loop, initialization happens first and only once, which
means that the initialization part of for loop only executes once.
• Second step: Condition in for loop is evaluated on each loop iteration, if
the condition is true then the statements inside for for loop body gets
executed. Once the condition returns false, the statements in for loop
does not execute and the control gets transferred to the next statement in
the program after for loop.
• Third step: After every execution of for loop’s body, the
increment/decrement part of for loop executes that updates the loop
counter.
• Fourth step: After third step, the control jumps to second step and
condition is re-evaluated.

By Prof.Avani Bhuva 3
Example of a Simple For loop in C++:

Here in the loop initialization part I have set the value of variable i to 1,
condition is i<=6 and on each loop iteration the value of i increments by 1.
#include <iostream>
using namespace std;
int main(){
for(int i=1; i<=6; i++)
{
// This statement would be executed repeatedly until the condition i<=6 returns false.
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}

Output:
Value of variable i is: 1
Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6
By Prof.Avani Bhuva 4
By Prof.Avani Bhuva 5
Fibonaccci Series in C++ Output:
Enter the number of terms: 3
#include <iostream> 011
using namespace std;
int main()
{
int n1=0,n2=1,n3,i,number;
cout<<"Enter the number of elements: ";
cin>>number;
cout<<n1<<" "<<n2<<" "; //printing 0 and 1
for(i=3;i<number;i++) //loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
cout<<n3<<" ";
n1=n2;
n2=n3;
}
return 0;
}

By Prof.Avani Bhuva 6
#include <iostream>
using namespace std;
int main() {
int n, t1 = 0, t2 = 1, nextTerm = 0;
cout << "Enter the number of terms: ";
cin >> n;
cout << "Fibonacci Series: ";
for (int i = 1; i <= n; ++i) {
// Prints the first two terms.
if(i == 1) {
cout << t1 << ", ";
continue;
}
if(i == 2) {
cout << t2 << ", ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
cout << nextTerm << ", ";
}
return 0;
By Prof.Avani Bhuva 7
}
By Prof.Avani Bhuva 8
What is a Multiplication Table ? Let's start with very first program of this article, that prints table
A multiplication table shows a list of of 2:
multiples of a particular number, from 1 to #include<iostream>
10. using namespace std;
For example, the multiplication table of 3 int main()
will be: {
3*1=3 int num, i, res;
3*2=6 //cout<<”Enter a number”;
3*3=9 //cin>>num;
3 * 4 = 12 for(i=1; i<=10; i++)
3 * 5 = 15 {
3 * 6 = 18 res = num*i;
3 * 7 = 21 cout<<num<<" * "<<i<<" = "<<res;
3 * 8 = 24 cout<<endl;
3 * 9 = 27 }
3 * 10 = 30 cout<<endl;
Note - Typically list of multiples are from return 0;
1 to 12. But in this article, we've created }
all the programs on printing of
multiplication table based on multiples
from 1 to 10 only.
Print Multiplication Table of 2

By Prof.Avani Bhuva 9
The syntax of a while loop in C++ is −
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is
any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.

Flow Diagram

By Prof.Avani Bhuva 10
By Prof.Avani Bhuva 11
#include <iostream> #include<iostream>
using namespace std; using namespace std;
int main() { int main()
int i=1; {
while(i<=10) int t=5;
{ cout<<"Hello I am going to print the value of variable t in decending order"<<endl;
cout<<i <<"\n"; while(t!=0)
i++; {
} cout<<t<<endl;
} t=t-1;
Output: }
1 return(0);
2 }
3
4
5
6
7
8
9
10

By Prof.Avani Bhuva 12
WAP to print multiplication table using while loop
#include<iostream>
using namespace std;
int main()
{
int t=1,k=10;
cout<<"Table of 10"<<endl;
while(t!=11)
{
cout<<"10 X "<<t<<"="<<k*t<<endl;
t=t+1;
}
return 0;
}

By Prof.Avani Bhuva 13
/* Write a c++ program to print reverse of a given number. */
int main( ){
int n,d,rev=0;
cout<<“Enter one number\n”;
cin>>n;
while(n!=0){
d=n%10;
rev=rev*10+d;
n/=10; // Update expression.
}
cout<< “Reverse number is ”<<rev;
return 0;
}
Output
Enter one number
2357
Reverse number is 7532

By Prof.Avani Bhuva 14
Detailed 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;
}
Output
12345
Here is how the program works.
Iteration Variable i <= 5 Action
1st i = 1 true 1 is printed and i is increased to 2.
2nd i = 2 true 2 is printed and i is increased to 3.
3rd i = 3 true 3 is printed and i is increased to 4
4th i = 4 true 4 is printed and i is increased to 5.
5th i = 5 true 5 is printed and i is increased to 6.
6th i = 6 false The loop is terminate By Prof.Avani Bhuva 15
Write a C++ program and draw flowchart to calculate the sum of square of digits of a number given by the user. (while
loop)
#include<iostream>
using namespace std;
int main()
{
int num, rem, sum=0;
cout<<"Enter any number: ";
cin>>num;
while(num>0)
{
rem = num%10;
sum = sum + rem*rem;
num = num/10;
}
cout<<"\nSum of Square of Digits ="<<sum;
return 0;
}

By Prof.Avani Bhuva 16
C++ do...while Loop
The do...while loop is a variant of the while loop with one
important 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.
This process continues until the condition evaluates to false.
Then the loop stops.

By Prof.Avani Bhuva 17
By Prof.Avani Bhuva 18
for loop while loop do while loop
#include <iostream> #include <iostream>
using namespace std; using namespace std; #include <iostream>
int main() { int main() using namespace std;
int num, sum; { int main()
sum = 0; int num, i, sum = 0; {
cout << "Enter a positive integer: "; cout << "Enter a positive integer: "; int num, i, sum = 0;
cin >> num; cin >> num; cout << "Enter a positive integer: ";
for (int i = 1; i <= num; i++) i = 0; cin >> num;
{ while (i <= num) i = 0;
sum = sum+i; { do
} sum = sum + i; {
cout << "Sum = " << sum << endl; i++; sum = sum + i;
return 0; } i++;
} cout << "Sum = " << sum << endl; }while (i <= num);
return 0; cout << "Sum = " << sum << endl;
} return 0;
}

19
Infinite for loop in C++

A loop is said to be infinite when it executes repeatedly and never stops. This usually happens by mistake. When you set the
condition in for loop in such a way that it never return false, it becomes infinite loop.
For example:

#include <iostream>
using namespace std;
int main(){
for(int i=1; i>=1; i++)
{
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
This is an infinite loop as we are incrementing the value of i so it would always satisfy the condition i>=1, the condition
would never return false.
Here is another example of infinite for loop:
// infinite loop
for ( ; ; )
{
// statement(s)
} By Prof.Avani Bhuva 20
For Loop While Loop

It is used when the number of iterations is It is used when the number of iterations is not
known. known.

In case of no condition, the loop is repeated


In case of no condition, an error will be shown.
infinite times.

Initialization is repeated if carried out during the


Initialization is not repeated.
stage of checking.

Statement of Iteration is written after running. Can be written at any place.

Initialization can be in or out of the loop Initialization is always out of the loop.

The nature of the increment is simple. The nature of the increment is complex.

Used when initialization is simple. Used when initialization is complex.

By Prof.Avani Bhuva 21
While Loop example in C++
1.
#include <iostream>
using namespace std;
int main(){
int i=1;
/* The loop would continue to print
* the value of i until the given condition
* i<=6 returns false.
*/
while(i<=6){
cout<<"Value of variable i is: "<<i<<endl;
i++;
}
}
Output:
Value of variable i is: 1
Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6
By Prof.Avani Bhuva 22
WAP to print even numbers The program prints all the even numbers from 1 to a certain number entered
#include <iostream> by user. At first a number is asked from user, stored in the variable n. Then using a
using namespace std; while loop, all the even numbers from 1 to n are printed by checking if the number
int main() is divisible by 2 or not.
{ Output
int n,i=1; Enter a number:20
cout <<"Enter a number:"; 2
cin>>n; 4
while (i <= n) 6
{ 8
if (i % 2 == 0) 10
cout <<i<<endl; 12
i++; 14
} 16
return 0; 18
} 20

By Prof.Avani Bhuva 23
Example 2: Sum of Positive Numbers Only Output
// program to find the sum of positive numbers Enter a number: 6
// if the user enters a negative number, the loop ends Enter a number: 12
// the negative number entered is not added to the sum Enter a number: 7
#include <iostream> Enter a number: 0
using namespace std; Enter a number: -2
int main() { The sum is 25
int number; In this program, the user is prompted to enter a number, which
int sum = 0; is stored in the
// take input from the user variable number.
cout << "Enter a number: "; In order to store the sum of the numbers, we declare a variable
cin >> number; sum and initialize it
while (number >= 0) { to the value of 0.
// add all positive numbers The while loop continues until the user enters a negative
sum += number; number. During each
// take input again if the number is positive iteration, the number entered by the user is added to the sum
cout << "Enter a number: "; variable.
cin >> number; When the user enters a negative number, the loop terminates.
} Finally, the total sum
// display the sum is displayed
cout << "\nThe sum is " << sum << endl;
return 0;
}
By Prof.Avani Bhuva 24
Infinite While loop
We can also create infinite while loop by passing true as the te
A while loop that never stops is said to be the infinite while
condition.
loop, when we give the
#include <iostream>
condition in such a way so that it never returns false, then the
using namespace std;
loops becomes infinite
int main () {
and repeats itself indefinitely.
while(true)
An example of infinite while loop:
{
This loop would never end as I’m decrementing the value of i
cout<<"Infinitive While Loop";
which is 1 so the
}
condition i<=6 would never return false.
}
#include <iostream>
Output:
using namespace std;
Infinitive While Loop
int main()
Infinitive While Loop
{
Infinitive While Loop
int i=1; while(i<=6)
Infinitive While Loop
{
Infinitive While Loop
cout<<"Value of variable i is: "<<i<<endl; i--;
ctrl+c
}
}

By Prof.Avani Bhuva 25
do-while loop:
The do-while loop should be used when the number of iterations is not fixed, and the loop must execute for at least once. The
C++ compiler executes the loop body
first before evaluating the condition. That means the loop must return a result. This is the case even when the test condition
evaluates to a false on the first evaluation.
Since the loop body has already been executed, it must return the result.
Syntax
The basic syntax of C++ do while loop is as follows:
do{
//code
}while(condition);
The condition is test expression. It must be true for the loop to execute.
The { and } mark the body of do while loop. It comes before the condition. Hence, it is executed before the condition.
C++ Do while flow chart
Flow Chart Explanation:
1. Start of do while loop.
2. The body of do while loop.
3. The test expression or condition to be evaluated.
4. If the test expression is true, the C++ compiler executed the body of do
while loop.
5. If the test expression is false, the C++ compiler executes the statements after
the loop body.
6. Statements that come after the loop body.
By Prof.Avani Bhuva 26
By Prof.Avani Bhuva 27
Example 1
#include <iostream>
using namespace std;
int main()
{
// Local variable
int x = 1;
do
{
cout << "X is: " << x << endl;
x = x + 1;
} while (x < 5);
return 0;
}

By Prof.Avani Bhuva 28
C++ program for menu driven using do while loop
if (choice == 'C' || choice == 'c')
#include <iostream>
{
#include <iomanip>
cout << "A: Earl Gray Tea and Biscuits" << c << endl;
using namespace std;
}
int main()
if (choice == 'D' || choice == 'd')
{
{
double a = 5.99, b = 4.99, c = 4.99, d = 5.99, e = 9.99, totalprice;
cout << "D: Coffee and a Muffin" << d << endl;
const double TAX = 0.13;
}
int choice = 0;
if (choice == 'E' || choice == 'e')
char (answer);
{
do
cout << "E: The Assorted Tea, Scones, and Biscuits Platter" << e << endl;
{
}
cout << "\nGood day! Welcome to The Bakery! What would you like today?\n";
else if (answer == 'N' || answer == 'n')
cout << "\nMenu\n Price"<< endl;
{
cout << "A: Earl Gray Tea and Biscuits - " << a << endl;
cin >> totalprice;
cout << "B: Coffee and a blueberry scone - " << b << endl;
cout << "The final bill for today is ";
cout << "C: Espresso and a tea biscuit - " << c << endl;
}
cout << "D: Coffee and a Muffin- " << d << endl;
else //Displaying error message
cout << "E: The Assorted Tea, Scones, and Biscuits Platter- $" << e << endl;
{
cout << "\nAre there any addtional orders? 'Y' or 'N'\n" << endl;
cout << "Invalid input";
cin >> answer;
}
if (answer == 'Y' || answer == 'y')
} while (answer != 'Y' && answer != 'y');
{ //Display Choice
}
cout << "\nYour choice?\n" << endl;
}
if (choice == 'A' || choice == 'a')
{
cout << "A: Earl Gray Tea and Biscuits" << a << endl;
}
if (choice == 'B' || choice == 'b')
{
cout << "B: Coffee and a blueberry scone" << b << endl;
}

By Prof.Avani Bhuva 29
Following are the Loop control statements: Example : Demonstrating the Break statement's execution
1. Break Statement #include <iostream>
2. Continue Statement using namespace std;
3. Goto Statement int main()
1. Break Statement: {
• Break statement is used to terminate loop or switch int cnt = 0;
statements. do
• It is used to exit a loop early, breaking out of the enclosing {
curly braces. cout<<"Value: "<<cnt<<endl;
Syntax: cnt++;
break; if(cnt>5)
{
break; //terminate the loop
}
}
while(cnt<10);
return 0;}
Output:
Value: 0
Value: 1
Value: 2
Value: 3
Value: 4
By Prof.Avani Bhuva 30
Value: 5
break:-
- ‘break’ is used to exit the execution of any loop.
- ‘break’ is used to stop the execution of remaining cases in the switch.
Syntax:-
break;
In the above syntax, we have only break keywords followed by semicolon, and we can write this in switch and any loops.

Example:- Programming example to show use break.


#include<stdio.h>
int main()
{
int i;
i=1;
while(1)
{
if(i==4) break;
cout<<“\t”<<i;
i++;
}}
Output
1 2 3 4
In this example, we have used the ‘break’ keyword to break the while loop… and execution of the while loop will be
terminated whenever condition if(i==4) is evaluated as true, as the break will get executed.
By Prof.Avani Bhuva 31
Continue:-
- ‘continue’ is used to continue the execution of the next iteration by skipping the current iteration of any loop.
- Note:- continue can not be used in switch-case.
- Syntax:-
continue;
In the above syntax, we have only the ‘continue’ keyword followed by a semicolon and we can write this in any loop.
Example:- Programming example to show use continue.
int main( )
{
int i;
for(i=1;i<=5;i++){
if(i==4) continue;
cout<<“\t”<<i;
}
}
Output
1 2 3 5

In this example, we have used the ‘continue’ keyword to continue the iteration of the loop. Whenever condition if(i==4)
is evaluated as true, then the next iteration will be continued.

By Prof.Avani Bhuva 32
2. Continue Statement
• Continue statement skips the remaining code block.
• This statement causes the loop to continue with the next iteration.
• It is used to suspend the execution of current loop iteration and transfer control to the loop for the next iteration. Can be
included within a while, do-while or for.
Syntax:
continue;
• In For and while Loop, Control automatically passes to the beginning of the loop
• In Do-While Loop, Sends the control straight to the test at the end of the loop.
The remaining loop statements are skipped and the execution proceeds directly to the next pass through the loop.

33
Example : Demonstrating the execution of Continue statement
#include <iostream>
using namespace std;
int main()
{
int cnt = 0;
do
{
cnt++;
if(cnt>5 && cnt<10)
continue;
cout<<"Value: "<<cnt<<endl;
}
while(cnt<11);
return 0;
}
Output:
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
Value: 10
By Prof.Avani Bhuva 34
Value: 11
Break Statement Continue Statement
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main() int main()
{ {
int n,total=0,i; int n,total=0,i;
for(i=1;i<=10;i++) for(i=1;i<=3;i++)
{ {
cout<<"Enter a number:"; cout<<"Enter a number:";
cin>>n; cin>>n;
if(n>99) if(n>99)
break; {
total=total+n; cout<<"no is greater than 99";
} i--;
cout<<"Total="<<total; continue;
} }
total=total+n;
Output: }
Enter a number:23 cout<<"Total="<<total;
Enter a number:45 }
Enter a number:700 Output:
Total=68 Enter a number:1
Enter a number:100
no is greater than 99Enter a number:
2
Enter a number:3
Total=6 35
Difference between break and
continue
break continue
A break can appear in both switch and loop (for, while, do) A continue can appear only in loop (for, while, do)
statements. statements.

A break causes the switch or loop statements to terminate the A continue doesn't terminate the loop, it causes the loop to
moment it is executed. Loop or switch ends abruptly when go to the next iteration. All iterations of the loop are executed
break is encountered. even if continue is encountered. The continue statement is
used to skip statements in the loop that appear after
the continue.

The break statement can be used in both switch and loop The continue statement can appear only in loops. You will
statements. get an error if this appears in switch statement.

When a break statement is encountered, it terminates the When a continue statement is encountered, it gets the control
block and gets the control out of the switch or loop. to the next iteration of the loop.

A break causes the innermost enclosing loop or switch to be A continue inside a loop nested within a switch causes the
exited immediately. next loop iteration.

By Prof.Avani Shah 36
C++ Program to Find Sum of series 1²+2²+3²+….+n² or sum
square of first n natural numbers
#include <iostream>
using namespace std;
int main()
{
int n, i, sum = 0;
cout<<"Enter a positive integer: ";
cin>>n;
for(i=1;i<=n;i++)
{
sum=sum+(i*i);
}
cout<<"Sum ="<<endl<<sum;
return 0;
}

By Prof.Avani Bhuva 37
Write a program to calculate the value of following series
1+1/2+1/3+1/4+1/5+.............. +1/n
#include<iostream>
using namespace std;
int main()
{
int i,n;
float sum=0.0;
cout<<"Enter a number: ";
cin>>n;
for(i=1;i<=n;i++)
{
sum=sum+1.0/i;
}

cout<<"The value of the series is:"<<sum;


return 0;
}

By Prof.Avani Bhuva 38
Write a program to calculate the value of following series 1 + 1/2!
+ 1/3! + 1/4! ......... + 1/n!
#include<iostream>
using namespace std;
int main()
{
int i,n,fact=1; float sum=0.0;
cout<<"Enter a number: ";
cin>>n;
for(i=1;i<=n;i++)
{
fact=fact*i;
sum=sum+1.0/fact;
}
cout<<"The value of the series is:"<<sum;
return 0;
}

By Prof.Avani Bhuva 39
WAP to find the sum of given series 1!+3!+5!+….+n! (sum
of factorial of odd numbers)
#include<iostream>
using namespace std;
int main()
{
int i,n,sum=0,fact=1;
cout<<"Enter the Number : ";
cin>>n;
for( i = 1; i <= n; i++)
{
fact=fact*i;
if( i % 2 != 0 )
{
sum =sum+fact;
}
}
cout<<"sum of all even number is"<<sum;
return 0;
}
By Prof.Avani Bhuva 40
WAP to find the sum of given series 2!+4!+6!+….+n! (sum of
factorial of even numbers
#include<iostream>
using namespace std;
int main()
{
int i,n,sum=0,fact=1;
cout<<"Enter the Number : ";
cin>>n;
for( i = 1; i <= n; i++)
{
fact=fact*i;
if( i % 2 == 0 )
{
sum =sum+fact;
}
}
cout<<"sum of all even number is"<<sum;
return 0;
}

By Prof.Avani Bhuva 41
Lab Exercise

By Prof.Avani Bhuva 42
Write a C++ program to print the sum of the following series up to n terms where n is given by the user.
1+x+x2/2! + x3/3! +… n terms Lab excercise
#include<iostream>
using namespace std; Input the value of x :3
int main() Input number of terms : 5
{ The sum is :
float x,sum,no_row; 16.375
int i,n;
cout<<"Input the value of x :";
cin>>x;
cout<<"Input number of terms : ";
cin>>n;
sum =1; no_row = 1;
for (i=1;i<n;i++)
{
no_row = no_row*x/(float)i;
sum =sum+ no_row;
}
cout<<"\nThe sum is :"<<endl<<sum;
return 0;
}

By Prof.Avani Bhuva 43
WAP to find perfect number: example 6 is perfect number coz its
divisible by 1,2,3 n sum of these number is 1+2+3=6 6,28,496,8128 etc
are perfect number
#include<iostream>
using namespace std;
int main()
{
int number, i, sum = 0;
cout<<"Enter a any number: ";
cin>>number;
for(i=1; i <number; ++i)
{
if(number%i==0)
sum = sum+i;
}
if(sum==number)
cout<<"entered number is "<<number;
else
cout<<"entered number is not perfect number = "<<number;

return 0;
} By Prof.Avani Bhuva 44
Write a program to count +ve number, -ve number and zeros until user want, make use of do
while loop.
#include<iostream>
using namespace std;
int main()
{
int n, sum_p=0, sum_n=0, sum_z=0;
char choice;
do
{
cout<<"Enter number ";
cin>>n;
if(n>0)
sum_p++;
else if(n<0)
sum_n++;
else
sum_z++;
cout<<"Do you want to Continue(y/n)? ";
cin>>choice;
}while(choice=='y' || choice=='Y');
cout<<"Positive Number :"<<sum_p<<"\nNegative Number :"<<sum_n<<"\
nZero Number :"<<sum_z;
return 0;
}
45
Write a program to check whether a number is a strong number or not.
#include<iostream> else
using namespace std; {
int main() cout<<number<<" is Not a Strong Number";
{ }
int i, number, temp, reminder; return 0;
long sum = 0, factorial = 1; }
cout << "\nPlease Enter the number";
cin >> number;
for(temp=number; temp>0; temp=temp/10 )
{
factorial=1;
reminder=temp%10;
for(i=1;i<=reminder;i++)
{
factorial=factorial*i;
}
cout << "\nThe Factorial of "<< reminder << " = " << factorial;
sum=sum+factorial;
}
cout<<"\n\nThe Sum of the Factorials of " << number << " is = " << sum << "\n\n";
if(number==sum)
{
cout<<number<<" is a Strong Number"; By Prof.Avani Bhuva 46
Write a program to accept a number from the user. Find and print the sum of digits of the number.
#include<iostream>
using namespace std;
int main()
{
int num, rem, sum=0;
cout<<"Enter the Number: ";
cin>>num;
while(num>0)
{
rem = num%10;
sum = sum+rem;
num = num/10;
}
cout<<"\nSum of Digits = "<<sum;
cout<<endl;
return 0;
}

By Prof.Avani Bhuva 47
#include <cmath>
#include <iostream> Write a program to accept a number from user and display if
using namespace std; the number is Armstrong number. (Armstrong number is the
int main() { number in any given number base, which forms the total of the
int num, originalNum, remainder, n = 0, result = 0, power; same number, when each of its digits is raised to the power of
cout << "Enter an integer: "; the number of digits in the number.)
cin >> num;
originalNum = num;
while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
while (originalNum != 0) {
remainder = originalNum % 10;
power = round(pow(remainder, n));
result =result+ power;
originalNum /= 10;
}
if (result == num)
cout << num << " is an Armstrong number.";
else
cout << num << " is not an Armstrong number.";
return 0; By Prof.Avani Bhuva 48
}
#include<iostream>
using namespace std;
int main()
{
int num, temp=0, last, rem, sum=0;
cout<<"Enter a Number: ";
cin>>num;
while(num!=0)
{
if(temp==0)
{
last = num%10;
temp++;
}
rem = num%10;
num = num/10;
}
sum = rem + last;
cout<<"\nSum of First ("<<rem<<") and Last ("<<last<<") Digit = "<<sum;
cout<<endl;
return 0;
}

By Prof.Avani Bhuva 49
Write a program to check whether the entered number is a palindrome.
Output
#include <iostream>
Enter a positive number: 12321
using namespace std;
The reverse of the number is: 12321
int main()
The number is a palindrome.
{
int n, num, digit, rev = 0;
Enter a positive number: 12331
cout << "Enter a positive number: ";
The reverse of the number is: 13321
cin >> num;
The number is not a palindrome.
n = num;
do
{
digit = num % 10;
rev = (rev * 10) + digit;
num = num / 10;
} while (num != 0);
cout << " The reverse of the number is: " << rev << endl;
if (n == rev)
cout << " The number is a palindrome.";
else
cout << " The number is not a palindrome.";
return 0;
By Prof.Avani Bhuva 50
}
Write a program to check whether the entered number is prime or not. (make use of break)

#include<iostream>
using namespace std;
int main()
{
int num, i, chk=0;
cout<<"Enter a Number: ";
cin>>num;
for(i=2; i<num; i++)
{
if(num%i==0)
{
chk++;
break;
}
}
if(chk==0)
cout<<"\nIt is a Prime Number";
else
cout<<"\nIt is not a Prime Number";
cout<<endl;
return 0;
} By Prof.Avani Bhuva 51
Self:

Write a program to print the entire uppercase and lowercase letters using a loop (use continue).
Implement a program to print all Leap Years from 1 to N using C++ program.

By Prof.Avani Bhuva 52
Write a program using loop to find the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of
two numbers

GCD (Greatest Common Divisor)


GCD stands for Greatest Common Divisor. GCD of two numbers is the largest positive integer that completely divides
both the given numbers.
Example: GCD(10,15) = 15, GCD(12,15) = 3.
LCM (Least Common Multiple)
LCM stands for Least Common Multiple. It is a method to find the lowest common multiple between the two numbers.
LCM of two numbers is the lowest possible number that is divisible by both numbers.
Examples: LCM(10,15) = 30, LCM(12,15) = 60.

By Prof.Avani Bhuva 53
Program Explanation
1.In this C program, we are reading the two integer numbers.
2. Compare the two numbers, store the greater number in the numerator and the smaller number in the denominator.
3.Run the while loop until the remainder becomes ‘0’.
4. Inside the while loop keep on dividing the numerator by denominator and store the value in the remainder variable.
5. When the value of the remainder variable becomes ‘0’ come out of the loop and store the value of the denominator in
the gcd variable.
6.Now, calculate the lcm by the formula lcm = (num1 * num2) / gcd
7. Print the value of gcd and lcm.

Example:
•Consider, the two numbers 12 and 15, first find the greater of the two numbers and store the greater in
the numerator and smaller in the denominator i.e., numerator=15 and denominator=12.
•Divide the numerator by the denominator and store the value in the remainder variable i.e., remainder = 15%12 = 3.
•Now, enter the while loop and check if the remainder value is ‘0’ or not.
•Now, assign the value of the denominator to the numerator and the value of the remainder to
the denominator i.e., numerator=12 and denominator=3
•Calculate the remainder of the two variables i.e., remainder=12%3=0.
•Now, check the while loop condition again, this time remainder = 0, therefore come out of the loop and store the value
of the denominator in gcd i.e., gcd = 3.
•Now, using the formula of lcm (lcm = (num1 * num2) / gcd) calculate lcm i.e., lcm = (12*15)/3 = (180/3) = 60.
•Now, print the gcd and lcm of the two numbers.
By Prof.Avani Bhuva 54
#include <iostream>
using namespace std;
int main()
{
//variable declaration
int n1, n2, i;
//variable declaration and initialization
int gcd = 1, lcm = 1;
//taking input from the command line (user)
cout << " Enter the two numbers you want to find the GCD and LCM of : \n\n";
cin >> n1 >> n2;
//logic to calculate the GCD and LCM of the two numbers
for ( i = 1; i < 1000; i++)
{
//i is the least value that perfectly divides both the numbers and hence the GCD
if ((n1 % i == 0) && (n2 % i == 0))
{
gcd = i;
}}
lcm = (n1 * n2) / gcd;
cout << " \n\nThe GCD of the two numbers : " << n1 << " and " << n2 << " is : " << gcd;
cout << " \n\nThe LCM of the two numbers : " << n1 << " and " << n2 << " is : " << lcm << "\n\n";
cout << "\n\n\n";
return 0;} By Prof.Avani Bhuva 55

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy