Sie sind auf Seite 1von 23

Imperative

Programming
MODULE-2: Operators and Expressions , Data Input and output

Vidyalankar School of
Information Technology Compiled by: Prof. Seema Bhatkar
Wadala (E), Mumbai seema.bhatkar@vsit.edu.in
www.vsit.edu.in
Certificate
This is to certify that the e-book titled “Imperative
programming” comprises all elementary learning tools for a better
understating of the relevant concepts. This e-book is comprehensively compiled as per
the predefined eight parameters and guidelines.

Signature Date: 20-07-2017


Ms. Seema Bhatkar
Assistant Professor
Department of IT

DISCLAIMER: The information contained in this e-book is compiled and distributed for
educational purposes only. This e-book has been designed to help learners understand
relevant concepts with a more dynamic interface. The compiler of this e-book and
Vidyalankar Institute of Technology give full and due credit to the authors of the contents,
developers and all websites from wherever information has been sourced. We acknowledge
our gratitude towards the websites YouTube, Wikipedia, and Google search engine. No
commercial benefits are being drawn from this project.
Unit II Operators and Expressions , Data Input and output

Contents :
Operators and Expressions:
Arithmetic operators, unary operators, relational and logical operators, assignment operators, assignment
operators, the conditional operator, library functions.

Data Input and output:


Single character input and output, entering input data, scanf function, printf function, gets and puts
functions, interactive programming.
Recommended Books :
Programming with C by Byron Gottfried , Tata McGRAW-Hill , 2nd Edition
Programming Logic and Design by Joyce Farell , Cengage Learning , 8th edition
“C” Programming” by Brian W. Kernighan and Denis M. Ritchie, PHI ,2nd edition
Let us C by Yashwant P. Kanetkar , BPB publication
C for beginners by Madhusudan Mothe , X-Team Series , 1st edition
21st Century C by Ben Klemens , OReilly , 1st edition

Prerequisites
Unit II Pre- Sem. II Sem. III Sem. IV Sem. V Sem. VI
requisites
Operators and -- WT,
Expressions , OOPS
Data Input and
output
Operators and Expressions:
Operators in C are classified into five main categories
1. Arithmetic Operators
2. Unary Operators
3. Relational Operators
4. Logical Operators
5. Assignment Operators
1. ARITHMETIC OPERATORS
Arithmetic operators are used to perform arithmetic between variables and/or values.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% (modulus operator) Remainder after integer division
Example :
Suppose that a and b are integer variables whose values are 10 and 3, respectively.
Several arithmetic expressions involving these variables are shown below, together with their
resulting values.

//program to perform different arithmetic expressions


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter two number:-"); scanf("%d %d",&a,&b);
c=a+b; printf("\n Addition=%d",c);
c=a-b; printf("\n Subtraction=%d",c);
c=a*b; printf("\n Multiplication=%d",c);
c=a/b; printf("\n Division=%d",c);
c=a%b; printf("\n Remainder=%d",c);
getch(); }
Output:
Enter two numbers:- 20 7
Addition=27
Subtraction= 13
Multiplication=140
Division=2
Remainder=6
Source:- https://www.youtube.com/watch?v=JZ3-o9Q-Kjk

 Some More Examples:


1. Suppose that v l and v2 are floating-point variables whose values are 12.5 and 2.0,
respectively. Several arithmetic expressions involving these variables are shown below,
together with their resulting values.

2. suppose that c l and c2 are character-type variables that represent the characters P and T,
respectively. Several arithmetic expressions that make use of these variables are shown
below, together with their resulting values (based upon the ASCII character set).
Ascii Value for P is 80 , T is 84 and 5 is 53

3. Suppose that i is an integer variable whose value is 7, f is a floating-point variable whose


value is 5.5, and c is a character-type variable that represents the character w. Several
expressions which include the use of these variables are shown below. Each expression
involves operands of two different types.
w is encoded as (decimal) 119 and 0 is encoded as 48 in the ASCII character set.
 Operands that differ in type may undergo type conversion before the expression takes on its
final value.
 If one operand is a floating-point type (e.g., f loat , double or long double) and the other is a
char or an int (including short int or long int), the char or int will be converted to the floating-
point type. i.e. the lower precision operand will be converted to the higher precision operand.

2. UNARY OPERATORS

C includes a class of operators that act upon a single operand to produce a new value.
Such operators are known as unary operators.

Operator Meaning
+ Unary plus
- Unary minus
++ Increment(postfix and prefix)
-- Decrement(postfix and prefix)

