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 5 ■ Programs with Repetition Logic

Program P5.5

//find the smallest of a set of numbers entered

#include <stdio.h>

int main() {

int num;

printf("Enter a number (0 to end): ");

scanf("%d", &num);

if (num == 0) return; //halt the program

int smallNum = num;

while (num != 0) {

if (num < smallNum) smallNum = num;

printf("Enter a number (0 to end): ");

scanf("%d", &num);

}

printf("\nThe smallest is %d\n", smallNum);

}

In C, the keyword return can be used in main to halt the program by "returning" to the

operating system. We will discuss return in more detail in Chapter 7.

When run, if numbers are entered in the following order:

36 17 43 52 50 0

the program will print

The smallest is 17

and if the numbers entered are

36 -17 43 -52 50 0

the program will print

The smallest is -52

5.8 Read Data from a File

So far, we have written our programs assuming that data to be supplied is typed at the keyboard.

We have fetched the data using scanf for reading numbers and gets for reading strings. Typically,

the program prompts the user for the data and waits for the user to type the data. When the data is

typed, the program reads it, stores it in a variable (or variables), and continues with its execution.

This mode of supplying data is called interactive since the user is interacting with the program.

106

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!