Chapter-3-Computer Science-10 Class-Federal Board

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

In

3.1 3 INPUT AND OUTPUT FUNCTIONS


programming, input means to enter or feed data in a computer
program and output is what the computer produces after processing the data. C language
provides many input/output functions to provide interaction between a program and user.

3.1.1 OUTPUT FUNCTIONS


In computer programming, output means to display information on screen or print on printer. C
language provides different functions to output information on computer screen. The most
common is the printf() function.

The printf() Function

The printf() function is used to print text, constants, values of variables and expressions on the
screen in a specified format. The general syntax of this function is:

printf(control_string, list of arguments);


The ‘control_string’ consists of text, format specifiers and escape sequences. It is written
within double quotes. Text specifies the message that is to be printed along with the values.
Format specifier specifies the format according to which a value is to be printed. Escape
sequence controls the printing on the output device.

The ‘list of arguments’ consists of a list of variables, constants and arithmetic expressions,
separated by commas, whose values are to be printed. The values are printed according to the
corresponding format specifier. The first format specifier applies to the first argument, the second
to the second argument and so on. The arguments in the printf() function are optional. When
printf() function is used to print only a message, then the arguments are omitted.

Following is an example of printf() function.

printf(“\nThe value of a is %d and the value of b is %d.”,a ,b);


Assuming that a has the value of 3 and b has the value of 4, then the following message will be
printed by the above statement on a new line.

The value of a is 3 and the value of b is 4.


In the above print statement, \n is an escape sequence and %d is a format specifier. The escape
sequence \n is used to start printing on a new line. The format specifier %d is replaced by the
values stored in variables a and b in the order in which they are written. The format specifier %d
is used for printing values stored in integer variables.
3 Input and Output Handling 51
3 Input and Output Handling
3.1.2 INPUT FUNCTIONS
In computer programming input means to feed data into a program through an input device.
C language provides different functions to input data. The most common is the scanf() function.
The scanf() Function
The scanf() function is used to get values into variables from the keyboard during the
execution of a program. The value is input into a variable in a specified format.
Its syntax is:
scanf(“format specifiers”, list of variables);
The ‘format specifiers’ specify the format of the variables. These are written within double
quotes with or without spaces.
The ‘list of variables’ consists of a list of variables, separated by commas, into which the
values are to be entered. In C language, ampersand ( &) symbol is used in scanf() function
before the name of the variable to which a value is to be assigned. Ampersand (&) sign refers
to the memory location where the variable is going to store.
For example, to input values into two integer variables, a and b, the scanf() function is
written as:

scanf(“%d %d”, &a, &b);


Here, the format specifier %d is used twice in control string for the variables a and b.
The program in Fig.3-4, reads two numbers and prints their sum.

Fig.3-4 Program to find sum of two numbers.


52
In the above program, the statement
int a,b,c;
is used to declare that a, b and c are integer variables. Note that the statement ends with a
semicolon(;) as all the C statements do.
The statement
printf("Enter the first number: ");
prompts the user for the first number.
The statement
scanf("%d", &a);
reads the value for the variable a and stores it in the computer’s memory. In this statement, %d
format specifier specifies that an integer is to be input .
The next two statements prompt the user to input the second number and store it in variable
named b. The expression c=a+b calculates the sum of values stored in variables a and b and
stores it in variable c. The last statement prints the sum on the screen.
The execution of this program is shown Fig.3-5.

Fig.3-5 Execution of program to print sum of two numbers.

3.1.3 STATEMENT TERMINATOR


Semicolon (;) is entered at the end of a statement in C language. It indicates the compiler
that the statement ends here. If a statement is not terminated with semicolon, C compiler will
give an error message during compilation and the program will not be compiled.

3.1.4 FORMAT SPECIFIERS


A format specifier is computer code that tells about the data type, field width and the format
according to which a value is to be printed or read from an input device. A list of commonly used
format specifiers is given below.
3 Input and Output Handling 53
3 Input and Output Handling
%d decimal integer
%i integer
%ld long decimal integer
%f floating-point (decimal notation)
%e floating-point (exponential notation)
%c single character
Integer Format Specifiers (%d, %ld and %i)
The format specifier %d is used to read or print a decimal integer and the format specifier
%ld is used with long integers.
The program in Fig.3-12, demonstrates the use of integer format specifiers.