Example :
Suppose that a and b are integer variables and value of a is 10. Here are some unary
expressions that make use these variables.
Expression Value
b=-a b=-10 a=10
b=a++ b=10 a=11
b=a-- b=10 a=9
b=++a b=11 a=11
b=--a b=9 a=9

//program to perform different unary expressions


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
a=10;
b=-a;
printf("\n After unary minus b=%d a=%d",b,a);
b=a++;
printf("\n After postfix increment b=%d a=%d",b,a);
b=++a;
printf("\n After prefix increment b=%d a=%d",b,a);
b=a--;
printf("\n After postfix decrement b=%d a=%d",b,a);
b=--a;
printf("\n After prefix decrement b=%d a=%d",b,a);
getch();
}
Output:
After unary minus b=-10 a=10
After postfix increment b=10 a=11
After prefix increment b=12 a=12
After postfix Decrement b=12 a=11
After pretfix Decrement b=10 a=10

Source:- https://www.youtube.com/watch?v=hmT81ECRYIs

3. RELATIONAL OPERATORS
Relational operator is a programming language construct or operator that tests or defines
some kind of relation between two entities.
Operator Meaning
< Less than
<= Less than equal to
> Greater than
>= Greater than equal to
== Equal to
!= Not equal to
Example:
Suppose that i, j and k are integer variables whose values are 1, 2 and 3, respectively. Several logical
expressions involving these variables are shown below.
//program to perform different relational expressions
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
a=10;
b=20;
c=10;
printf("a=%d b=%d c=%d",a,b,c);
printf("\n a<b :- %d",(a<b));
printf("\n a<=b :- %d",(a<=b));
printf("\n a>b :- %d",(a>b));
printf("\n a>=b :- %d",(a>=b));
printf("\n a!=c :- %d",(a!=c));
printf("\n a==c :- %d",(a==c));
getch();
}
Output:
a=10 b=20 c=10
a<b :- 1
a<=b :- 1
a>b :- 0
a>=b :- 0
a!=c :- 0
a==c :- 1

Source:-https://www.youtube.com/watch?v=8N5_27GaBxA
4. LOGICAL OPERATORS
These operators are used to perform logical operations on the given expressions.
Operator Meaning
&& Called Logical AND operator. If both the operands are non-zero, then the
condition becomes true.
|| Called Logical OR Operator. If any of the two operands is non-zero, then
the condition becomes true.
! Called as logical NOT operator. It is used to reverse the logical state of its
operand. If a condition is true, then Logical NOT operator will make it
false.
Suppose that i is an integer variable whose value is 7, f is a floating-point variable
whose value is 5.5, and c is a character variable that represents the character ‘w‘(ascii value
is 119) . Several complex logical expressions that make use of these variables are shown
below.

//program to perform different logical expressions


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
a=10; b=20; c=30;
printf("a=%d b=%d c=%d",a,b,c);
printf("\n (a>b&&a>c) :- %d",(a>b&&a>c));
printf("\n (c>a&&c>b) :- %d",(c>a&&c>b));
printf("\n (a<b||a>c) :- %d",(a<b||a>c));
printf("\n !(a>=b) :- %d",!(a>=b));
getch(); }
Output:
a=10 b=20 c=30
(a>b&&a>c) :- 1
(c>a&&c>b) :- 1
(a<b||a>c) :- 1
!(a>=b) :- 0
Source:- https://www.youtube.com/watch?v=-NigITzZteM

5. ASSIGNMENT OPERATORS

Assignment operator assigns the value of an expression to an identifier.


Syntax for assignment expression:
identifier = expression
where identifier generally represents a variable, and expression represents a constant, a variable
or a more complex expression.

Example
Here are some typical assignment expressions that make use of the = operator.
a=3
x=y
delta = 0.001
sum = a + b
area = length * width

Operator Meaning
= Simple assignment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Remainder assignment

Suppose that i and j are integer variables whose values are 5 and 7, and f and g are floating-point
variables whose values are 5.5 and -3.25. Several assignment expressions that make use of these
variables are shown below. Each expression utilizes the original values of i, j , f and g.
//program to perform different assignment expressions
#include<stdio.h>
#include<conio.h>

void main()
{
int a,b,c,d,e;
clrscr();
a=10;
b=55;
c=12;
d=30;
e=23;
printf("a=%d b=%d c=%d d=%d e=%d",a,b,c,d,e);
a+=2;
printf("\n a+=2:-%d",a);
b-=30;
printf("\n b-=30 :- %d",b);
c*=3;
printf("\n c*=3 :- %d",c);
d/=5;
printf("\n d/=5 :- %d",d);
e%=3;
printf("\n e mod=3 :- %d",e);
getch();
}

