Sum of ten numbers ( for loop )
So here is the code given below how to use for loop in C++. So here we go to the code. Just don't copy the code just go for its explanation given below the code. It may guide/help your for your learning and remembrance of the code.
Sum of ten numbers
#include<iostream.h>
#include<conio.h>
void main(){
clrscr();
int num, sum = 0, count = 0;
for (count = 0; count < 10; count++){
cout<<"\n\t Enter number : ";
cin>>num;
sum = sum + num;
}
if (count == 10 ){
cout<<"\n\t Sum of 10 numbers : "<<sum;
}
getch();
}
Explanation of Code
- The header tags.
#include<iostream.h>
#include<conio.h>
- Then the main() function is declared.
void main()
- clrscr(); is a function use to clear the output console screen.
int is use to initialize variables.
int num, sum = 0, count = 0;
- for loop is use for continuation to check the conditions entered in loop and to perform the action.
for (count = 0; count < 10; count++){
cout<<"\n\t Enter number : ";
cin>>num;
sum = sum + num;
}
Whereas, int count = 0 is define in a loop to state that the variable declared with its value, count < 10 is to check whether count variable's value is less than ( < ) 10. And lastly the count++ is use to increase the value of count variable.
Note : count = count + 1 ( count is equals to count plus one ) is written as count++ ( count plus plus ) in the given program.
- if (count == 10 ){cout<<"\n\t Sum of 10 numbers : "<<sum;}
This above if condition statement checks whether the count is exactly equals to ( == ) 10 and if condition goes true it gives addition of an output for the all of those ten values in the loop.
- \n it displays the output in each new line accordingly. \t is a tab use to give 3 white space in an output of program accordingly.
cout<<"\n\t";
- getch(); is the function use to get the characters directly from the keyboard.
getch();
Screenshots :
Code