In: Computer Science
C++ Questions:
7. What is a potential problem with the code below:
int x=4.5;
8. Write a C++ code snippet to input a whole number from the user and output double the number to the screen.
9. True/False. Assume x is an int which has been declared and assigned a valid value. The value of x is guaranteed to change after this code snippet:
if (x<0) x--; else x++;
10. Consider the below code snippet. Will it compile? What is a likely error?
int score = 0; if (score = 0) cout << "We had a shutout today!\n";
11. Write a loop which prints out the even numbers from 0-100, including 0 and 100, to the screen.
12. Same as Question 11, but count down from 100 to 0, even numbers only.
7)
int x = 4.5, its called as an lossy onversion because the 4.5 is the float value and it is getting converted into the integer value so that lossy of data occurs, if we try to print the value of x it will prints 4
8)
#include <stdio.h>
int main()
{
int x;
printf("Enter the value of x : ");
scanf("%d", &x); // read the value
double y = (double) x; // convert it into double
printf("Double : %lf", y); // print the double value
return 0;
}
9)
True, Yeah the x value will change at the end of the execution of the program, If it falls in the IF condition it will get decremented or in the else condition it will get incremented
10)
Yeah the code will compile successfully
if(score = 0), in the if condition the score is initialized with the value 0, where the if condition returns false and the statements inside the if statements will not execute
Likely error in this case we can simply called a logical flaws errors, where we are initialize score with the 0 instead of comparing them, where the logical execution of the program will disrupts
in the above code we can re-write the if condition as :
if(score == 0) // now the compare the score with the value 0
11)
#include <stdio.h>
int main()
{
printf("Even numbers are : \n");
for(int i = 0; i <= 100; i++)
{
if(i % 2 == 0) // checking if it is even number
{
printf("%d ", i); // then print the number
}
}
return 0;
}
12)
#include <stdio.h>
int main()
{
int count = 0;
printf("No of Even numbers are : ");
for(int i = 0; i <= 100; i++)
{
if(i % 2 == 0) // checking if it is even number
{
count++; // then increment the count
}
}
printf("%d", count);
return 0;
}