Questions and Answers
Task 1: Selection structures: if statement
Task 2: Using only the techniques you learned in this chapter, write a
program that calculate the squares and cubes of the number from 0 to
10 and uses tabs to print the following table of values:
number sequare cube
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
Reference Code:
#include <stdio.h>
int main(void)
{
// initialization
int i;
printf("Number\tSquares\tCubes\n");
// iterate i for ten times
for (i=0; i<=10; i++){
printf("%d\t%d\t%d\n", i, i*i, i*i*i);
}
return 0;
}
Note: we use a repetition sturcure by for statement.
, Task 3: Write a program that reads in the radius of a circle and prints
the circle’s diameter, circumference and area.
Hints:
1. using floating-point numbers %f instead of %d to print out the result.
2. float pi; pi = 3.14156.
3. diameter = 2*radius; circumference = 2*pi*radius; area = pi*radius*radius.
Reference Code:
#include <stdio.h>
int main(void)
{
// initialization
float radius, diameter, circumference, area;
float pi = 3.14156;
// input radius
printf("Please enter the radius:\n");
scanf("%f", &radius);
// calculate diameter, circumference and area
diameter = 2 * radius;
circumference = 2 * radius * pi;
area = radius * radius * pi;
// output and termination
printf("Diameter is: %f\n", diameter);
printf("Circumference is: %f\n", circumference);
printf("Area is: %f\n", area);
// return the value of main function
return 0;
}
Task 4: Write a program that asks the users to enter two numbers, and
obtains the two numbers from the user and prints the sum, product,
difference, quotient and remainder of the two numbers.
Reference Code:
#include <stdio.h>
int main(void)
{
// initialization
int num1, num2;