...

View Full Version : C++ Array stops when inputs 0



flint0131
09-22-2009, 06:31 PM
Help me please! :(

Here's the problem..


Write a program that inputs integers until a 0 value is entered. The integers will be stored in an array that can hold a maximum of 50 integers.


I tried making it with this code :


#include <iostream.h>
#include <conio.h>

void main() {
clrscr();
int numbers[50], i;
do {
i++;
cin >> numbers[i];
} while ( cin >> numbers[i] == 0 );
}


The problem is, the looping will stop after entering the second input.
I need help A.S.A.P. :(

flint0131
09-22-2009, 06:33 PM
Here's the real problem..



Write a program that inputs integers until a 0 value is entered. The integers will be stored in an
array that can hold a maximum of 50 integers. The program will then find and display the
largest integer and the smallest integer.


and I really need a code for this one. :(

oracleguy
09-22-2009, 06:49 PM
Your loop doesn't work because calling cin again will cause it to ask for another number, which isn't what you are intending. Further more, cin >> numbers[i] returns something other than what the user entered. I believe it returns if there was an error or not. Which is why your loop is exiting.

I'm surprised your program hasn't crashed, you must be getting lucky that the debugger is setting the variables to 0 automatically. Are you getting a warning saying you are using a variable that hasn't been initialized? You are using i without ever setting the value.



#include <iostream>
#include <conio>

void main() {
clrscr();
int numbers[50];
int i = 0;
do {
cin >> numbers[i];
i++;
} while (numbers[i - 1] == 0);
}


And in your code you are incrementing i before you use it even once which means you'll only be able to store 49 values. Plus you aren't making sure someone doesn't enter more than 50 numbers. I'll leave that part up to you to fix.

Shyama_Mukherji
09-30-2009, 12:22 PM
//Try this code to stop loop at i=0


#include "stdio.h"
void main()
{
int i, Arr[50];
i=1;
while ((i != 0)&&(i<50))
{
scanf("%d",i);
Arr[i]=i;
printf("%d",i);
}
}

oracleguy
09-30-2009, 06:01 PM
//Try this code to stop loop at i=0


#include "stdio.h"
void main()
{
int i, Arr[50];
i=1;
while ((i != 0)&&(i<50))
{
scanf("%d",i);
Arr[i]=i;
printf("%d",i);
}
}
That would be helpful however this is a C++ question and you wrote C. Plus since this is a homework question we try to avoid just giving full answers away.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum