Write a program in C++ to display the n terms of odd natural number and their sum like:
1 3 5 7 … n.
Flowchart of C++ Program to display the n terms of odd natural number and their sum
C++ Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include<iostream> using namespace std; int main() { int n,sum=0,i,t; cout<<"enter the number :"; cin>>n; i=1; do { cout<<2*i-1<<" "; sum=sum+2*i-1; i++; } while(i<=n); cout<<"\n the sum of an odd numer is "<<sum; } |
Output
enter the number: 5
1 3 5 7 9
the sum of an odd number is 25.
Excercise
Find the possible mistakes in the following Shamil’s Flow Table of the program to display the n terms of odd natural number and their sum.
Loop | condition | What lines will execute? | Actual work to do |
Time 1
I=1 |
T | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 | Sum = sum+i
0=0+(2*1-1) |
Time 2
I=3 |
T | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15, 9, 10, ,11,12,13,14,15 | Sum = sum+i
1=1+(2*2-1) |
Time 3
I=5 |
T | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15, 9, 10, ,11,12,13,14,15 | Sum = sum+i
3=3+(2*3-1) |
Time 4
I=7 |
T | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15, 9, 10, ,11,12,13,14,15,16,17 | Sum = sum+i
5=5+(2*4-1) |