Problem with assigning a value to a array

Joined
Nov 12, 2006
Messages
3
Reaction score
0
Hi, I am a new in C/C++ , and this years if my first in programming in this langauges.

I have this assignement: Write a program that after you enter a certain number, it writes it backwards
Examples:
Input: 1234567
Output: 7654321
Preferrably use arrays. (The lessos is about arrays)

This is what i wrote:

void main ()
{
cout<<"\nEnter a number :";
int num;
cin>>num;
cout<<"\nThe number you have entered is : "<<num<<"\n";

int masiv[40];

int tempnum;
int i;
i = 0;
tempnum = num;
while (tempnum != 0)
{
masiv = tempnum%10;
tempnum = tempnum/10;
i = i+1;
cout<<masiv<<" "<<tempnum<<"\n";
};

}

I hope you get what the idea is.
But as soon as i run the program this is what i get:


Enter a number :1234567

The number you have entered is : 1234567
-858993460 123456
-858993460 12345
-858993460 1234
-858993460 123
-858993460 12
-858993460 1
-858993460 0
Press any key to continue

To explain why i do this loop: It is intended in order to check if i get the correct values in the correct places. For example if the masiv actually gets a single number in every incrementation of the loop and if this number is correct with what it should be.
Now the question is why instead of the different numbers i should be getting as elements of the array "masiv" i get this "-858993460" seamingly random number as output.

I hope i explained myself good enough :)
 
Joined
Nov 12, 2006
Messages
1
Reaction score
0
How did you fix it?

atk0309 said:
Oh well, after 3 hours looking at it ... sorry for bothering, i found my problem.

Can you show how you fixed it for a newbie?:shake:
 
Joined
Nov 12, 2006
Messages
3
Reaction score
0
while (tempnum != 0)
{
masiv = tempnum%10;
tempnum = tempnum/10;
i = i+1;
cout<<masiv<<" "<<tempnum<<"\n";
};


In here i am cout-ing an element in the array that still has no value assigned to it.

If you note that i first increment i = i+1 and now the pointer is on the next element but as it still has no value assigned, it shows the strange stuff.
And this is how it works just fine:
while (tempnum != 0)
{
masiv = tempnum%10;
tempnum = tempnum/10;
cout<<masiv<<" "<<tempnum<<"\n";
i = i+1;
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top