TaaHa Schaikh
TaaHa Schaikh

Reputation: 21

for loop in C returning only first value of array

I'm a beginner. Well I was just trying out my hand at data structures and could not understand why I was getting the error. I think it would be better to post the code and the output I'm getting. (I use the C-Free 4.0 Compiler), by the way. So here's the code

// Write a C program to enter and display elements of an array

    #include <stdio.h>
    int main(int argc, char *argv[])
{
    int a[44],n,i=0;
    // No. of elements:
    printf("\n How many elements in all?");
    scanf("%d",&n);

    // Entering all elements:
    printf("\n\n Plz do enter the elements:");
    for(;i<n;i++)
    scanf("%d",&a[i]);

    // Displaying all elements:
    printf("\n Array elements are:");

     for(i=0;i<n;)
     {

       printf("\n a[%d]=%d",i,a[i]);
       i++;
       break;

     }

    int sum=0;
    for(i=0;i<n;i++)

    {
      sum=sum+a[i];

    }

    printf("\nSum=%d",sum);


    return 0;
}
/*
  And here's the output when I say that I'm entering 3 elements into the array:

   How many elements in all?3


 Plz do enter the elements:12
0
-22

 Array elements are:
 a[0]=12
Sum=-10Press any key to continue . . . */

Well as you all can see, I am able to enter values for(i=0;i

Upvotes: 2

Views: 1805

Answers (3)

Tushar Mishra
Tushar Mishra

Reputation: 177

for(i=0;i<n;)
{
   printf("\n a[%d]=%d",i,a[i]);
   i++;
   break;
}

Here the break statement you are using is getting you out of the loop. remove the break statement and it will print all the elments of the array....

Upvotes: 2

Sunil Bojanapally
Sunil Bojanapally

Reputation: 12658

for() loop can be used in two ways,

for (Start value; end condition; increase value)
        statement;

or

Start value = initialization;
for (; end condition;){
        statement;
        increase value;
}

In your code, the Start value is initialized to i = 0 so you can try any of the ways but preferably first is accepted more for ease and clarity.

Upvotes: 0

Abubakkar
Abubakkar

Reputation: 15644

for(i=0;i<n;)
{
   printf("\n a[%d]=%d",i,a[i]);
   i++;
   break;
}

You have put a break; so it only prints 1 element.

Remove that break; and it will print all.

Also you can put that i++ just next to the condition i<n as shown below.

for(i=0;i<n;i++)
{
    printf("\n a[%d]=%d",i,a[i]);
}

Upvotes: 4

Related Questions