2

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

3 Answers 3

4
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]);
}
Sign up to request clarification or add additional context in comments.

Comments

2
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....

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.