C++ Assighnment 4
C++ Assighnment 4
Ans] while is a pretest loop. It is an entry controlled loop. The variable in test condition must be
initialized prior to entering the loop structure.
3.1.3 The following program fragment is supposed to input numbers from the user and
display them until a 0 is entered, but a statement is missing. What is the missing statement
and where should it be inserted?
while (number != 0)
while (number != 0)
cout<<”enter a number”<<endl;
cin >> number;
3.1.4 Replace the while loop in the Counting program and the Summation program with
the do-while loop.
Ans]1. Counting program
#include <iostream>
int main()
int c=0;
cin>>pass;
cin>>marks;
do
if(marks>=pass)
c++;
cin>>marks;
while(marks!=-1);
return 0;
}
2. accumulating program
#include <iostream>
int main()
int marks,sum=0;
cin>>marks;
do
cin>>marks;
}while(marks!=-1);
cout<<"sum of marks"<<sum<<endl;
return 0;
3.1.5 Write a program to count the number of students when a set of student marks are
entered as input.
Ans]
#include <iostream>
int main()
int marks,c=0;
while(marks!=-1)
if(marks>=0)
c++;
cin>>marks;
return 0;
3.1.6 Write a program to find the average marks scored by a set of students.
Ans]
#include <iostream>
int main()
double marks,avg,sum=0;
int c=0;
cin>>marks;
while(marks!=-1)
{
sum=sum + marks;
c++;
cin>>marks;
avg=sum/c;
cout<<"average is"<<avg<<endl;
return 0;
Ans]
#include <iostream>
int main()
int num=10;
cout<<”multiple of 10 are”<<endl;
for(int i=1; i<=10;i++)
cout<<i*num<<endl;
return 0;
#include <iostream>
int main()
for(int i=5;i>=1;i--)
for(int j=1;j<=i;j++)
cout<<i;
cout<<endl;
return 0;
}
3.3.1 What are the differences between break, continue
and return?
Ans] break: In a loop, the break statement is used to exit the loop before
the exit conditions are met. A break causes the program to jump over all the
statements in the loop’s block and continue with the statement immediately
after the loop.
Continue: The continue statement forces return to the next test condition of
the loop before all the statements in the body of the loop are executed. It
serves to bypass certain sections of a loop.
Return: The return statement in the body of the loop will cause the function
(in which the loop is placed) to return immediately to the calling function.
if (i == 4)
break;
}
cout << “done”<< endl;
ans]
10
9
8
7
6
5
4
Done
10
9
8
7
6
5
4
3
2
1
Done
3.3.3 Write a program that accepts a character input and validates that the character is
only between a to z.
Ans]
#include <iostream>
int main()
char ch;
cout<<"enter a character"<<endl;
cin>>ch;
else
return 0;