0
How to store value in an array using for loop, and printing it from outside the loop as a whole array. In C language.
What's wrong in this. #include <stdio.h> #include <conio.h> void main() { int i, n[10]; for(i=0; i<10; i++) { n[i] = i; } printf("%d", n[i]); getch(); }
22 odpowiedzi
+ 5
You can do it with one loop like that :
int j = 0, i;
for(i = 0; i != 20 || !j; i += 1+j){
printf("%d ",i);
if(i == 20){
j = 1;
i = -1;
putchar('\n');
}else if(i > 20){
i = -2;
putchar('\n');
}
}
printf("%d\n",i);
+ 10
You could do it with a single loop, but would have to do it with stuff you haven't been taught. Your teacher wants the loops in your code.
(put output into strings as you process the array and print the strings afterwards)
+ 8
You don't ask it to print the whole array only one element.
+ 7
I didn't notice the new as he never used it. Sorry!
+ 6
You are referring beyond n as i is 10 after loop finishes.
+ 6
second for loop to print or move within first loop
+ 6
personally, I'd do something like:
for (i=0; i<10; i +=5)
printf(%d %d %d %d %d\n", n[i], n[i+1], n[i+2], n[i+3], n[i+4]);
+ 6
@Baptiste, the question was for C. @gordie, it works though it costs about the same as three loops so why complicate the issue. But, it is a awesome method to use only one loop.
+ 2
@gordie, it is C++ not C
+ 2
Near !
cstdio -> stdio.h
new int[20] -> (int*)malloc(20*sizeof(int))
and ... you forgot to delete your pointer !
delete[] -> free
+ 2
Yes @john, that is what I said to @gordie as he/she did C++ instead ^^
+ 1
If you want to avoid a loop, use recursive function like that :
void print(int * array, int size){
if(size){
printf("%d\n",array[0]);
print(array + 1, size - 1);
}
}
But it is still looping in a way
+ 1
Yes, and when you see other languages not using loops, it is only because the loop is hidden
+ 1
You can do it using no loops :p
printf("0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n1 3 5 7 9 11 13 15 17 19\n0 2 4 6 8 10 12 14 16 18 20\n");
+ 1
@Baptiste E. Prunier,
Can you give a little explanation for the above codes.
+ 1
I'll try to be as clear as I can :
first, i go from 0 to 20.
When it has reached 20, j is put to 1 and i start at -1 (as it will be incremented by 2 at the end of the loop)
Then, it reach 21, if it happens, i start back at -2, go from 0 to 20 incremented by 2 each time.
At the end of this process, i ==20 and j==1 so the loop ends
0
Sir, suppose n[100], still it is not printing the whole array.
0
Sir how can I print whole array, Can you please tell me.
0
Oh Sir, actually I want to avoid using the 2nd loop.
I want to store all values of i in an array and I want it to print whole array from outside the loop.
0
Oh, I see. So basically printing a whole array needs a loop? I thought there would be another way doing it.