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 6 ■ Characters

number of characters in the line and the other to count the number of blanks. The logic could be

expressed as:

set number of characters and number of blanks to 0

while we are not at the end-of-line

read a character

add 1 to number of characters

if character is a blank then add 1 to number of blanks

endwhile

This logic is implemented as shown in Program P6.7.

Program P6.7

//count the number of characters and blanks in the input line

#include <stdio.h>

int main() {

char ch;

int numChars = 0;

int numBlanks = 0;

printf("Type some data and press 'Enter' \n");

while ((ch = getchar()) != '\n') { // repeat as long as ch is not \n

numChars++;

// add 1 to numChars

if (ch == ' ') numBlanks++; // add 1 if ch is blank

}

printf("\nThe number of characters is %d \n", numChars);

printf("The number of blanks is %d \n", numBlanks);

}

Here is a sample run:

Type some data and press 'Enter'

One moment in time

The number of characters is 18

The number of blanks is 3

The if statement tests the condition ch == ' '; if it is true (that is, ch contains a blank),

numBlanks is incremented by 1. If it is false, numBlanks is not incremented; control would

normally go to the next statement within the loop but there is none (the if is the last statement).

Therefore, control goes back to the top of the while loop, where another character is read and

tested for \n.

154

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!