Arrays in C
(Same Output, But still different!)
So I was learning arrays in C, and I tried two different styles to take and print 5 numbers.
One uses a loop, and one doesn’t, but both give the exact same output!
Here's what have i done:
Program 1: Using a Loop
#include <stdio.h>
int main() {
int numbers[5];
int i;
printf("Enter 5 numbers:\n");
for(i = 0; i < 5; i++) {
scanf_s("%d", &numbers[i]);
}
printf("You entered:\n");
for(i = 0; i < 5; i++) {
printf("%d\n", numbers[i]);
}
return 0;
}
What it does:
-
Creates an array with 5 elements
-
Uses a
for
loop to take input and print it -
Code is shorter and cleaner
Program 2: Without a Loop
#include <stdio.h>
int main() {
int num[5];
printf("Enter 5 numbers:\n");
scanf_s("%d", &num[0]);
scanf_s("%d", &num[1]);
scanf_s("%d", &num[2]);
scanf_s("%d", &num[3]);
scanf_s("%d", &num[4]);
printf("You entered:\n");
printf("%d\n", num[0]);
printf("%d\n", num[1]);
printf("%d\n", num[2]);
printf("%d\n", num[3]);
printf("%d\n", num[4]);
return 0;
}
What it does:
-
Also takes and prints 5 numbers
-
No loops, just direct
scanf_s
andprintf
-
Easy to understand, but not good for large inputs
Same Output Example:
If user enters:
10 20 30 40 50
Both programs will print:
You entered:
10
20
30
40
50
No comments:
Post a Comment