I'm trying to understand while loop, and the difference when I put "!" and "false" as a condition because somehow they produced different result for me.
I'm writing this very simple program to sum an array of numbers, and I want to check if my input is integer or not.
Flowchart :
1. Ask user how many numbers to sum
2. Get user input (check if this is integer or not)
3. (loop) ask user to input each value of number
4. sum them
What I have tried:
This is my code, I'm using `isdigit` to check whether an input is an integer, and check it using
while (isdigit(array_size==false))
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int array_size;
int sum = 0;
int main(){
cout << "How many numbers ? " << endl;
cin >> array_size;
while (isdigit(array_size==false)){
cout << "Input is not a number " << endl;
break;
}
int sum_array[array_size];
for (int n=0; n < array_size; n++){
cout << "Number " << n+1 << " is : ";
cin >> sum_array[n];
sum+=sum_array[n];
}
cout << "Sum of numbers are : " << sum << endl;
return 0;
}
Here's the result when I tried to input integer and non-integer :
lock@lock ./a.out
How many numbers ? 3
Number 1 is : 1
Number 2 is : 2
Number 3 is : 3
Sum of numbers are : 6
lock@lock ./a.out
How many numbers ? a
Sum of numbers are : 0
See that in the second case when I put a non-integer, my line
cout << "Input is not a number " << endl;
is not being executed.
Now if I changed my condition with
while (!isdigit(array_size)), here's the result :
lock@lock ./a.out
How many numbers ? 3
Input is not a number
Number 1 is : 1
Number 2 is : 2
Number 3 is : 3
Sum of numbers are : 6
lock@lock ./a.out
How many numbers ? a
Input is not a number
Sum of numbers are : 0
Apparently the line
cout << "Input is not a number " << endl;
will be executed no mater what the input (even if it's integer). What did I miss here ? How did "!" different from "false".