c++: What does 'while (cin >> variable, variable)' exactly do? - c++

So here's that piece of code, very basic but i just can't find any similar questions that have two variables in the while loop with cin in it.
void Perm(int start, int end, int a[]) {
//some recursion code
}
int main() {
int i, n, a[10];
while (cin >> n, n) {
for (i = 0; i < n; i++)
{
a[i] = i + 1;
}
Perm(0, n, a);
}
return 0;
}
Can't figure out what does while (cin >> n, n) part do, and when will it stops. It looks like when I run the code, the input is just required once..

The comma operator performs the expression to the left of the comma and discards the result then performs the expression on the right and offers up the result for testing. So, in English
while (cin >> n, n)
says, read from Standard In into integer n and discard whether or not the read was successful, then test the value of n. If n is not zero, enter the loop.
With a modern compiler the point is sort of moot, but I believe it would read better as
while (cin >> n && n)
or in English, if we successfully read from standard in into integer n and n is not zero, enter the loop. It conveys the intent better, but it's moot because if the read fails, as of C++11 n will be set to zero and still exit the loop. Before C++11 you probably got an infinite loop testing the last good, non-zero value of n over and over forever.
As explored in the comments below the point seems to be not so moot. It appears that under some conditions, no data given in this case, the value is not being zeroed. More Standard-reading required here, but it looks as though
while (cin >> n && n)
or similar is required to catch all of the cases.

