简体   繁体   中英

Adding numbers to an array with for loop in C

So I don't really understand why when I use for loop to store numbers from 1 to 4 I get random numbers? When I use for loop without an Array Everything works just fine, but when i add Array, the numbers I get are random, can someone explain why the numbers are random? Here is the simple code:

int i, arr[5]; for(i=1; i<5; i++){ printf("%d ", arr[i]);

Your code never explicitly assigns values to the items in the array. In C, variables that are not explicitly declared contain random values. If you're expecting the array to contain zeroes by default, you'd want to declare your array like this:

int arr[5] = {0};

If you want to store the numbers 1 through 4 in your array, you need to add a line in your for loop to assign those values:

arr[i] = i + 1;

Without initializing arr , you end up with garbage values .

The code for initializing during declaration is given below:

int arr[5] = {1, 2, 3, 4, 5}; // This is declaration and initialisation of arr
for (int i = 0; i < 5; i++) {
  printf("%d ", arr[i]);
}

Need to initialize the array and the variable before using them.

int i = 0, arr[5] = {1,2,3,4,5};
    for(i=0;i<5;i++)
        printf("%d ",arr[i]);

updated the proper answer.

And insert after int i, arr[5];

arr[5] = {1,2,3,4,5};

or try this code...

int i,arr[5];
    for(i=0;i<5;i++){
        arr[i] = (i + 1);
        printf("%d ",arr[i]);
}

You have declared a array but didn't assigned any value so compiler automatically assigning garbage value in it. That's why you get some random values.

#include<stdio.h>
int main()
{
         int arr[5] = {0};
 
         for(int i = 0; i < 5; i++)
         {
                 printf("%d\n", arr[i] = i + 1);
         }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM