(Lecture 5) Data Input and Output - 2025
(Lecture 5) Data Input and Output - 2025
Functions in C Programming
3
Learning Objective
1. At the end of this lecture, students should be able
to appropriately use the following data input and
data output (I/O) functions in C:
➢getchar and putchar
➢gets and puts
➢scanf and printf
4
Lecture Outline | Progress
5
Single Character Input:
The getchar Function
❖ Single characters can be entered into the computer using
the C library function getchar.
8
Single Character Output:
The putchar Function
❖ Single characters can be displayed (i.e., written out of
the computer) using the C library function putchar.
▪ This function is complementary to the character input function
getchar.
10
Single Character Output:
The putchar Function (Example 5-2)
➢ A C program contains the following statements.
char c;
... ...
putchar(c);
▪ The first statement declares that c is a character-type variable.
▪ The second statement causes the current value of c to be
transmitted to the standard output device (e.g., a TV monitor) where
it will be displayed.
11
Single Character Output:
The getchar and putchar Functions (Example 5-3)
#include<stdio.h> /*header file in C */
int main() /*the main function in C */
{
int c; /*declare a character variable, c */
printf("Enter a number character:");
c = getchar(); /*input or read a single character*/
printf("\n You entered: ");
putchar(c); /*output or write a single character*/
return 0;
}
12
The getchar and putchar Functions for
Multicharacter Input and Output
▪ The getchar function can be used to read multicharacter
strings, by reading one character at a time within a multipass
loop.
▪ The putchar function can also be used to output a string
constant by storing the string within a one-dimensional
character-type array.
▪ Each character can then be written separately within a loop.
– The most convenient way to do this is to utilize a for statement.
13
Lecture Outline | Progress
14
The gets and puts functions
❖ The gets and puts functions facilitate the transfer of strings between
the computer and the standard input/output (I/O) devices.
❖ In the case of gets, the string will be entered from the keyboard, and will
terminate with a newline character (i.e., the string will end when the user
presses the Enter key).
15
String of Characters Input:
The gets Function (Example 5-4)
➢ A C program contains the following statements.
char c[20];
... ...
gets(c);
▪ The first statement declares that c is an array of character-type of size 20.
18
The gets and puts functions
❖ The gets and puts functions offer simple way for
reading/inputting and displaying/outputting strings of
characters.
❖ The puts function writes out the string ”s” and a trailing
newline.
19
Lecture Outline | Progress
20
The scanf and printf functions
❖ Input data can be entered into the computer from a standard input
device (e.g. keyboard) by means of the C library function scanf.
▪ The scanf function can be used to enter any combination of numerical
values, single characters and strings.
▪ The function returns the number of data items that have been entered
successfully.
21
Entering Input Data:
The scanf Function
➢ In general terms, the scanf function is written as:
scanf(contro1 string, argl, arg2, ..., argn);
23
Example 5-6: Typical Application of a scanf function.
24
Example 5-6: Typical Application of a scanf function
(Explanation).
➢ Within the scanf function, the control string is; "%s %d %f".
▪ It contains three character groups.
▪ The first character group, %s, indicates that the first argument (item) represents a string.
▪ The second character group, %d, indicates that the second argument (&partno)
represents a decimal integer value, and
▪ the third character group, %f, indicates that the third argument (&cost) represents a
floating-point value.
➢ Notice that the numerical variables partno and cost are preceded by ampersands (&)
within the scanf function.
▪ An ampersand (&) does not precede item, however, since item is an array name.
25
Example 5-7: The use of the scanf function to enter a string
consisting of UPPERCASE LETTERS and blank spaces.
#include<stdio.h>
main()
{
char line[80]; /*declare a character-type array, line*/
scanf("%[ ABCDEFGHIJKLMNOPQRSTUWXYZ]", line);
/*read in string of UPPERCASE (A-Z) & null characters into line*/
}
26
Example 5-7: The use of the scanf function to enter a string
consisting of uppercase letters and blank spaces (Explanation).
➢ If the string NEW YORK CITY is entered from the standard input device
when the program is executed, the entire string will be assigned to the
array line since the string is comprised entirely of uppercase letters
and blank spaces.
➢ If the string were written as New York City however, then only the single
letter N would be assigned to line, since the first lowercase letter (in this
case, e) would be interpreted as the first character beyond the string.
#include<stdio.h>
main()
{
char line[80]; /*declare a character-type array, line*/
scanf("%[ ^ABCDEFGHIJKLMNOPQRSTUWXYZ]", line);
/*read in string that’s not UPPERCASE (A-Z) & null characters into line*/
}
28
Example 5.8a: Using scanf function with no
restrictions on the characters that comprise the string
➢ If the characters within the brackets are simply the circumflex followed by a newline
character (i.e., ^\n), then the string entered from the standard input device can
contain any ASCII characters except the newline character (line feed, \n).
▪ Thus, the user may enter whatever he or she wishes and then press the keyboard E n t e r key.
▪ The E n t e r key will issue the newline character, thus signifying the end of the string.
#include<stdio.h>
main()
{
char line[80]; /*declare a character-type array, line*/
scanf(" %[^\n]", line);
... /*read in any string of characters (not newline) and null into line*/
}
29
Example 5.9: Using scanf function with no restrictions
on the characters that comprise the string (Explanation)
30
Writing Output Data:
The printf Function
❖ Output data can be written from the computer onto a standard
output device using the library function printf.
▪ This printf function can be used to output any combination of
numerical values, single characters and strings.
❖ printf is similar to the input function scanf, except that its purpose
is to display data rather than to enter it into the computer.
▪ That is, the printf function moves data from the computer’s memory to
the standard output device (Monitor), whereas
▪ the scanf function enters data from the standard input device
(Keyboard) and stores it in the computer’s memory.
31
Writing Output Data:
The printf Function
➢ In general terms, the printf function is written as:
printf(contro1 string, argl, arg2, ..., argn);
32
Table 5-2:
Commonly used conversion characters for data output
Conversion Meaning
character
c Data item is displayed as a single character
d Data item is displayed as a signed decimal integer
e Data item is displayed as a floating-point value with an exponent
f Data item is displayed as a floating-point value without an exponent
g Data item is displayed as a floating-point value using either e-type or f-type conversion,
depending on value. Trailing zeros and trailing decimal point will not be displayed.
34
Example 5.9: Here is a simple program that makes
use of the printf function.
➢ Notice that the first two arguments within the
printf function are single variables,
➢ the third argument is an arithmetic expression, and
➢ the last argument is a function reference that has a
numeric expression as an argument.
➢ Executing the program produces the following
output:
9.000000 7.000000 16.000000 4.000000
35
Example 5.9: Here is a simple (alternative) program
that makes use of the printf function.
#include<stdio.h>
#include<math.h>
main()
{
float i=9.0, j=7.0; /*instantiate two floating-type variables, i, j*/
float k=i+j; /*expression statement*/
float m=sqrt(i+j); /* expression statement*/
printf("%f %f %f %f", i, j, k, m);
/*display four floating-type data items*/
}
36
Example 5.10: Displaying several different types of
data using the printf function.
37
Example 5.10: Displaying several different types of
data using the printf function.
➢ Now suppose that item, partno and cost have been assigned the
values “fastener”, 12345 and 0.05, respectively, within the program.
▪ When the printf statement is executed, the following output will be
generated: fastener 12345 0.050000
➢ The single space between data items is generated by the blank
spaces that appear within the control string in the printf statement.
➢ Suppose printf statement had been
the written as
printf(“%s%d%f”,item,partno,cost);
▪ This printf statement is syntactically valid, though it causes the output
items to run together; i.e. fastener123450.050000
38
Example 5.11: Reading and Writing a Line of Text
using scanf and printf
➢ Here is a short C program that will read in a line of text and then write it back out, just
as it was entered.
#include<stdio.h>
main()
{
char line[80]; /*declare a character-type array, line*/
scanf("%[^\n]", line); /*read in any string (not newline) and null into
line*/
printf("%s", line); /*write out the string of characters and null from
line*/
}
39
Example 5.11: Reading and Writing a Line of Text
using scanf and printf
➢ Notice the difference in the control strings within the scanf function
and the printf function.
▪ Now suppose that the following string is entered from the standard input device
(keyboard) when the program is executed: AUSTIN JAYJAY OKOCHA is one of
Nigeria's all time favorite footballers!
▪ This string is entered with the single scanf function, as long as it is terminated
by a newline character, \n (by pressing the keyboard’s E n t e r key).
➢ The printf function will then cause the entire string to be displayed
on the standard output device (monitor), just as it had been entered.
▪ Thus, the message: AUSTIN JAYJAY OKOCHA is one of Nigeria's all time favorite
footballers! would be shown on screen.
40
Example 5.12: Simple program that reads and writes data stream
according to the format provided
#include<stdio.h>
main() ❖ When the above code is
{ compiled and executed, it
reads the input and
char str[100]; displays it as follows:
int i; ➢ Enter a value :
printf("Enter a digit in word and in figure: "); seven 7
scanf("%s %d", str, &i);
➢ You entered:
printf("\nYou entered: %s, %d ", str, i); seven, 7
return 0;
}
41
Example 5.13: A C program to calculate the area of a
circle using scanf and printf
/* program to calculate the area of a circle */
45
Example 5.14: Reading and Writing a line of text using
gets and puts functions, VS scanf and printf functions
➢ The 1st program that utilized gets and puts, rather than scanf and
printf, to transfer the line of text into and out of the computer presented
a simpler programming syntax (compare carefully with the 2nd program that
used scanf and printf).
➢ On the other hand, the scanf and printf functions in the 2nd program
can be expanded to include additional data items other than strings,
whereas the 1st program cannot.
➢ However, when both programs are executed, they will behave in exactly the
same manner by inputting and outputting the same string data item.
46
Example 5.15: Reading and Writing a line of text using both the
gets and puts functions, and scanf and printf functions
#include <stdio.h>
❖ When the above code is
main() compiled and executed,
{ it waits for you to input
some text when you
char str[100]; enter a text and press
printf("Enter a digit in word and figure: "); enter then program
proceeds and reads the
gets(str); complete line till end
printf("\nYou entered: "); and displays it as
follows:
puts(str);
➢ Enter a value : Seven 7
return 0;
➢ You entered: Seven 7
}
47
Lecture Outline | Progress
48
Interactive (Conversational) Programming
49
Interactive (Conversational) Programming
51
Interactive (Conversational) Programming
Example 5.16: To Computer the Average Exam Score of a Student
#include <stdio.h>
main()
{
char name[20]; avg = (score1+score2+score3)/3;
float score1, score2, score3, avg; printf("\nName: %s\n", name);
printf("Please enter your name:"); printf("Score 1: %f\n", score1);
scanf("%[^\n]", name);
printf("Score 2: %f\n", score2);
printf("Please enter the first score:");
printf("Score 3: %f\n", score3);
scanf("%f", &score1);
printf("Please enter the second score:"); printf("Average: %f\n", avg);
scanf("%f", &score2); }
printf("Please enter the third score:");
scanf("%f", &score3);
1 2
52
Interactive (Conversational) Programming
Example 5.16: To Computer the Average Exam Score of a Student
❖ Notice that two statements are associated with each input data item.
➢ The first is a printf statement, which generates a request for the item.
Then the second statement, a scanf function, causes the data item to be
entered from the standard input device (i.e., the keyboard).
➢ After the student's name and all three exam scores have been entered, an
average exam score is calculated.
➢ The input data and the calculated average are then displayed, as a result of
the group of printf statements at the end of the program.
53
Interactive (Conversational) Programming
Example 5.16: To Computer the Average Exam Score of a Student
54
Summary:
Data Input and Data Output Functions in C
❖The input functions are:
➢getchar: allows single characters to be obtained
from the keyboard.
➢gets: facilitates the input of strings from the
keyboard.
➢scanf: allows single characters, numerical values
and strings to be obtained from the keyboard.
55
Summary:
Data Input and Data Output Functions in C
56
Exercise 1
b) Suppose that x1 and x2 are floating-point variables whose values are 8.0
and -2.5, respectively. Display the values of x1 and x2, with appropriate
labels; i.e., generate the message: x1 = 8.0 x2 = -2.5
c) Suppose that a and b are integer variables. Prompt the user for input
values of these two variables, then display their sum. Label the output
accordingly.
58
Exercise 3
➢ A C program contains the following statements:
#include<stdio.h>
int i, j , k;
▪ Write an appropriate scanf function to enter numerical values for
i, j and k, assuming
a) The values for i, j and k will be decimal integers.
b) The value for i will be a decimal integer, j an octal integer and k a
hexadecimal integer.
c) The values for i and j will be hexadecimal integers and k will be an
octal integer.
59
Exercise 4
➢ A C program contains the ▪ For each of the following groups of
following statements: variables, write a scanf function that
will allow a set of data items to be read
#include<stdio.h>
into the computer and assigned to the
int i, j; variables.
long ix; ▪ Assume that all integers will be read in
short s; as decimal quantities.
unsigned u; a) i, j, x and dx
float x; b) i, ix, j, x and U
double dx; c) i, u and c
char c; d) c, x, dx and s
60
Exercise 5
➢ A simple C program contains the following statements:
#include <stdio.h>
char text[80];
62
Exercise 7
64
Important Notice
❖You are expected to solve the Exercises 1-8 and
submit as stipulated:
– Typed out your solutions and submit via the MOODLE Link
– Single MsWord or PDF.
– Lifeline: Next Week’s Class, FRIDAY, 26th May, 2013
➢ Be reminded that your weekly attendance record is
only guaranteed by your assignment submission.
65