What is the exact output of the program below in C If you co
What is the exact output of the program below in C++?
If you could explain why each cout occurs that would be great!
#include <iostream>
using namespace std;
int g = 20;
void runme1(int k)
{
k = k + 10;
cout << k << endl;
}
int runme2(int x)
{
g += 2;
return 10;
}
void runme3(int &g)
{
for(int i=0;i<10;i++)
g = g + 10;
}
int main()
{
int k = 10;
cout << (g+k) << endl;
cout << (g<0) << endl;
g = 10.0/3.0;
cout << g++ << endl;
if(k>10)
cout << (g+k) << endl;
else
cout << (g-k) << endl;
runme1(k);
cout << k << endl;
k = runme2(g);
cout << g << endl;
cout << k << endl;
runme3(k);
cout << k << endl;
cout << ++k << endl;
return 0;
}
Solution
main.cpp
#include <iostream>
using namespace std;
int g = 20;
void runme1(int k)
{
k = k + 10;
cout << k << endl; //runme1(10) print k=k+10 = 10+10 = 20
}
int runme2(int x)
{
g += 2;
return 10;
}
void runme3(int &g)
{
for(int i=0;i<10;i++)
g = g + 10;
}
int main()
{
int k = 10;
cout << (g+k) << endl; //g+k = 20+10 = 30
cout << (g<0) << endl; // if g<0 true(1) otherwise false(0)
g = 10.0/3.0;
cout << g++ << endl; //g = 10.0/3.0 = 3, it will print g = 3 then g++
if(k>10)
cout << (g+k) << endl;
else
cout << (g-k) << endl; // if k>10, false, so print g-k = 4-10 = -6
runme1(k);
cout << k << endl; // return nothing so k = 10
k = runme2(g);
cout << g << endl; //runme2(4), it will give g=4+2=6
cout << k << endl; // runme2(4) return 10 so k = 10
runme3(k);
cout << k << endl; //runme3(10), it is taking address of g, add g to 10, ten times so k become 110
cout << ++k << endl; //++k = 1+110 = 111
return 0;
}
Output :-

