PDA

View Full Version : scanning multiple inputs


mivec
06-03-2004, 07:39 AM
hie, i am quite new to C++..and i can't get this thing done..it's something like that:

Quote:

A program that reads 10 integers (from 1 to 99 inclusive) and prints the first and last on one line, the second and the ninth on the second line, the third and the eighth on the next line, and so forth. It should look like the following sample.

Please enter 10 numbers:
10 31 2 73 24 65 6 87 18 9

Your numbers are:
10 9
31 18
2 87
73 6
24 65
[/QUOTE]

and also how can i make it like the user can input the 10 numbers randomly from 1-99?that means the 10 numbers are not fixed as seen above.something like the below(i am not sure about the code so i am just assuming):

int numbers[10];
printf("Enter 10 numbers");
scanf("d% d% d% d% d% d% d% d% d% d%", &numbers[10]);



can someone pls help me?i know it's kinda simple but i am new in C++.....if possible, is there a code for this simple programme? :(

Jason
06-03-2004, 10:55 PM
that is like the perfect answer right there...you just need to use the printf command again...


int numbers[10];
printf("Enter 10 numbers");
scanf("d% d% d% d% d% d% d% d% d% d%", &numbers[10]);


now all you need is to print the numbers in the correct ofder...something along the lines of


printf("your numbers are:\n");
printf("d% d%", numbers[1], numbers[10]);
................


just keep going...


Jason

Unit
06-03-2004, 11:33 PM
Those statements are wrong.


int numbers[10];
printf("Enter 10 numbers");
scanf("d% d% d% d% d% d% d% d% d% d%", &numbers[10]);


the scanf statement is wrong for reasons highlighted.

first thing you can do is to correct them.. like this..

int numbers[10];
printf("Enter 10 numbers");
scanf("%d %d %d %d %d %d %d %d %d %d", &numbers[0],&numbers[1],&numbers[2],&numbers[3],&numbers[4],&numbers[5],&numbers[6],&numbers[7],&numbers[8],&numbers[9]);


Note that each format specifier is of the form %? where ? should be replaced by the format we want to input/output. Also note that for scanf, the number of arguments after the format string should match the number of format specifiers in the format string. (10 in this case)

Now that we fixed the error, we will want to write that using streams which are the common way of I/O from c++

int numbers[10];
cout << "Enter 10 Numbers" <<endl;
cin >> numbers[0] >>numbers[1] >> numbers[2]........>> numbers[9];


This is obviously very inefficient since we have to list each number.
the trick is to run this in a loop with an index going from 0 to 9 and read them in the loop one by one.

the same goes for the output you require.

the basic logic is to loop through the numbers using index x from 0 to 4 and print

numbers[x], numbers[9-x]

I will not write the code here since it is a school assignment and you should work to get it done.

mivec
06-07-2004, 07:26 AM
thanks alot guys...i think i got it to work my way by ur advices did help...thanks once again.:).