Thursday, December 31, 2009

C programs on series using for loop

Evaluate the following expression S=1+ x + x^2 +x^3+....+x^n using for loop.

#include < stdio.h>
#include < stdio.h>
void main()
{
int i,sum=0,x,n;
clrscr();
printf("Enter the value of 'x' and 'n':-");
scanf("%d%d",&x,&n);
for(i=0;i < =n;i++)
{
if(i < n)
printf("%d^%d+",x,i);
else
printf("%d^%d=",x,i);
sum=sum+pow(x,i);
}
printf("\t%d",sum);
getch();
}


Program to compute exponential series ex=1+x+x2/2!+x3/3!+x4/4!
+.....+xn/n! where 'n' represents the number of terms using for loop.


#include < stdio.h>
void main()
{
float x,t,sum;
int i,n,ffact;
clrscr();
printf("Enter value for 'x' and 'n':-");
scanf("%f%d",&x,&n);
printf("\n%f\n%d",x,n);
t=1;
sum=1;
for(i=1;i < n;i++)
{
ffact=i;
t=t*x/ffact;
sum+=t;
}
printf("\nE raised to power x=%.2f",sum);
getch();
}


Write the output of the following C codes
@ for(i=3;i > =0;i--)
{
for(j=0;j < =4;j++)
{
if((j%2)==0)
break;
printf(“%d”,j);
}
if((i%2)==0)
continue;
printf(“%d”,i);
}
Ans:- 3 and 1 , both from the statement printf(“%d”,i);
@ int i=2;
unsigned j=5;
for(i=2;i >= 0;i--)
{
printf(“\nXYZ”);
}
for(j=8;j >= 0;j--)
{
printf(“\nPQR”);
}

This program in for loop  will show compile time error. As j is unsigned variable it can hold only positive value, so the
control statement for(j=8;j >= 0;j--) will be always true.


@ int I=0,x=0;
for(I=1;I < 10;++I)
{
if(I%2==1)
x+=I
else
x--;
printf(“%d”,x);
}
printf(\nx=%d”,x);
}
Output will be 1 0 3 2 7 6 13 12 21
and x=21





Any Question ? Put Your comments

1 comment:

  1. Your program output is not very clear to me. Is it 1 2 3, 4 5 6, 7 8 9 10? If it is so, then the C program would be



    #include< stdio.h >
    void main()
    {
    int i,x=1;
    clrscr();
    for(i=1;i< 12;i++)
    {
    if(i%4==0)
    printf(",");
    else
    printf("%3d",x++);
    }
    printf("%3d",x++);
    getch();
    }

    ReplyDelete

Subscribe via email

Enter your email address:

Delivered by FeedBurner