I want to assign every array with its index and this is my code.
#include <stdio.h>
#include <cs50.h>
int main(void) {
int length = get_int("How many arrys do you need? ");
int s[length];
for (int i = 0; i < length; i++) {
s[i] = i;
printf("s[i] = %d\n", i);
}
}
when run
s[i] = 0
s[i] = 1
so I want replace i
in the code with its index number like this:
s[0] = 0
s[1] = 1
Your code is fine regarding the initialization of the array.
The printf
statement should be changed to print both the index and the value stored at the index:
printf("s[%d] = %d\n", i, s[i]);
Here is a modified version:
#include <cs50.h>
#include <stdio.h>
int main() {
int length = get_int("How many array elements do you need? ");
if (length <= 0 || length > 1024) {
printf("invalid length: %d\n", length);
return 1;
}
int s[length];
for (int i = 0; i < length; i++) {
s[i] = i;
printf("s[%d] = %d\n", i, s[i]);
}
return 0;
}
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.