Output:
a=10 b=55 c=12 d=30 e=23
a+=2 :- 12
b-=30 :- 25
c*=3 :- 36
d/=5 :- 6
e mod =3 :- 2

 THE CONDITIONALOPERATOR

Conditional operator assigns a value to a variable based on some condition.


Syntax
expression 1 ? expression 2 : expression 3
When evaluating a conditional expression, expression1 is evaluated first. If expression1 is
true (i.e., if its value is nonzero), then expression 2 is evaluated and this becomes the value of the
conditional expression. However, if expression1 is false (i.e., if its value is zero), then expression 3
is evaluated and this becomes the value of the conditional expression.

Example:
In the conditional expression shown below, assume that i is an integer variable.
(i < 0) ? 0 : 100
The expression (i < 0) is evaluated first. If it is true (i.e., if the value of i is less than 0), the entire
conditional expression takes on the value 0. Otherwise (if the value of i is not less than 0), the entire
conditional expression takes on the value 100.

//program to handle conditional operator


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter two numbers");
scanf("%d %d",&a,&b);
printf("\n a = %d b = %d",a,b);
c=(a>b)?a:b;
printf("\n c = %d",c);
getch();
}
Output:
Enter two numbers 34 46
a = 34 b = 46
c = 46

 OPERATOR PRECEDENCE TABLE


 LIBRARY FUNCTIONS
The C language is accompanied by a number of library functions that carry out various
commonly used operations or calculations.
Table below shows some commonly used Library functions
Header File Function Type purpose
abs (i) int Return the absolute value of i.
ceil(d) double Round up to the next integer value (the smallest integer that
is greater than or equal to d).
floor(d) double Round down to the next integer value (the largest integer
that does not exceed d).
cos(d) double Returns the cosine of d.
cosh(d) double Return the hyperbolic cosine of d.
sin(d) double Return the sine of d.
tan(d) double Return the tangent of d.
<math.h>
exp(d) double Raise e to the power d.
pow(d1,d2) double Return d1 raised to the d2 power.
fabs (d) double Return the absolute value of d.
fmod(d1,d2) double Return the remainder (i.e., the non-integer part of the
quotient) of dl /d2, with same sign as d1.
rand() int Return a random positive integer.
srand (u) void Initialize the random number generator.
sqrt(d) double Return the square root of d.
log(d) double Return the natural logarithm of d.
getchar() int Enter a character from the standard input device.
<stdio.h> putchar(c) int Send a character to the standard output device.
printf ( ...) int Send data items to the standard output device
scanf(…) int Enter data items from the standard input device
toascii(c) int Convert value of argument to ASCII.
<ctype.h> tolower(c) int Convert letter to lowercase.
Toupper(c) int Convert letter to uppercase.

Example:
int a;
a=-8;
abs(a); //returns absolute value of a i.e. 8

double d;
d=5.7;
ceil(d); //round up the value of d to 6
floor(d); //round down the value of d to 5

pow(5,3); //returns 5 raised to 3 i.e. 125


sqrt(100); //return square root of 100 i.e. 10

//program to illustrate the use of functions in <math.h> header file

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,p,a,ab;
double s;
clrscr();
a=-7;
ab=abs(a);
printf("\n absolute value of %d = %d ",a,ab);
printf("\n Enter a number");
scanf("%d",&n);
s=sqrt(n);
printf("\n squareroot of %d = %lf",n,s);
p=pow(n,4);
printf("\n %d raised to 4 = %d",n,p);
printf("\n Sine value of 90=%lf",sin(90));
printf("\n cosine value of 90=%lf",cos(90));
printf("\n tangent value of 90=%lf",tan(90));
printf("\n log base 10 value of 30=%lf",log(30));
printf("\n ceil value of 5.7=%lf",ceil(5.7));
printf("\n floor value of 5.7=%lf",floor(5.7));
getch();
}

Output:

//program to illustrate the use of functions in <ctype.h> header file

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{

int a;
char b,c;
clrscr();
a=toascii('A');
printf("\n Ascii of A is = %d",a);
b=tolower('B');
printf("\n B in lowercase = %c",b);
c=toupper('t');
printf("\n t in uppercase = %c",c);
getch();
}
Output:

SINGLE CHARACTER INPUT -THE getchar FUNCTION


The getchar function is a part of the standard C I/O library. It returns a single character from
a standard input device (typically a keyboard). The function does not require any arguments, though
a pair of empty parentheses must follow the word getchar.
In general terms, a function reference would be written as
char variable = getchar ( ) ;

A C program contains the following statements.


char c;
.....
c = getchar();
The first statement declares that c is a character-type variable. The second statement causes a
single character to be entered from the standard input device (usually a keyboard) and then assigned
to c.

