Things you should previously know::
Some C++ knowledge, along with some Array knowledge
Let's get into it.
Finding max value::
First, make your array. In this tutorial I will use "Array" as the name for it.
int Array[] = {1,2,3,4,5};
The numbers in the brackets {}, are the values stored in Array[]. The number 1 is stored in Array[0], the number 2 is stored in Array[1], and so on.
Now, make an int, and set it equal to 0
int maxValue = 0;
This int will store the value of the highest number in the array.
Make a for loop::
for(int i = 0; i < 5; i++){
The purpose of the for loop, is to take the index i and put it in Array[]. Thus making it Array[i]. And since values are stored into Array[0],Array[1]... You can call those values easier by using Array[i], and having i++ every time it is less than 5.
if(Array[i] > maxValue){
maxValue = Array[i];
}
What this if statement is saying, is that if the value stored in Array[i] is greater than maxValue (it is 0 the first time through the for loop) it will store the value in Array[i] as maxValue. Now it will do this 5 times, and every time Array[i] is greater than maxValue, it will store that value in it.
So, with the values in our Array, it will go through and see if 1 is greater than 0. Since it is, it will store 1 into maxValue. Now it will go through the program with Array[i] as 2. Since 2 is greater than 1, it will store it into maxValue. It will continue through this 5 times, leaving the value 5 as maxValue, and that is our highest number!
}
cout << "The highest value is: " << maxValue;
What I did there, was close the for loop, so it only prints the highest value once, then it prints it out.
And that's it to find the max number!
*************************************************
Finding min value::
Since finding min value is almost the same, just backwards, I will go through this a little faster
int Array[] = {1,2,3,4,5};
int lowestNum = Array[0];
I assigned lowestNum to the value in Array[0], so I can compare the other values to it
for(int i = 1; i < 5; i++){
Notice I started the int i at 1 this time. Rather than 0. I did this because I want to start at spot Array[1], so I can compare Array[1] to Array[0] (Which is lowestNum)
if(Array[i] < lowestNum){
lowestNum = Array[i];
}
}
cout << "The lowest number is: " << lowestNum;
Okay, now in the if statement, I have it where if the value stored in Array[i] is less than lowestNum, it will store the value if Array[i] into lowestNum, so it can be compared to the next Array value. I close the if statement and for loop, the print out the value.
And there you go, if you have any questions, feel free to post or send me a message!





MultiQuote







|