How arrays work in a "for" loop (C language)

I am relatively new to programming and programming in general.

1) I am trying to create an array called "input" that will be used for user input (and the array will use only two integer elements).

2) I want to use the for loop so that it scrolls my code 2 times, so I can duplicate the printf "Enter an integer" statement without entering the printf statement several times. And then my scanf placeholder will be based on my "input" array.

3) Then I want to add these two numbers together for the sum.

Problem: When the user enters a number, for example, 1, and then 1 again, the index at input [0] is 1, but then the index at 1 for input [1] is 2 ...

I will use the supplement to try to explain. When I try to print the numbers in addition (the integer [0] is 1, the integer [1] is 2, and my variable that adds them together is "total"), I get the following: 1 + 2 = 2.

So why is input [0] correct, but input [1] seems to add two user inputs together and store them there?

Here is my code

int main()
{
    int input[1];
    for(int i = 0; i < 2; i++)
    {
        printf("Please enter an integer: ");

        scanf("%d", &input[i]);

    }
    int total = input[0]+input[1];
    printf("%d + %d = %d ", input[0], input[1], total);


}

Thanks in advance, and I hope you understand me. Sorry, I'm a noob, learning the basics, so I can become advanced.

+4
source share
3 answers

You have to use

int input[2];

. , [1] .

, n .

int main()
{
int input[1];
int total = 0;
int n; //To count number of elements to add:
  printf("Please enter the number of elements to add: ");

    scanf("%d", &n);

for(int i = 0; i < n; i++)
{
    printf("Please enter integer %d: ",(i+1));

    scanf("%d", &input[i]);

}

for(int i = 0; i < n; i++)
{
    total = total +input[i];

}

printf("The sum is = ", total);


}

, , , , , , .

, .

+1

int input [1];

. , .

int [2];

.

int main()
{
    int input[2];
    for(int i = 0; i < 2; i++)
    {
        printf("Please enter an integer: ");

        scanf("%d", &input[i]);

    }
    int total = input[0]+input[1];
    printf("%d + %d = %d ", input[0], input[1], total);


}
+3

int main()
{
    int input[2];  //initializes array of size 2,which can contain maximun 3-->(0,1,2)
    for(int i = 0; i < 2; i++)
    {
        printf("Please enter an integer: ");

        scanf("%d", &input[i]);

    }
    int total = input[0]+input[1];
    printf("%d + %d = %d ", input[0], input[1], total);


}

i<=2.

int main()
{
    int input[1];  //initializes array of size 1 which can contain -->(0,1),or use i<=2
    for(int i = 0; i <= 2; i++)
    {
        printf("Please enter an integer: ");

        scanf("%d", &input[i]);

    }
    int total = input[0]+input[1];
    printf("%d + %d = %d ", input[0], input[1], total);


}
0

All Articles