By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,918 Members | 2,225 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,918 IT Pros & Developers. It's quick & easy.

URGENT - how to make 0 to stop?

P: 12
I have one C programming problem:

Enter value, 0 to stop:
15
26
45
0

List now : 15 26 45 0 37814140
Value to change : 26
Want to change with value: 45
List now: 15 45 26 0 37814140

The problem is when I key in 0, it should stop, and the list only can show up to 45 only.
Why my output show 0 and 37814140, izzit my code is worng?

Below is my code:

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #define max 5
  3. int main()
  4. {
  5.     int num[max], i=0;
  6.     int swapFromNum = 0;
  7.     int swapToNum = 0;
  8.     int swapFromArrIndex = 0;
  9.     int swapToArrIndex = 0;
  10.     bool swapFromNumFound = false, swapToNumFound = false;
  11.  
  12.     printf("Enter value , 0 to stop: \n");
  13.     while(1)
  14.       {
  15.        scanf("%d", &num[i]);   // read value
  16.        if(num[i]==0)
  17.        break;       // if 0 finished
  18.        i++;
  19.       }
  20.  
  21.     printf("List now: ");
  22.  
  23.       for(i=0;i<max;i++)
  24.        {
  25.         printf("%d ",num[i]);
  26.        }
  27.        printf("\n");
  28.  
  29.  
  30.      printf("Value to change:");
  31.      scanf("%d",&swapFromNum);
and some more....
Mar 8 '07 #1
Share this Question
Share on Google+
2 Replies


Ganon11
Expert 2.5K+
P: 3,652
Suppose the user enters 3 values, then 0. (35, 20, 14, 0). Then there are only 4 values in the array - the 5th element is garbage, correct?

But when you display the list, you loop i from 0 to max (which is 5), printing every element of the array, garbage or not. You should keep track of how many values the user entered before the 0.
Mar 8 '07 #2

AdrianH
Expert 100+
P: 1,251
Suppose the user enters 3 values, then 0. (35, 20, 14, 0). Then there are only 4 values in the array - the 5th element is garbage, correct?

But when you display the list, you loop i from 0 to max (which is 5), printing every element of the array, garbage or not. You should keep track of how many values the user entered before the 0.
And you might notice that if you enter 10 numbers, strange things may happen after 5 and you may crash your programme.


Adrian
Mar 8 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.