Fig.3-12 Program that uses integer format specifiers

The format specifiers %d and %i are same when they are used with the printf()
function but different when used with scanf() function. For printf() function, both %d and
%i are used for decimal integer as shown in the program.
The execution of the program is shown in Fig.3-13
54

Fig.3-13 Reading decimal, hexadecimal and octal integers

Floating-point Format Specifiers (%f, %e)


The format specifier %f is used to read and print floating-point numbers in decimal notation
with a precision of 6 digits after the decimal point.
The format specifier %e is used to read and print floating-point numbers in exponential
notation.
The program in Fig.3-14, demonstrates the use of floating-point format specifiers.

Fig.3-14 Using floating-point format specifiers in a program


3 Input and Output Handling 55
3 Input and Output Handling
The execution of the program is shown in Fig.3-15.

Fig.3-15 Printing floating -point numbers

The Character Format Specifier (%c)


The character format specifier, %c, is used to read or print a single character.
The program in Fig.3-16 demonstrates the use of %c format specifier.

Fig.3-16 Using character format specifier in a program

The execution of the program is shown in Fig.3-17.

Fig.3-17 Reading and printing characters


56
3 Input and Output Handling 57
58
The program in Fig.3-22, demonstrates the use of arithmetic operators.

Fig.3-22 Using arithmetic operators in a program

In this program when x/y is performed it will give an integer result because the fractional
part is truncated when the two operands are of type integer. Moreover, the remainder operator
will give the remainder after dividing x by y when x%y is performed. The output of the program
is shown in Fig.3-23.

Fig.3-23 Use of arithmetic operators to perform calculations

3.2.2 ASSIGNMENT OPERATORS


Assignment operators are used to assign values to variables used in computer programs.
C language provides three types of assignment operators. These are basic assignment operator,
compound assignment operators and increment/decrement operators
60

3 Input and Output Handling


Basic Assignment Operator
The basic assignment operator is =. This is used to assign value of an expression to a variable.
It has the general form: variable = expression where expression may be a constant, another
variable to which a value has previously been assigned or a formula to be evaluated. For
example: sum = a + b;

Compound Assignment Operators


In addition to =, there are a number of assignment operators unique to C. These include +=, -
=, *=, /= and %=. Suppose op represents an arithmetic operator. Then, the compound
assignment operator has the following general form to assign value of an expression to a
variable.

variable op = expression
This is equivalent to:

variable = variable op expression


For example, consider the following statement:

sum = sum + n;
This assignment statement could be written using a compound assignment operator as:
sum += n;

The effect is exactly the same but the expression is more compact. Some more examples are:

sum - = n is equivalent to sum = sum – n


prod *= n is equivalent to prod = prod * n
a /= b is equivalent to a = a / b
a %= b is equivalent to a = a
%b

3.2.3 RELATIONAL OPERATORS


Relational operators are used to compare two values of the same type. These are used in
expressions when a decision is to be based on a condition. After evaluation of a relational
expression, the result produced is either True or False. Relational operators are used in
programming for decision making.

TYPES OF RELATIONAL OPERATORS


Six types of relational operators are available in C language. These are described in Fig.3-25.

Oper Definition
ator
3 Input and Output Handling 61

== equal to
62

!= not equal to
3 Input and Output Handling 63
64
3 Input and Output Handling 65

Example:
(n<10)||(n>25)
Suppose, the value of n is 5, then the expression will be considered true because one of the
two conditions is true. If the value of n is 28 then also the compound condition will be true. If the
value of n is 12 then the expression will be false since both conditions are false.

The next compound condition will be true if a is greater than b or c is equal to 10. It will also be
true if both conditions are true, that is, a is greater than b and c is equal to 10. It will only be false
if a is not greater than b and at the same time c is not equal to 10.

(a>b) || (c= =10)


Logical OR condition is used when we wish to perform an operations if one of the two conditions
is true or both of the conditions are true. Logical NOT (!) Operator

The logical NOT operator is used with a single expression (condition) and evaluates to true if
the expression is false and evaluates to false if the expression is true. In other words, it reverses
the result of a single expression.

Syntax:
!Expression1
Truth table for AND operator is shown here under:
Expression !Expression For example, the expression:
True False
!(a<b)
False True will be true if a is not less than b. In
other words, the condition will be true if a is greater than or equal to b. The same condition can
also be written as given below which is easy to understand.

(a>=b)
3.2.5 INCREMENT AND DECREMENT OPERATORS
Increment operator is ++ and decrement operator is - -. These are defined in Fig.3-24.
Operator Definition
++ Increment by 1
-- Decrement by 1

Fig.3-24 Increment and decrement operators


3 Input and Output Handling
Examples:
66

++n and n++ are both equivalent to n = n + 1 (or n+=1)


- - n and n- - are both equivalent to n = n – 1 (or n-=1)
When increment or decrement operator is written before the variable, it is known as prefix and
when it is written after the variable, it is known as postfix.

In certain situations, ++n and n++ have different effect. This is because ++n increments
n before using its value whereas n++ increments n after it is used.

As an example, suppose n has the value 3. The statement: a = ++n; will first increment
n and then assigns the value 4 to a. But the statement: a = n++; will first assign the value
3 to a and then increments n to 4. In both cases n has the value 4.

The same rule applies to - -n and n- - as well.

3.2.6 DIFFERENCE BETWEEN ASSIGNMENT OPERATOR AND


EQUAL TO OPERATOR
The assignment operator (=) is used to assign a value to a variable whereas the equal to
operator (==) is used to compare two values of same data type.

For example:

a=5;
c=b; z=x+y;
In the above statements, variable a is assigned the value 5, c is assigned the value stored
in variable b and z is assigned the sum of values stored in variable x and y.

The relational operator (= =) is used to build a condition based on which computer takes some
action.

For example:

a= =1
c= = a+b
In the first condition, if the value of a is equal to 1 then the condition is true otherwise it is false.
In the second condition, the equal to operator is used to check whether the value of c is equal
to the sum of a and b. If it is equal then the condition is true otherwise it is false.

3.2.7 DIFFERENCE BETWEEN UNARY AND BINARY OPERATORS


The operators that work with a single operand are known as unary operators whereas operators
that work with two operands are known as binary operators. Unary operators are -, ++, -- and
3 Input and Output Handling 67

the logical operator ! (NOT). Binary operators are -, +, *, \, % and logical operators && (AND)
and || (OR).

Some examples of unary operators are:

a= -
b; k++;
- -x;
Some examples of binary operators are:

a=b+c;
z=x*y;
k=d%e;
3.2.8 CONDITIONAL (TERNARY) OPERATOR
A conditional operator is a decision-making operator. It has the following form.

condition? expression1 : expression2;


When this statement is executed, the condition is evaluated. If it is true, the entire conditional
expression takes on the value of expression1. If it is false, the conditional expression takes on
the value of expression2. The entire conditional expression takes on a value and can therefore
be used in an assignment statement. Consider the following example.

a = (k>15)? x*y : x+y;


This statement will assign the product of x and y to the variable a, if k is greater than 15,
otherwise a will be assigned the sum of x and y. This expression is equivalent to the following
if-else statement which will be explained in the next unit. if (k>15) a = x*y; else a = x+y;

Some programmers may prefer to use the above if-else statement rather than using the
conditional operator because it is easy to understand.
68 3 Input and Output Handling
The program in Fig.3-27, demonstrate the use of conditional operator for finding the larger
of two numbers.

Fig.3-27 Program to find larger of two numbers

The execution of the program is shown in Fig.3-28.

Fig.3-28 Finding larger of two numbers


3.2.9 ORDER OF PRECEDENCE OF OPERATORS
Order of precedence of operators is the rule that specifies the order in which operations
are to be performed in an expression. The order of precedence is similar to that used in
algebraic formulas.
3 Input and Output Handling 69
70

3 Input and Output Handling


