I was writing a program that takes in 5 numbers, and calculates the lowest number and outputs it. The code I wrote didn't work at first (the example below does, and I don't know EXACTLY why), until I found an example online and I found I was missing a statement. Below in the code I have comments further explaining my confusion.
#include <iostream>
usingnamespace std;
int main()
{
int array[5];
int z;
for (int x=0; x<5; x++)
{
cin >> array[x];
}
z=array[0]; /* This is the bit I don't understand, why do I need to
assign z to the first element in array, after I have taken input
to each element in the for loop above */
for (int x=0; x<5; x++){
if (array[x] < z){
z=array[x]; /* Why isn't this enough?
why do I have to assign z up above? */
}
}
cout << z;
}
If anybody could explain why I needed to assign z to the first element, and not the element that x was pointing to. I would greatly appreciate it.
If z is not set to any value, it will hold a junk value. This value can be anything an int can hold, so can definitely mess up any calculations. It's good practice to initialize variables before using them to avoid problems like this.
If you did not assigned z as array[0], it would be NULL/garbage.
If that is so, when doing the first test:
1 2 3 4
if (array[x] < z)//z is not initialized, cannot be compared
{
z=array[x];
}
x=0;
array[0] = (what you input earlier, which is okay)
z = Error (has not been assigned)
So when comparing (array[0]<z), you would get error or undefined behavior.
You could literally assign anything to z, but it must be initialized before used.
Oh I understand, if it doesn't have anything to compare it to then I will get the incorrect results. So that's why I was getting a number equal to the max value an int could hold as an output...
I really appreciate you guys putting up with my dumb questions! Thanks!