C++ Program to display the n terms of odd natural number and their sum

By: Prof. Fazal Rehman Shamil
Last modified on April 22nd, 2020

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

Flowchart of C++ Program to display the n terms of odd natural number and their sum

C++ Source Code

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)

Prof. Fazal Rehman Shamil