Click here to Skip to main content
14,359,798 members
Rate this:
Please Sign up or sign in to vote.
See more:
#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 7:36am
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

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++
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

try to replace
test–;

with
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.
   
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.
Rate this:
Please Sign up or sign in to vote.

Solution 2

int main(void) {
int arr[10],k=0,test=6;
while(test>0){
arr[k]=test;
printf("%d ",arr[k]);
k++;
test--;
}
return 0;
}
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100