Next the low-priority operations are performed in the order in which they occur, from left to right.
The subtraction is thus performed first giving

62 + 3
and then the addition is carried out, giving the final result 65.

The standard order of evaluation can be modified by using brackets to enclose part of an
expression. The part of the expression within brackets is first evaluated in the standard manner
and then the result is combined to evaluate the complete expression. For example in the
expression, a / (b + c) b+c will be performed first and then a will be divided by the sum of b and
c.

If the brackets are nested, that is, if one set of brackets is contained within another, the
computations in the innermost brackets are performed first.

Key Points
• The printf() functions is used to print text and values on the screen in a specified format.

• The scanf() function is used to get values into variables from the keyboard during execution
of a program.

• A semicolon is entered at the end of each C statement to terminate it.

• A format specifier tells about the data type, field-width and the format according to which a
value is to be printed or read from an input device.

• Escape sequence is a combination of backslash (\) and a code character to control printing
of data on the screen.

• Assignment operator is used to assign a value to a variable.

• Relational operator is used to compare two values of the same type. It is used in an
expression when a decision is to be based on a condition in a program.

• Logical operator is used for building compound condition.

• The order of precedence of operators is the rule that specifies the order in which operations
are to be performed in an expression.

Exercise
3 Input and Output Handling 71

Q1. Select the best answer for the following MCQs.


i. Which function is used for output purpose in C language?
72
A. printf() B. scanf()
C. input() D. getch()
ii. Which character terminates a C statement?
A. Colon B. Semicolon
C. Period D. Comma
iii. Which format specifier is used to print or read a floating-point value?
A. %d B. %i
C. %f D. %e
iv. Which escape sequence is used to move cursor to the beginning of current line?
A. \a B. \r
C. \n D. \b
v. Which of the following is an arithmetic operator?
A. % B. <=
C. && D. +=
vi. Which of the following is a logical operator?
A. % B. <=
C. && D. +=
vii. Which statement is equivalent to “k = k + a;”?
A. k+=a; B. k=+a;
C. k++a; D. k=a++;
viii. Which of the following is an increment operator?
A. + B. +=
C. ++ D. =+
ix. Which of the following operator has the highest precedence?
A. && B. <=
C. = D. *
x. What will be the output of the expression, 5+3*3-1?
A. 16 B. 13
C. 23 D. 12

Short Questions
Q2. Give short answers to the following questions.
i. Why format specifier is used? Explain with examples.
70 4 Conditional Control Structure 1
3 Input and Output Handling
ii. Why escape sequence is used? Explain with examples.
iii. What is the purpose of printf() function? Explain with an example.
iv. Differentiate between printf() and scanf() functions.
v. Evaluate the following expressions.
a) 7+5*(3+4)
b) 100/10/4
c) 50%13%3
d) 30/7*3-6
vi. What will be the output of the following program?
# include <stdio.h>
void main(void)
{
int x,y,z1,z2,z3,z4;
x=17;
y=5;
z1=x/y;
printf(“\nz1=%d”,z1);
z2=x%y;
printf(“\nz2=%d”,z2);
z3=++x;
printf(“\nz3=%d”,z3);
z4=y++;
printf(“\nz4=%d”,z4);
}
vii. What will be the output of the following program?
# include <stdio.h>
void main(void)
{
int b;
float a,c,d,e,f;
a=14.84;
b=7;
c=a-b;
printf(“\nc=%f”,c);
d=a/b;
printf(“\nd=%f”,d);
e=a-b*3;
printf(“\ne=%f”,e);
2 3 Input and Output Handling
f=(a+b)/2;
printf(“\nf=%f”,f);
}

Extensive Questions
Q3. Describe how basic and compound assignment operators are used?
Q4. Describe the functions of the following operators?
i) Relational operators
ii) Logical operators
iii) Conditional operator
Q5 . Write a program that reads three numbers and prints their sum, product and average.
Q6. Write a program that reads the length and width of a rectangle and prints its area.
Q7. Write a program that reads the length of one side of a cube and prints its volume.
Q8. Write a program that reads temperature in Celsius, converts it into Fahrenheit and prints
on the screen.

You might also like