Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C
#include <stdio.h>

int main(void) {
// your code goes here
int arr[10],k=0,test=6;
while(test>0){
arr[k]=test;
k++;
test–;
printf("%d ",arr[k]);
}
return 0;
}

Output
0 -6269075 11015 0 0 0

What I have tried:

in loop initializing problem doesn't occur but if i use other loop to initialize it array did't take desire values
Posted
Updated 5-Jun-19 6:36am
v2

let's say you are initialising the first element, so k is 0

arr[k]=test; // arr[0] has been given the value test
k++; // k is now 1
test–;
printf("%d ",arr[k]); // you're printing arr[1] which has yet to be given a value


do the printf before the k++
 
Share this answer
 
try to replace
C++
test–;

with
C++
test–-;

And look very carefully at when you print and what you print.

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

1.11 — Debugging your program (stepping and breakpoints) | Learn C++[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 
v2
Comments
jeron1 5-Jun-19 10:44am    
Good point, I can't imagine that test-; would actually compile.
Patrice T 5-Jun-19 11:02am    
I suspect he made a mistake while copying the code.
int main(void) {
int arr[10],k=0,test=6;
while(test>0){
arr[k]=test;
printf("%d ",arr[k]);
k++;
test--;
}
return 0;
}
 
Share this answer
 
Comments
Stefan_Lang 6-Jun-19 3:54am    
While your code may be correct, for these kind of questions it is usually better to explain why something doesn't work instead of just posting the correct code.

Give a starving man a fish and he will live for a day. Teach him to fish and he will live for years.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900