SINGLE CHARACTER OUTPUT -THE putchar FUNCTION


The putchar function is a part of the standard C I/O library. It transmits a single
character to a standard output device (typically a TV monitor). The character being transmitted will
normally be represented as a character-type variable.
It must be expressed as an argument to the function, enclosed in parentheses, following the
word putchar.
In general, a function reference would be written as
putchar ( char variable)
where character variable refers to some previously declared character variable.

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.
//program to input and output single character
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter any character:");
ch=getchar();
printf("\n Entered character is ");
putchar(ch);
getch();
}
Output:
Enter any character: V
Entered character is V
ENTERING INPUT DATA -THE scanf FUNCTION
Input data can be entered into the computer from a standard input device by means of the C
library function scanf. This function can be used to enter any combination of numerical values,
single characters and strings.
In general terms, the scanf function is written as
scanf(contro1 string, argl, arg2, . . . , argn)
where control string consist of the percent sign(%), followed by a conversion character which
indicates the type of the corresponding data item and argl, arg2, . . . argn are arguments that
represent the individual input data items.

Character conversion Meaning


C data item is a single character
D data item is a decimal integer
E data item is a floating-point value
F data item is a floating-point value
G data item is a floating-point value
H data item is a short integer
S data item is a string followed by a whitespace character (the null
character \ 0 will automatically be added at the end)
U data item is an unsigned decimal integer X data
I data item is a decimal, hexadecimal or octal integer
O data item is a octal integer
X data item is a hexadecimal integer
[….] data item is a string which may include whitespace characters

 More About Scanf Function


The consecutive non whitespace characters that define a data item collectively define a
field. It is possible to limit the number of such characters by specifying a maximum field width
for that data item. To do so, an unsigned integer indicating the field width is placed within the
control string, between the percent sign (%) and the conversion character.
The data item may contain fewer characters than the specified field width. However, the
number of characters in the actual data item cannot exceed the specified field width. Any
characters that extend beyond the specified field width will not be read. Such leftover characters
may be incorrectly interpreted as the components of the next data item.
Example1:
#include <stdio.h>
void main( )
{
i n t a, b y c;
scanf ( "%3d %3d %3d" , &a, &by &c) ;
.....
}
Suppose the input data items are entered as 1 2 3
Then the following assignments will result: a = 1 , b = 2 , c = 3

If the data had been entered as 123 456 789


Then the assignments would be a = 123, b = 456, c = 789

Now suppose that the data had been entered as 123456789


Then the assignments would be a = 123, b = 456, c = 789

Example 2:
#include <stdio.h>
void main ( )
{
int i;
f loat x;
char c;
scanf("%3d %5f %c", &i,&x, &c);
}
If the data items are entered as 10 256.875 T
Then the assignments would be a = 10, x = 256.8, c = 7
The remaining two input characters (5 and T) will be ignored.

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 function can be used to output any combination of numerical values, single
characters and strings.
The printf function moves data from the computer’s memory to the standard output device, whereas
the scanf function enters data from the standard input device and stores it in the
computer’s memory.
In general terms, the p r i n t f function is written as
printf (control string, arg7, arg2, . . . , argn)
where control string consist of the percent sign, followed by a conversion character which indicates
the type of the corresponding data item and arg7, arg2, . .. , argn are arguments that represent the
individual output data items. The arguments can be written as constants, single variable or array
names, or more complex expressions.

Character Meaning
conversion
C data item is a single character
D data item is a decimal integer
E Data item is displayed as a floating-point value with an exponent
F data item is 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.
H data item is a short integer
I Data item is displayed as a signed decimal integer
O Data item is displayed as an octal integer, without a leading zero
S data item is a string followed by a whitespace character (the null character \ 0
will automatically be added at the end)
U data item is an unsigned decimal integer
X Data item is displayed as a hexadecimal integer, without the leading Ox

//program to input and output integer, float and double values using printf and scanf function

#include<stdio.h>
#include<conio.h>

void main()
{

int a;
float b;
double d;
clrscr();
printf("Enter an integer:");
scanf("%d",&a);
printf("\n Entered integer is %d",a);
printf("\n Enter a float number:");
scanf("%f",&b);
printf("\n Entered float number is %f",b);
printf("\n Enter a double number:");
scanf("%lf",&d);
printf("\n Entered double number is %lf",d);

getch();
}

