Pages

Monday, April 7, 2014

ADDING CURRENT NUMBER WITH BEFORE NUMBER UP TO n TERMS


Write a program to generate the following sequence:

1,2,4,7,11,16...........................................20 terms
The second number in the sequence is obtained by adding 1 to previous number, the third number is obtained by adding 2 to the previous number, the fourth number is obtained by adding 3 to the previous number and so on. The loop is to be executed for 20 times.The program is as follows:
#include<stdio.h>
#include<conio.h>
void main()
{
int term;
int i;
i=1;
term=1;        /*control variable*/
while(term<=20)
{
printf("%d
",i);

i=i+term;
term=term+1;
}

In the above, the variable term is used to control the execution of the loop and the variable i is used as a processing variable.The logic of the program depends on the statement i=i+term; where the next number in the sequence is obtained by adding the value of term to the previous number and the term is incremented by 1 every time the loop executes.The success of the program that uses a while loop depends on the proper use of control and process variables.The control variable is to be initialized, tested in the condition and then updated in the loop.The process variable is used in the logic

Related Posts by Categories

0 comments:

Post a Comment