3.4 Write a C statement to accomplish each of the following tasks. a) Define var
ID: 3687030 • Letter: 3
Question
3.4 Write a C statement to accomplish each of the following tasks. a) Define variables sum and x to be of type int. b) Set variable x to 1. c) Set variable sum to 0. d) Add variable x to variable sum and assign the result to variable sum. e) Print " The sum is: " followed by the value of variable sum. 3.10 (or 3.11 for 6th edition) Identify and correct the errors in each of the following. [ Note: There may be more than one error in each piece of code.] a) if ( age >= 65 ); puts( " Age is greater than or equal to 65" ); else puts( " Age is less than 65" ); b) int x = 1, total; while ( x <= 10 ) { total += x; ++ x; } c) While ( x <= 100 ) total += x; ++ x; d) while ( y > 0 ) { printf( "% d n", y ); ++ y; } Program: 3.5: Combine the statements that you wrote in Exercise 3.4 into a program that calculates the sum of the integers from 1 to 10. Use the while statement to loop through the calculation and in-crement statements. The loop should terminate when the value of x becomes 11.
Explanation / Answer
3.4)
#include<stdio.h>
int main (int argc, char *argv[])
{
//a
int sum, x;
//b
x = 1;
//c
sum = 0;
//d
sum = sum + x;
//e
printf("The sum is: %d ", sum);
return 0;
}
3.10)
#include<stdio.h>
int main (int argc, char *argv[])
{
//a)
if ( age >= 65 );
puts( " Age is greater than or equal to 65" );
else
puts( " Age is less than 65" );
//b)
int x = 1, total = 0;
while ( x <= 10 ) { // here is problem, total is not initialized, so initially it contains garbage value
total += x; // so it will not produce correct result
++ x;
}
//c)
While ( x <= 100 ) {
total += x;
++ x; // here is problem, ++x, this is not part of while loop, so value of x will not increase and end with infinite loop
}
//d)
while ( y > 0 ) {
printf( "% d n", y );
++ y;
}
return 0;
}
3.5)
#include<stdio.h>
int main (int argc, char *argv[])
{
//a
int sum, x;
//b
x = 1;
//c
sum = 0;
//d
while(x <= 10){ // code to sum upto x=10
sum = sum + x;
x++;
}
//e
printf("The sum is: %d ", sum);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.