Output:
Enter an Integer: 69
Entered integer is 69
Enter a float number:45.67
Entered float number is 45.66998
Enter a double number:65.1234
Entered float number is 65.123400
//program to input and output character and string data using printf and scanf function
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
char str[20];
clrscr();
printf("Enter initial character of your first name:");
scanf("%c",&ch);
printf("\n Entered charcter is %c",ch);
printf("\n Enter your first name:");
scanf("%s",str);
printf("\n Your name is %s",str);
getch();
}

OUTPUT:

Enter initial character of your first name:S


Entered charcter is S
Enter your first name:Shruti
Your name is Shruti

Source:- https://www.youtube.com/watch?v=OWe-8nJ28AY
 gets() Function
Reads a string, it reads the input characters until a newline is read, discards the
newline, appends a NULL character to the string, and stores the string.
Syntax:
gets(char array);

Example:
char s[20];
gets(s);
The above code allows user to enter a string and store that in character array s.

 puts() Function
Outputs the string after stripping the NULL and appending a newline
Syntax:
puts(char array);

Example:
char s[20];
gets(s)
puts(s);
The above code displays string s on the screen.
//program to input and output string using gets & puts function

#include<stdio.h>
#include<conio.h>
void main()
{
char str[30];
clrscr();
printf("Enter your country name:");
gets(str);
printf("\n Your country is ");
puts(str);
getch();
}

Output:
Enter your country name: India
Your country is India

Question Bank:
1. What is an operator? Describe several different types of operators that are included in C.
2. Describe any five arithmetic operators in C with program.
3. What are unary operators? Describe any five unary operators with program.
4. What are relational operators? Explain any five with program.
5. Explain logical operators in detail.
6. Describe any five assignment operators with program.
7. Write the syntax for conditional operator and describe the use of it with example.
8. Explain any five functions in <math.h> header file.
9. Explain different functions in <ctype.h> header file with example.
10. What is the purpose of the getchar() function? How it is used within a C program?
11. What is the purpose of the putchar() function? Explain with the help of a program?
12. What is the purpose of the scanf() function? How it is used within a C program? Compare
with the getchar() function.
13. What is the purpose of the control string in a scanf function? Describe the role of any five
control string.
14. How can the maximum field width for a data item be specified within scanf() function?
Explain with program.
15. What is the purpose of the prinf() function? How it is used within a C program? Compare
with the putchar() function.
16. What is the purpose of the control string in a printf function? Describe the role of any five
control string.
17. What is the purpose of the gets() function? How it is used within a C program?
18. Explain the use of puts() function with the help of a program.
Multiple Choice Questions
1. Which of the following operator takes only integer operands?
a. +
b. *
c. /
d. %
2. Determine output:
void main()
{
int c = - -2;
printf("c=%d", c);
}
a. 1
b. -2
c. 2
d. Error
3. In C programming language, which of the following type of operators have the highest
precedence
a. Relational operators
b. Equality operators
c. Logical operators
d. Arithmetic operators
4. Which of the following comments about the ++ operator are correct?
a. It is a unary operator
b. The operand can come before or after the operator
c. It cannot be applied to an expression
d. It associates from the right
e. All of the above
5. Which operator has the lowest priority?
a. ++
b. %
c. +
d. ||
6. Pick the operator that not associates from the left?
a. +
b. –
c. =
d. <
7. Pick the operator that not associates from the right?
a. ?:
b. +=
c. =\
d. !=

8. Which of the following is not a compound assignment operator?


a. /=
b. +=
c. %=
d. ==

9. What is the value of X in the sample code given below?


double X; X = ( 2 + 3) * 2 + 3;
a. 10
b. 13
c. 25
d. 28

10. Which among the following is odd one out?


a. Printf
b. Puts
c. Putchar
d. Scanf

11. To print out a and b given below, which of the following printf() statement will you use?
#include<stdio.h>
float a=3.14;
double b=3.14;
a. printf("%f %lf", a, b);
b. printf("%Lf %f", a, b);
c. printf("%Lf %Lf", a, b);
d. printf("%f %Lf", a, b);

12. To scan a and b given below, which of the following scanf() statement will you use?
#include<stdio.h>
float a;
double b;
a. scanf("%f %f", &a, &b);
b. scanf("%Lf %Lf", &a, &b);
c. scanf("%f %Lf", &a, &b);
d. scanf("%f %lf", &a, &b);

13. The Single character input/output function are ?


a. scanf() and printf()
b. getchar() and printf()
c. scanf() and putchar()
d. getchar() and putchar()
14. The two operators && and || are?
a. Arithmetic operator
b. Equality operators
c. Logical operators
d. Relational operators

15. Input/output function prototypes and macros are defined in which header file?
a. conio.h
b. stdlib.h
c. stdio.h
d. dos.h

Das könnte Ihnen auch gefallen