08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 3 ■ Programs with Sequence Logic

Points to note about Program P3.4:

• The variable average is declared as double instead of int since the average

may not be a whole number.

• If whole numbers are not entered in the data, the program will crash or, at

best, give incorrect results.

• We use 3.0 instead of 3 in calculating the average. This forces a floatingpoint

division to be performed. If we had used 3, an integer division would

be performed, giving 13.0 as the answer for the sample data, above.

• In the last printf, the first \n is used to print the blank line in the output.

• We could have declared average and assigned to it in one statement,

like this:

double average = (a + b + c) / 3.0;

• The variable average is not really necessary in this program. We could

calculate and print the average in the printf statement with

printf("\nTheir average is %3.1f\n", (a + b + c) / 3.0);

3.5.2 Problem 2 - Square

Write a program to request a whole number and print the number and its square. The program

should work as follows:

Enter a whole number: 6

Square of 6 is 36

A solution is shown as Program P3.5.

Program P3.5

//request a whole number; print its square

#include <stdio.h>

int main() {

int num, numSq;

printf("Enter a whole number: ");

scanf("%d", &num);

numSq = num * num;

printf("\nSquare of %d is %d\n", num, numSq);

}

56

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!