Can someone explain this

Ok so I did the thing in the begginers excercises on this website. I got to the pancake one and I did the code right but I know knowing how to do it but not knowing why it works is as bad as not knowing how to do it. so here is the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  #include "stdafx.h"
#include <stdio.h>
#include <string>
#include <iostream>
#include<stdlib.h>

using namespace std;


int main()
{
	int pcakes[10];
	int max = 0;

	for (int i = 0; i < 10; ++i){
		cout << "enter the pancake amount for person" << i + 1 << endl;
		cin >> pcakes[i];

		if (pcakes[i] > max)
		{
			max = pcakes[i];
		}
	
		
	}
	cout << "the max number is " << max << endl;
	
	system("pause");
	return 0;
}



the other libraries is there from other things..but my question is why does that work, it does not make sense to me , if pcakes[i] si greater then max then max = pcakes[i]. but wouldnt that mean that if pcakes is greater which it is if its above 0 then pcakes would be 0 since max is 0?
Ok I am dumb, after asking it on here i see now, max becomes pcakes[i]. but my new question is...how does it know to give max the highest value? since there is 10 other values in pcakes?
closed account (j3Rz8vqX)
The max variable is being defaulted to the lowest non negative value 0.

So in your case, if you entered a pancake with greater value than 0, it would assign that value to max.

If checks for true if (pcakes[i] > max)

max = pcakes[i]; assigns max the value of pancake, not the other way around; right side argument is assigned to left side argument.
I see, so each number higher then the last is what max's new number is? thats hwo it gets the highest number in there?
closed account (j3Rz8vqX)
Yes.

max will change if a number is higher than itself.

The next cycle would compare to the new max value; not zero.
Eventually leading to storing the highest number entered by the user.
Topic archived. No new replies allowed.