I'm trying to write a program that asks the user to input 10 numbers, and then print the largest number input. I'm having some trouble getting my for loop to work correctly.
Just saw that k wasn't initialized. I know that you can find out which one is largest once they're in the memory, that's the part I'm having trouble with. Here's the code so far, but it's still giving me the wrong number as the largest:
First, it should be i = 0; i < 10, otherwise you'll only have 9 numbers.
Second, to get the largest number just take the first number as the largest, if the next number is larger then that one becomes the largest otherwise just move to assess the next number ...
All you need is a simple for loop through the array of 10 numbers. You can delete lines 16 and 17.
Is there a reason you need to retain all values that are input? If not, you don' t need an array to store them, you don't need any of lines 16 through 24 if you compare each number to the preceding one.
Also - it's not a good idea to modify the counter within its own loop as in line 22.
1 2 3 4 5 6
// let's assume array[0] == 3, array[1] = 5, array[2] == 4, array[3] == 7
//now -- starting from array[0] (3)
// with k = 0 and j = 1
// when k arrives at 2:
// if array[2] < array [1], which it is, you set your counter k back to j (1) and the loop will never end.
//Better to start with j at zero, change it to array[k] value when array[k] is larger
if you still want to use j as a pointer into array, then set j to k in line 22, not the other way around, and make sure your comparison is going the right way in line 20. As it is, you're actually going to find the smallest number, not the largest.