In the condition of the while statement
while (cin >> n, n) {
there us used the comma operator.
That is the expression consists from two subexpressions, cin >> n and n, that are executed sequentially. The result of the condition is the value of the second subexpression that is implicitly converted to the type bool.
From the C++ 17 Standard (8.19 Comma operator)
... A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression
(Clause 8). Every value computation and side effect associated with
the left expression is sequenced before every value computation and
side effect associated with the right expression. The type and value
of the result are the type and value of the right operand;...
The while loop can be equivalently rewritten like
while (cin >> n, n != 0 ) {
It would be more safer to write the condition of the while statement like
while (cin >> n, n != 0 && n <= 10 ) {
Instead of the comma operator it would be better to use the logical AND operator like for example
while (cin >> n && n != 0 && n <= 10 ) {

Related

why this code does not work only when i provide a number having zero in it ? for example t=1 and string = "1012"

In this question what I have to do is: find the no. of digits in the given string which are divisor of the complete number represented by the string.
For numbers without 0 in it it is working fine. for example t=1 , s="12" , output=2
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
long long t,i,n,ct;
cin>>t;
while(t--)
{
ct=0;
cin>>s;
n=stoi(s);
for(i = 0; i < s.length(); i++)
{
if(n%(s[i]-'0') == 0 && s[i] != '0')
{
ct++;
}
}
cout<<ct<<endl;
}
}
if(n%(s[i]-'0') == 0 && s[i] != '0')
For a start, this is in the wrong order. You want to ensure it's not '0' before attempting a division-type operation. The reason for this is that C++ uses short-circuiting operation so that in the following code, if xyzzy is false, plugh will never be evaluated:
if (xyzzy && plugh)
If xyzzy is a "dangerous" operation that shouldn't happen when plugh is false, you'll get into trouble.
In your specific code, what you have will first try to evaluate the division before checking the digit. So, it will allow division by zero to be performed, not really a good idea. It would be safer to use:
if ((s[i] != '0') && (n % (s[i] - '0') == 0))
There's a few other minor issues in your code such as signed/unsigned comparisons, or the not-really-necessary use of long long(a), or not following the guideline of declaring variables where they're needed rather than at some point long before then (such as at the top of the function).
But it's the order of the sub-expressions in the if statement that's most likely your immediate issue.
(a) Just how long do you expect these strings to get? :-)

What is the use of "and N" in this code?

C++ Code:
#include<iostream>
using namespace std;
int main()
{
int N;
cin>>N;
int *A = new int[N];
int i=0;
for(i=0;i<N;i++)
cin>>A[i];
while(cout<<A[--N]<<' ' and N);
delete[] A;
return 0;
}
Print the integers of the array in the reverse order in a single line separated by a space.
Does anyone know what is "and N" do in cout statement?
It's a cryptic way of writing:
while( (cout<<A[--N]<<' ') and (N != 0) );
// output is successful and N is not equal to zero.
It could be written more clearly as:
for ( ; N != 0; --N)
{
cout << A[N-1] << ' ';
}
Since it's theoretically possible for N to be negative, it will be better to use:
for ( ; N > 0; --N)
{
cout << A[N-1] << ' ';
}
N is an integer variable, value of type int can be implicitly converted to bool (non zero becomes true and zero becomes false). So the expression basically sais execute when result of operator<< converted to bool is true and N is not equal to zero. Logically this code
while(cout<<A[--N]<<' ' and N);
is equal to:
do {
bool b1 = cout<<A[--N]<<' ';
bool b2 = N;
} while( b1 and b2 );
actual code is a little different due to short circuit but that differences are unimportant in this case.
The part and N that can be also written like && N of the while statement
while(cout<<A[--N]<<' ' and N);
that as it has been pointed out can be rewritten like
while(cout<<A[--N]<<' ' && N != 0);
checks that N that is being decreased (A[--N]) in each iteration of the loop is not equal to 0.
So the loop outputs elements okf the array in the reverse order.
The word and is a so-called alternative token for the primary token &&.
It is just a way of writing the code by some programmers.
It is actually written as
while( (cout<<A[--N]<<' ') and (N != 0) );
Basically 'and' operator returns true when both operands are non zero values.
So cout will give number of characters it printed which will be non zero in this case and until the value of N becomes zero your loop will be execute.

C++ ? operator with continue operator in for loop

I have a method which looks like this:
bool Perfect(int num) {
int sum = 0;
for (int i = 1; i < num; i++)
{
num%i == 0 ? sum += i : continue;
}
return sum == num ? true : false;
}
I'm trying to combine here ? operator with continue operator...
So logically if the statement here is false in this line:
num%i == 0 ? sum += i : continue;
I will just skip the iteration or do nothing?
If I do it like this the compiler reports an error like:
expected an expression
And in case like this:
num%i == 0 ? sum += i
It says:
Expected a ':'
Is there any way to use continue with ? operator or just simply avoid false case somehow ???
bool Perfect(int num) {
int sum = 0;
for (int i = 1; i < num; i++)
{
if(num % i == 0)
sum += i;
}
return sum == num;
}
Use an if statement. No need of continue since you have no other statement after sum += i.
C++ and C have both statements and expressions (notice that an assignment or a function call is an expression, and that expressions are statements). They are different syntactic (and semantical) things.
You could have coded (but this is weird style as a statement reduced to a ?: conditional expression) inside your for loop:
(num%i == 0) ? (sum += i) : 0;
(when num%i is non-zero, that evaluates to 0 which has no significant side effect; BTW that last occurrence of 0 could be 1234 or any constant integral expression)
Some programming languages (notably Scheme, read SICP) have only expressions (and no statements).
The ternary ?: operator applies to expressions and gives an expression (so can't be used for statements).
Conditional statements use the if keyword. In your case it is much more readable (because you are using sum += i only for its side effect) and an if statement is here easier to understand.
You can't use a ternary operator in this way. You would normally use it for assigning a value to a variable based on an expression being true or false. Eg.
int j, i,
j = (i == 2) ? 5: 10;
If i is equal to 2 then j is given the value of 5 else if i is not equal to 2 then j is given the value of 10.

Arrays a[count++]

I'm a beginner in C++ so please bear with me. Below is just a part of the full program.
When the user inputs the first number (assume '3'), it goes to the if statement.
a[count ++] then becomes a[1] (if I'm not wrong, because count is initially 0). The array element a[1] thus stores the input which is 3. If so, then didn't the program just skip a[0]?
int readarray(int a[], int capacity) {
int count = 0;
int input;
do {
cout << "Enter a number (-1 to stop): ";
cin >> input;
if (input != -1) {
a[count++] = input;
}
} while (input != -1 && count << capacity);
return count;
Because count++ is a post increment operator. It uses the current value of count in the expression and also increments count. It's not defined how or when the increment happens so any other uses of count in the same statement could have unexpected results.
The statement is equivalent to writing
a[count] = input;
count = count + 1;
As a matter of personal opinion I think you should never use the pre/post increment/decrement operators in an expression. It doesn't produce any more efficient code, it is rather less readable and tends to end up with off by one errors.
No, postfix increment (x++) returns the old value of the variable. So a[count++] increments count from 0 to 1, but uses 0 (the old value of count) as the index.
By the way, count << capacity looks wrong. Did you mean count < capacity?
Instead of a[count++] you can do if(input != -1){a[count] = input; count++}. In this way the value will be assigned to current array index say at start, it will be assigned to a[0] and then count will be incremented to 1. So next iteration will have a[1].

How to correctly use Boolean functions?

I'm having trouble with the following assignment, mostly because I don't understand how a Boolean function works. "Write a function called Divisible that takes in two numbers as parameters. Return True if the first number is
evenly divisible (no remainder) by the second number. Otherwise return False. Hint: Use %"
Currently what I have is:
int Divisible()
{
int firstNum;
int secondNum;
int result;
cout << "Please enter any integer: ";
cin >> firstNum;
cout << "Please enter another integer: ";
cin >> secondNum;
result == firstNum%secondNum;
}
I'm not sure what to do beyond that. I thought I could assign bool = 0 as true but that doesn't appear to be the case. I'm still very new to C++ so any help would be appreciated.
The question asks you to write a method that takes the numbers as parameters, not let's you input them from standard input.
Boolean is a type of its own in c++, so you want the method to return bool and not int.
An easy to read solution:
bool Divisible(int a, int b) {
int remainder = a % b; // Calculate the remainder of a and b.
if(remainder == 0) {
return true; //If the remainder is 0, the numbers are divisible.
} else {
return false; // Otherwise, they aren't.
}
}
Or more concise:
bool Divisible(int a, int b) {
return (a % b) == 0;
}
Even more concise:
bool Divisible(int a, int b) {
return !(a % b);
}
When creating functions or using them always remember to start with the signature.
Think what will this function need to work with, and what will it return. You need to return if something is true or false, which are values of data type bool. Just like in a conditional such an if statement you may use Boolean operators like ==, != and etc.
So you need to return a bool and check if two numbers are divisible. Therefore:
bool Divisible(int a, int b){
// == boolean operator that will return true if a%b evaluates to 0
// false if not
return (a % b) == 0
}
Once you start thinking of functions this way, every program becomes one great puzzle!
In methods that return boolean, you want to first determine what the value of the result will be when the method returns true, and then use the == operator to evaluate any result you get against the acceptable result.
So in your case, you are trying to determine whether to return true or false depending on if the first number is evenly divisible by the second.
First thing you do is you take a case that should work, ex:
4, 2
How do you know 4 is divisible by 2? Well this means that if I divide 4 by 2, then the remainder should be zero. This is what the % operator returns. If you do 4 % 2 the value is zero.
Ok so now you have the correct result so what you simply do now is to evaluate any result you get against the accepted result like so:
int isDivisible(int a, int b)
{
const int acceptedAnswer = 4 % 2;
if ( a % b == acceptedAnswer )
return 1;
return 0;
}
And there you have it, any value you get that does not equal your accepted answer will return 0 or not equal (!=) and any other answer will return 1 or equal (==)
You don't return; or assign a result...
result = firstNum%secondNum;
return (result == 0); // Assuming you want 0 as true.
In general, the value 0 is false and any value that is not (!0) is true. By convention, that is 1.
what you have done is correct but in last line you are comparing an uninitialized integer with result (remainder of division).
set int result=0;
and then do this:
return result==firstNum%secondNum; // checks if remainder is zero (true if zero)
you could also simply do return (firstNum%secondNum)==0
Furthermore, your assignment asks for a function that takes in two numbers as parameters (input arguments).
So your function prototype should be something like:
bool Divisible(int a, int b);
and you should use a and b in the function instead of taking input from stdin as you are doing right now.
bool is a type that can hold only two values: true and false. You use it for expressing truth values, as whether a number divides another or not.
In your case, the function could have been implemented as follows:
bool is_divisible(int a, int b)
{
return a % b == 0;
}
In the assignment there is clear written that the function must have two parameters. So the function could look the following way (C++)
inline bool Divisible( int n, int m ) { return ( n % m == 0 ); }
or (C)
inline _Bool Divisible( int n, int m ) { return ( n % m == 0 ); }
In the last case you may substitute return type _Bool for int. In the firt case that is when C++ is used it is better to use return type bool.
The request to enter two numbers shall be outside the function. The function only allows to determine whether one number is divisible by other number.