Sunday, November 22, 2009

C programs on for loop

In this program we will use multiple statements in a for loop body. Here we will display the cube value of the numbers starting from 1 to 10.

#include < stdio.h>
void main ()
{
int num, cube;
clrscr ();
for (num=1;num<=10;num++) 

 {
 printf ("%d", num); 
cube=num*num*num; 
printf (": Cube value is: %d\n", cube);
 } 
getch (); 



The following program will display the sum of the first ten natural numbers using for loop.


 #include < stdio.h>
void main ()
{
int n,i,num;
float sum=0;
clrscr();
printf("Enter the number of elements to be entered::");
scanf("%d",&n);
for(i=0;i < 10;i++)
 
 sum=sum+i;
 printf("\nSum of the numbers divisible by 2 but not by 3 is:\t%d",sum);
 getch(); 



How we proceed in this program


We have used the variable 'sum' as a counter to store the total sum of the first ten natural numbers.’ sum' has been initialized with 0 in the main function block. If it were initialized with the same value inside the body of the for loop then there would be no syntax error but we won't get the desired result. Why? There would be a logical error.


Program to display fibonacci series


# include < stdio.h>
void main ()
{
int previous, current, next, n, i;
clrscr ();
previous=0;
current=1;
printf ("Series of how many elements?");
scanf ("%d", &n);
printf ("Fibonacci series: ");
printf ("%d", previous);
printf (" %d", current);
for (i=0;i {
next=previous + current;
printf (" %d", next);
previous=current;
current=next;
}
getch ();
}

2 comments:

  1. #include < stdio.h>
    void main ()
    {
    int n,i,num;
    float sum=0;
    clrscr();
    printf("Enter the number of elements to be entered::");
    scanf("%d",&n);
    for(i=0;i < 10;i++)
    sum=sum+i;
    printf("\nSum of the numbers divisible by 2 but not by 3 is:\t%d",sum);
    getch();
    }

    not using loop statements pls tell me

    ReplyDelete
  2. It should be like:



    #include < stdio.h>
    void main ()
    {
    int n,i,num;
    float sum=0;
    clrscr();
    printf("Enter the number of elements to be entered::");
    scanf("%d",&n);
    for(i=0;i < n;i++)
    {
    printf("\nEnter number:");
    scanf("%d",&num);
    if(num%2==0 && num%3!=0)
    sum=sum+num;
    }
    printf("\nSum of the numbers divisible by 2 but not by 3 is:\t%d",sum);
    getch();
    }

    ReplyDelete

Subscribe via email

Enter your email address:

Delivered by FeedBurner