0% found this document useful (0 votes)
15 views106 pages

Unit – II Constants Variables DataTypesInC Operators Expressions Input Output

This document covers Unit II of CS205, focusing on constants, variables, data types, operators, and input-output functions in C programming. It includes definitions and classifications of data types, rules for identifiers and constants, and the significance of C tokens and keywords. Additionally, it discusses the declaration of variables, type conversion techniques, and pre-processor directives such as #include and #define.

Uploaded by

Asmatullah khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views106 pages

Unit – II Constants Variables DataTypesInC Operators Expressions Input Output

This document covers Unit II of CS205, focusing on constants, variables, data types, operators, and input-output functions in C programming. It includes definitions and classifications of data types, rules for identifiers and constants, and the significance of C tokens and keywords. Additionally, it discusses the declaration of variables, type conversion techniques, and pre-processor directives such as #include and #define.

Uploaded by

Asmatullah khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 106

CS205 – Programming in C

Unit – II
Constants, Variables, Data Types in C, Operators and Expressions, Input-Output functions in C

Presented by
Asmatullah Khan

© A S M A T U L L A H K H A N
2

Unit – II Contents
1. Describe character set, C Tokens-Keywords, 9. Illustrate type conversion techniques.
Variables, Identifiers, Constants and Variables.
2. Define Data type. Classify data types and explain 10. Define and List Pre-processor
with examples. directives.
3. Explain declaration of a variable and assigning
11. Discuss #include and #define Pre-
values to variables.
processor directives.
4. Define operator.
5. Classify and Explain operators with examples.
12. Define Header file and discuss stdio.h,
conio.h, math.h, string.h Header files.
6. Describe precedence and associativity of operators.
7. Define expression. 13. Illustrate getchar(), putchar(), scanf(),
printf() with programs.
8. Describe evaluation of Arithmetic, Relational and
logical expressions.

© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, 3

Variables, Identifiers, Constants and Variables


• Introduction
• C is a structured programming
language.
• It is also known as function
orientated programming language.
• C programming language was
developed in the year of 1972 by
Dennis Ritchie at Bell Laboratories
in the USA (AT & T).

© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, Variables,
4

Identifiers, Constants and Variables cont…


• General rules for any C program
1. Every executable statement must end with a
semicolon symbol (;).
2. Every C program must contain exactly one
main method (Starting point of the program
execution).
3. All the system-defined words (keywords) must
be used in lowercase letters.
4. Keywords can not be used as user-defined
names(identifiers).
5. For every open brace {, there must be
respective closing brace }.
6. Every variable must be declared before it is
used.

© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, Variables,
5

Identifiers, Constants and Variables cont…


• C Character Set
• As every language contains a set of characters used to construct words, statements, etc., C
language also has a set of characters which include alphabets, digits, and special symbols.
• C language supports a total of 256 characters.
• Every C program contains statements which are constructed using tokens and these tokens are
constructed using characters from C character set.
• C language character set contains the following:
1. Alphabets
2. Digits
3. Special Symbols
• Every character in C language has its equivalent ASCII (American Standard Code for
Information Interchange) value.

© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, Variables,
6

Identifiers, Constants and Variables cont…


• C Character Set
• Alphabets
• C language supports all the alphabets from the English language.
• Lower and upper case letters together support 52 alphabets.
• lower case letters - a to z
• UPPER CASE LETTERS - A to Z

• Digits
• C language supports 10 digits which are used to construct numerical values in C language.
• Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

• Special Symbols
• C language supports a rich set of special symbols that include symbols to perform mathematical operations, to
check conditions, white spaces, backspaces, and other special symbols.
• Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL bell backspace verticaltab
etc.,
© A S M A T U L L A H K H A N
7

Describe character set, C Tokens-Keywords, Variables,


Identifiers, Constants and Variables cont… Additional Reading

© A S M A T U L L A H K H A N
8

Describe character set, C Tokens-Keywords, Variables,


Identifiers, Constants and Variables cont… Additional Reading

// C Program to print all ASCII Character Set

#include<stdio.h>
#include<conio.h>
int main()
{
int i;
clrscr();
printf("ASCII ==> Character\n");
for(i = -128; i <= 127; i++)
printf("%d ==> %c\n", i, i);
getch();
return 0;
}
© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, 9

Identifiers, Constants and Variables cont…


• C Tokens
• Every C program is a collection of instructions and every instruction is a collection of some individual “units”
called as TOKENS.
• In a C program, a collection of all the keywords, identifiers, operators, special symbols, constants, strings,
and data values are called tokens.
• Tokens are used to construct c programs and they are said to be basic building blocks of a c program.
• In a c program tokens contain the following:
1. Keywords
2. Identifiers
3. Operators
4. Special Symbols
5. Constants
6. Strings
7. Data values © A S M A T U L L A H K H A N
10

Describe character set, C Tokens-Keywords, Variables,


Identifiers, Constants and Variables cont…
• C Tokens
• C Keywords
• Keywords are the reserved words with predefined meaning which already known to
the compiler.
• As every language has words to construct statements, C programming also has words
with a specific meaning which are used to construct C program instructions.
• Keywords are special words with predefined meaning.
• Keywords are also known as reserved words in C programming language.
• In the C programming language, there are 32 keywords.

© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords,, Identifiers, 11

Constants and Variables cont…

• C Tokens
• C Keywords
• Properties of Keywords
1. All the keywords in C programming
language are defined as lowercase
letters so they must be used only in
lowercase letters
2. Every keyword has a specific
meaning, users can not change that
meaning.
3. Keywords can not be used as user-
defined names like variable,
functions, arrays, pointers, etc...
© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, 12

Identifiers, Constants and Variables cont…


• C Tokens
• C Identifiers
• An identifier is a collection of characters which acts as the name of variable, function,
array, pointer, structure, etc...
• An identifier can be defined as the user-defined name to identify an entity uniquely
in the C programming language.
• Example
• int marks;
• char studentName[30];
• Here, marks and studentName are identifiers.

© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, 13

Identifiers, Constants and Variables cont…


• C Tokens • Optional Rules for Creating Identifiers for
better programming
• C Identifiers - Rules for Creating Identifiers
• The identifier must be meaningful to
1. An identifier can contain letters (UPPERCASE and lowercase), describe the entity.
numeric, and _ (underscore ) symbol only. • Since starting with an underscore may
create conflict with system names, so we
2. An identifier should not start with a numerical value. It can start with
avoid starting an identifier with an
a letter or an underscore. underscore.
3. We should not use any special symbols in between the identifier even • We start every identifier with a lowercase
whitespace. letter. If an identifier contains more than
one word then use CAMELCASE (the first
4. Keywords should not be used as identifiers. word starts with a lowercase letter and
5. There is no limit for the length of an identifier. However, the second word onwards first letter is used as
compiler considers the first 31 characters only. an UPPERCASE letter). We can also use
an underscore to separate multiple words
6. An identifier must be unique in its scope. in an identifier.

© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, 14

Identifiers, Constants and Variables cont…


• C Tokens
• C Constants
• A constant is a named memory location which holds only one value throughout the
program execution i.e., once a value is assigned to the constant, that value can't be changed
during the program execution.
• Once the value is assigned to the constant, it is fixed throughout the program.
• In C programming language, a constant can be of any data type like
• integer,
• floating-point,
• character,
• string and
• double, etc.
© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, 15

Identifiers, Constants and Variables cont…


• C Tokens
• C Constants
• Integer constants
Example
• An integer constant can be a decimal integer or octal integer
or hexadecimal integer. 125 -----> Decimal Integer Constant

• A decimal integer value is specified as direct integer value O76 -----> Octal Integer Constant
whereas octal integer value is prefixed with 'o' and
hexadecimal value is prefixed with 'OX'. OX3A -----> Hexa Decimal Integer Constant

• An integer constant can also be unsigned type of integer 50u -----> Unsigned Integer Constant
constant or long type of integer constant.
30l -----> Long Integer Constant
• Unsigned integer constant value is suffixed with 'u' and
100ul -----> Unsigned Long Integer Constant
• long integer constant value is suffixed with 'l’
• whereas unsigned long integer constant value is suffixed with
'ul'. © A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, 16

Identifiers, Constants and Variables cont…


• C Tokens
• C Constants
• Floating Point constants
• A floating-point constant must contain both integer and decimal parts.
• Some times it may also contain the exponent part.
• When a floating-point constant is represented in exponent form, the value must be suffixed
with 'e' or 'E’.
• Example
• The floating-point value 3.14 is represented as 3E-14 in exponent form.

© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, 17

Identifiers, Constants and Variables cont…


• C Tokens Example

• C Constants 'A’
'2’
• Character Constants '+'
• A character constant is a symbol enclosed in single quotation.
• A character constant has a maximum length of one character.
• There are some predefined character constants called escape sequences.
• Every escape sequence has its own special functionality and every escape sequence is prefixed
with '\' symbol.
• These escape sequences are used in output function called 'printf()'.

© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, 18

Identifiers, Constants and Variables cont…


• C Tokens
• C Constants
• String Constants
• A string constant is a collection of characters, digits, special symbols and escape sequences that are enclosed
in double quotations.
• Example:
"This is StringConstantExample"
or
" This\
is\
StringConstantExample "
Or
"This" "is" " StringConstantExample "
• All the above three defines the same
©
string constant.
A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, Identifiers, 19

Constants and Variables cont…


• C Tokens
• C Constants Syntax for const keyword: Syntax for #define preprocessor directive:
const datatype constantName ; #define CONSTANTNAME value
• Constants can be created using
OR
1. 'const' keyword const datatype constantName = value ;
2. '#define' preprocessor
Example Example
const int x = 10 ; #define PI 3.14
Here, 'x' is a integer constant with fixed value 10. Here, PI is a constant with value 3.14
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() #defien PI 3.14
{ void main()
int i = 9 ; {
const int x = 10 ; int r, area ;
i = 15 ; x = 100 ; // creates an error printf("Please enter the radius of circle : ") ;
printf("i = %d\nx = %d", i, x ) ; scanf("%d", &r) ;
} area = PI * (r * r) ;
The above program gives an error because we are trying to change the printf("Area of the circle = %d", area) ;
constant variable value (x = 100). }
© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, 20

Identifiers, Constants and Variables cont…


• C Tokens
• C Variables
• Variables in a C programming language are the named memory locations where the user
can store different values of the same datatype during the program execution.
• That means a variable is a name given to a memory location or a variable can be defined
as a storage container to hold values of the same datatype during the program execution.
• Every variable in C programming language must be declared in the declaration section
before it is used.
• Every variable must have a datatype that determines the range and type of values be
stored and the size of the memory to be allocated.

© A S M A T U L L A H K H A N
Describe character set, C Tokens-Keywords, 21

Identifiers, Constants and Variables cont…


• C Tokens
• C Variables Declaration Syntax:
datatype variableName;
• A variable name may contain letters, digits and underscore symbol.
• The following are the rules to specify a variable name. Example:
1. Variable name should not start with a digit.
int number;

2. Keywords should not be used as variable names.


3. A variable name should not contain any special symbols except underscore(_).
4. A variable name can be of any length but compiler considers only the first 31 characters of the variable name.
• Declaration of Variable
• Declaration of a variable tells the compiler to allocate the required amount of memory with the specified variable name
and allows only specified datatype values into that memory location.
• In C programming language, the declaration can be performed either before the function as global variables or inside any
block or function.
• But it must be at the beginning of block or function.
© A S M A T U L L A H K H A N
22

Assignment - 1
1. Describe C Language character set in detail.
2. What are Tokens in C Language?
3. Define Keywords. List any 6 of them.
4. What are Identifiers? Give rules to create an identifier name.
5. How many types of Constants are there in C Language? Give
examples for each of its types.
6. What is a Variable in C Language? Give an example.

© A S M A T U L L A H K H A N
Define Data type. Classify data types and 23

explain with examples char


signed char
Character
• Data type is a set of value unsigned
char
with predefined int
characteristics. Basic Data signed short int
Types
• Data type specifies how much (Primary
Integer
long int
Data int
memory is to be allocated and Types)

Data Types Classification


unsigned short int
what type of values are to be
float long int
stored in a variable or
Floating double
constant or array. Point
long
double
• Data types are used to declare Enumerated
Used to define variables that can only assign certain integer values
Types
Variable, Constants, Arrays,
void The void type indicates that no value i.e., an empty value (nothing)
Pointers, and Functions.
Derived
User created data types like Array, Structure, Union etc.
Types
© A S M A T U L L A H K H A N
Define Data type. Classify data types and explain
24

with examples cont… char

Character signed char


• Data Types Classification unsigned
char
• Primary data types
int
• The primary data types in the C
programming language are the basic Basic Data signed short int
data types. Types
(Primary long int
• All the primary data types are already Data Integer
int
defined in the system. Types)

Data Types Classification


unsigned short int
• Primary data types are also called as
Built-In data types. float long int
• The following are the primary data Floating double
types in c programming language: Point
long
1. Integer data type double
Enumerated
2. Floating Point data type Used to define variables that can only assign certain integer values
Types
3. Double data type void The void type indicates that no value i.e., an empty value (nothing)
4. Character data type Derived
User created data types like Array, Structure, Union etc.
Types
© A S M A T U L L A H K H A N
Define Data type. Classify data types and explain
25

with examples cont… Character


char
signed char
unsigned
char int
• Data Types Classification

Classification
signed short int

Data Types
Basic Data
Types long int
Integer
• Primary data types (Primary
Data Types)
int
unsigned short int
• Character data type float long int
Floating double
• The character data type is a set of characters Point
long double
enclosed in single quotations.

© A S M A T U L L A H K H A N
Define Data type. Classify data types and explain
26

with examples cont…


Program:
• Data Types Classification
#include"stdio.h"
• Primary data types
• Character data type int main()
{
• The character data type is a set of characters char a= 'A’;
enclosed in single quotations. printf("value of char a : %c \n", a);
return 0;
}

Output:
value of char a : A Press any key to continue . . .

Program for char data type


© A S M A T U L L A H K H A N
Define Data type. Classify data types and explain
27

with examples cont…


Program: Program:

#include"stdio.h" #include"stdio.h"

int main() int main()


{ {
unsigned char a= 'C’; signed char a= 'P’;
printf("value of unsigned char a : %c \n", a); printf("value of signed char a : %c \n", a);
return 0; return 0;
} }

Output: Output:
value of char a : C Press any key to continue . . . value of char a : P Press any key to continue . . .

Program for unsigned char data type Program for signed char data type
© A S M A T U L L A H K H A N
Define Data type. Classify data types and explain
28

with examples cont… Character


char
signed char
unsigned
char int
• Data Types Classification

Classification
signed short int

Data Types
Basic Data
Types long int
• Primary data types (Primary Integer
int
Data Types)
• Integer Data type unsigned short int
float long int
• The integer data type is a set of whole numbers. Floating double
Point
• Every integer value does not have the decimal value. long double
• We use the keyword "int" to represent integer data
type in C.
• We use the keyword int to
1. declare the variables and
2. to specify the return type of a function.
• The integer data type is used with different type
modifiers like short, long, signed and unsigned.

© A S M A T U L L A H K H A N
Define Data type. Classify data types and explain
29

with examples cont…


• Data Types Classification
Program:
• Primary data types
• Integer Data type #include"stdio.h"

• The integer data type is a set of whole numbers. int main()


• Every integer value does not have the decimal {
value. int a=22;
printf("value of int a : %d \n", a);
• We use the keyword "int" to represent integer return 0;
data type in C. }
• We use the keyword int to declare the variables
and to specify the return type of a function. Output:
• The integer data type is used with different type value of int a : 22 Press any key to continue . . .
modifiers like short, long, signed and unsigned.
Program for int data type
© A S M A T U L L A H K H A N
Define Data type. Classify data types and explain
30

with examples cont…


Program:
Program:
#include"stdio.h"
#include"stdio.h"
int main()
int main()
{
{
unsigned int a= 45;
int a=22;
printf("value of unsigned int a : %d \n", a);
printf("value of int a : %d \n", a);
return 0;
return 0;
}
}

Output:
Output:
value of int a : 22 Press any key to continue . . .
value of unsigned int a : 45 Press any key to continue . . .

Program for unsigned int data type Program for int data type
© A S M A T U L L A H K H A N
Define Data type. Classify data types and explain
31

with examples cont…


Program: Program:

#include"stdio.h" #include"stdio.h"

int main() int main()


{ {
short a= 15; unsigned short a= 12;
printf("value of short a : %d \n", a); printf("value of unsigned short a : %d \n", a);
return 0; return 0;
} }

Output: Output:
value of short a : 15 Press any key to continue . . . value of unsigned short a : 12 Press any key to continue . . .
Program for short data type Program for unsigned short data type
© A S M A T U L L A H K H A N
Define Data type. Classify data types and explain
32

with examples cont…


Program: Program:

#include"stdio.h" #include"stdio.h"

int main() int main()


{ {
long a= 19898; unsigned long a= 78876;
printf("value of long a : %ld \n", a); printf("value of unsigned long a : %ld \n", a);
return 0; return 0;
} }

Output: Output:
value of long a : 19898 Press any key to continue . . . value of unsigned long a : 78876 Press any key to continue . . .
Program for long data type Program for unsigned long data type
© A S M A T U L L A H K H A N
Define Data type. Classify data types and explain
33

with examples cont… Character


char
signed char
unsigned
char int
• Data Types Classification

Classification
signed short int

Data Types
Basic Data
Types long int
• Primary data types (Primary Integer
int
Data Types)
• Floating Point data types unsigned short int
float long int
• Floating-point data type is used to represent a set of Floating
numbers with the decimal value. double
Point
long double
• Every floating-point value must contain the decimal
value.
• The floating-point data type has two variants...
1. float
2. double
• We use the keyword "float" to represent floating-point
data type and "double" to represent double data type in
C.
• The float value contains 6 decimal places whereas
double value contains 15 or 19 decimal places.
© A S M A T U L L A H K H A N
Define Data type. Classify data types and explain
34

with examples cont…


Program:
Program:
#include"stdio.h"
#include"stdio.h"
int main()
int main()
{
{
double a= 232.6;
float a=22.9;
printf("value of double a : %f \n", a);
printf("value of float a : %f \n", a);
return 0;
return 0;
}
}

Output:
Output:
value of float a : 22.900000 Press any key to continue . . .
value of double a : 232.600000 Press any key to continue . . .

Program for float data type Program for double data type
© A S M A T U L L A H K H A N
Define Data type. Classify data types and explain
35

with examples cont…


• Data Types Classification
• void data type Enumerated Used to define variables that can only
Types assign certain integer values
• The void data type means nothing or no value.
• Void is used in three situations:

Data Types Classification


1. Function return type as void – A function with no return value will have return type as
void.
2. Function arguments as void – A function with no parameter can accept the void. The void type indicates that no value
void
i.e., an empty value (nothing)
3. Pointers to void – It represents the address of an object, but not its type.
• Enumerated data type
• An enumerated data type is a user-defined data type that consists of integer constants and each
integer constant is given a name.
User created data types
Derived Types like Array, Structure,
• The keyword "enum" is used to define the enumerated data type. Union etc.
• Derived data types
• Derived data types are user-defined data types and are also called secondary data types.
• In the c programming language, the derived data types are created using the following concepts:
• Arrays, Structures, Unions, Enumeration © A S M A T U L L A H K H A N
Define Data type. Classify data types and 36

explain with examples cont…

© A S M A T U L L A H K H A N
37

Assignment - 2
1. What is a Data type in C language? Mention its types.
2. List and explain character data types with a suitable example.
3. List and explain integer data types with a suitable example.
4. List and explain floating-point data types with a suitable example.
5. Mention the following parameters of various primary Data types
a. Keyword used denote the Data type
b. Memory size allocated
c. Range of values
d. Format type specifier
e. Type Modifiers

© A S M A T U L L A H K H A N
Explain declaration of a variable and 38

assigning values to variables


• Variables in a C programming language are the named memory
locations where the user can store different values of the same
datatype during the program execution.
• It is a way to represent memory location through symbol so that it can
be easily identified.
Examples to declare a variable:
Syntax to declare a variable: int a; //declaring 2 variable of integer type
type variable_list; float b; int a=10, b=20;
char c;
float f=20.8;
char c='A';

© A S M A T U L L A H K H A N
Explain declaration of a variable and 39

assigning values to variables cont…


• Rules for defining variables
• A variable name can have alphabets, digits, and underscore.
• A variable name can start with the alphabet, and underscore only.
• It can't start with a digit.
• No whitespace is allowed within the variable name.
• A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names: Invalid variable names:


Syntax to declare a variable: int a; int 2;
type variable_list; int _ab; int a b;
int a30; int long;
© A S M A T U L L A H K H A N
Explain declaration of a variable and 40

assigning values to variables cont…


1. local variable 2. global variable 3. static variable 4. automatic variable 5. external variable

A variable that is A variable that is A variable that is declared with All variables in C that are We can share a variable in
declared inside declared outside the the static keyword is called static declared inside the block, are multiple C source files by
the function or function or block is variable. automatic variables by default. using an external variable.
block is called a called a global
local variable. variable. To declare an external
It retains its value between We can explicitly declare an
multiple function calls. automatic variable using auto variable, you need to
It must be
Any function can keyword. use extern keyword.
declared at the
start of the block,
change the value of If you call this function many
and initialize the the global variable. times, the local variable will
local variable print the same value for each
before it is used It is available to all function call, e.g, 11,11,11 and so
the functions. on.

It must be declared at But the static variable will print


the start of the block. the incremented value in each
function call, e.g. 11, 12, 13 and
so on.

© A S M A T U L L A H K H A N
Explain declaration of a variable and 41

assigning values to variables cont…


• Types of Variables in C
• There are 5 types of variables in C:

1. local variable 2. global variable 3. static variable 4. automatic variable 5. external variable

void function1() int value=20; void function1() void main() //Create a file myfile.h
{ //global variable { { extern int x=10;
int x=10; int x=10; int x=10; //external variable (also global)
// void function1() //local variable //
local variabl { local variable (also automatic) //Create a file program1.c
e int x=10; static int y=10; #include "myfile.h"
} //local variable //static variable auto int y=20; #include <stdio.h>
} //automatic variable
x=x+1; } void printValue()
y=y+1; {
printf("%d,%d",x,y); printf("Global variable: %d", global_vari
able);
} }

© A S M A T U L L A H K H A N
42

Assignment - 3
1. What is a variable in C Language?
2. List rules for declaring a variable.
3. How many types of variables are there in C Language?
4. Define Local Variable. Give an example.
5. Define Global Variable. Give an example.
6. Define Static Variable. Give an example.
7. Define Extern Variable. Give an example.
8. Define Automatic Variable. Give an example.
© A S M A T U L L A H K H A N
43

Define operator
• An operator is a symbol used to perform mathematical, relational comparison, and logical
operations in a program.
• C programming language supports a rich set of 8 operators that are classified as follows:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators

© A S M A T U L L A H K H A N
Classify and Explain operators with examples 44

cont…
• Arithmetic Operators (+, -, *, /, %)
• The arithmetic operators are the symbols that are used to perform basic mathematical operations
like addition, subtraction, multiplication, division and percentage modulo.
• The addition operator can be used with numerical data types and character data type.
• When it is used with numerical values, it performs mathematical addition and
• When it is used with character data type values, it performs concatenation (appending).
• The remainder of the division operator is used with integer data type only.
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Remainder of the Division 5%2=1

© A S M A T U L L A H K H A N
Classify and Explain operators with examples 45

cont…
• Relational Operators (<, >, <=, >=, ==, !=)
• The relational operators are the symbols that are used to compare two values.
• Every relational operator has two results TRUE or FALSE.
• In simple words, the relational operators are used to define conditions in a
program.
Operator Meaning Example
< Returns TRUE if the first value is smaller than second value otherwise returns FALSE 10 < 5 is FALSE
> Returns TRUE if the first value is larger than second value otherwise returns FALSE 10 > 5 is TRUE
<= Returns TRUE if the first value is smaller than or equal to second value otherwise returns FALSE 10 <= 5 is FALSE
>= Returns TRUE if the first value is larger than or equal to second value otherwise returns FALSE 10 >= 5 is TRUE
== Returns TRUE if both values are equal otherwise returns FALSE 10 == 5 is FALSE
!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is TRUE

© A S M A T U L L A H K H A N
Classify and Explain operators with examples 46

cont…
• Logical Operators (&&, ||, !)
• The logical operators are the symbols that are used to combine multiple conditions
into one condition.
• Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE
then complete condition becomes FALSE.
• Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE
then complete condition becomes TRUE.
Operator Meaning Example
&& Logical AND - Returns TRUE if all conditions are TRUE otherwise returns FALSE 10 < 5 && 12 > 10 is FALSE
|| Logical OR - Returns FALSE if all conditions are FALSE otherwise returns TRUE 10 < 5 || 12 > 10 is TRUE
! Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it is !(10 < 5 && 12 > 10) is TRUE
TRUE

© A S M A T U L L A H K H A N
Classify and Explain operators with examples 47

cont…
• Increment & Decrement Operators (++ & --)
• The increment operators adds one to the existing value of the operand and the decrement operator
subtracts one from the existing value of the operand.
• The increment and decrement operators are called unary operators because both need only one operand.
• The increment and decrement operators are used infront of the operand (++a) or after the operand (a++).
• If it is used infront of the operand, we call it as pre-increment or pre-decrement and
• If it is used after the operand, we call it as post-increment or post-decrement.

Operator Meaning Example


Increment - Adds one to existing value int a = 5;
++ a++;
⇒a=6
Decrement - Subtracts one from existing value int a = 5;
-- a--;
⇒a=4

© A S M A T U L L A H K H A N
Classify and Explain operators with examples 48

cont…
• Increment & Decrement Operators (++ & --) Example Program

• Pre-Increment or Pre-Decrement #include<stdio.h>


#include<conio.h>
• In the case of pre-increment, the value of the
void main(){
variable is increased by one before the expression int i = 5, j;
evaluation.
j = ++i; // Pre-Increment
• In the case of pre-decrement, the value of the
variable is decreased by one before the expression printf("i = %d, j = %d", i, j);
evaluation.
}

Output:

© A S M A T U L L A H K H A N
Classify and Explain operators with examples 49

cont…
• Increment & Decrement Operators (++ & --) Example Program

• Post-Increment or Post-Decrement #include<stdio.h>


#include<conio.h>
• In the case of post-increment, the value of the
void main(){
variable is increased by one after the expression int i = 5, j;
evaluation.
j = i++; // Post-Increment
• In the case of post-decrement, the value of the
variable is decreased by one after the expression printf("i = %d, j = %d", i, j);
evaluation. }

Output:

© A S M A T U L L A H K H A N
Classify and Explain operators with examples 50

cont…
• Assignment Operators (=, +=, -=, *=, /=, %=)
• The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand
side variable (Lvalue).
• The assignment operator is used in different variants along with arithmetic operators.
Operator Meaning Example
= Assign the right-hand side value to left-hand side variable A = 15
+= Add both left and right-hand side values and store the result into left-hand side variable A += 10
⇒ A = A+10
-= Subtract right-hand side value from left-hand side variable value and store the result into left-hand side variable A -= B
⇒ A = A-B
*= Multiply right-hand side value with left-hand side variable value and store the result into left-hand side variable A *= B
⇒ A = A*B
/= Divide left-hand side variable value with right-hand side variable value and store the result into the left-hand side A /= B
variable ⇒ A = A/B
%= Divide left-hand side variable value with right-hand side variable value and store the remainder into the left-hand A %= B
side variable ⇒ A = A%B

© A S M A T U L L A H K H A N
Classify and Explain operators with examples 51

cont…
• Bitwise Operators (&, |, ^, ~, >>, <<)
• The bitwise operators are used to perform bit-level operations in the c programming language.
• When we use the bitwise operators, the operations are performed based on the binary values.
• The following table describes all the bitwise operators in the C programming language. Let us consider two variables
A and B as A = 25 (11001) and B = 20 (10100).

Operator Meaning Example


& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A & B ⇒ 16 (10000)

| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1 A | B ⇒ 29 (11101)

^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A ^ B ⇒ 13 (01101)

~ the result of Bitwise once complement is negation of the bit (Flipping) ~A ⇒ 6 (00110)

<< the Bitwise left shift operator shifts all the bits to the left by the specified number of positions A << 2 ⇒ 100 (1100100)

>> the Bitwise right shift operator shifts all the bits to the right by the specified number of positions A >> 2 ⇒ 6 (00110)

© A S M A T U L L A H K H A N
Classify and Explain operators with examples 52

cont…
• Conditional Operator (?:)
• The conditional operator is used for decision making.
• It is also called a ternary operator because it requires three operands.
• In this operator, first we verify a condition, then we perform one operation out
of the two operations based on the condition result.
• if the condition is TRUE the first option is performed,
• if the condition is FALSE the second option is performed.
• The conditional operator is used with the following syntax.
Condition ? TRUE Part : FALSE
Part;
Example
A = (10<15)?100:200; ⇒ A value is 100
© A S M A T U L L A H K H A N
Classify and Explain operators with examples 53

cont…
• Special Operators (sizeof, pointer, comma, dot, etc.)
• The following are the special operators in c programming language.
1. sizeof operator sizeof(variableNam
e);
• This operator is used to find the size of the memory (in bytes) Example
allocated for a variable. sizeof(A);
⇒ the result is 2 if A is an integer
2. Pointer operator (*)
• This operator is used to define pointer variables in c programming
language.
3. Comma operator (,)
• This operator is used to separate variables while they are declaring,
separate the expressions in function calls, etc.
4. Dot operator (.)
• This operator is used to access members of structure or union.
© A S M A T U L L A H K H A N
Describe precedence and associativity of 54

operators
• Precedence of Operators in C
• The precedence of operator species that which operator will be evaluated first
and next.
• Associativity in Operators in C
• The associativity specifies the operator direction to be evaluated;
• It may be left to right or right to left.

• Example
int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive operator).

© A S M A T U L L A H K H A N
Describe precedence and associativity of operators 55

cont…
Precedence Operator Operator Meaning Associativity
() function call
[] array reference
1 Left to Right
-> structure member access
. structure member access

! negation
~ 1's complement
+ Unary plus
- Unary minus
++ increment operator
2 Right to Left
-- decrement operator
& address of operator
* pointer
sizeof returns size of a variable
(type) type conversion

© A S M A T U L L A H K H A N
Describe precedence and associativity of operators 56

cont…
Precedence Operator Operator Meaning Associativity
* multiplication
3 / division Left to Right
% remainder
+ addition
4 Left to Right
- subtraction
<< left shift
5 Left to Right
>> right shift
< less than
<= less than or equal to
6 Left to Right
> greater than
>= greater than or equal to
== equal to
7 Left to Right
!= not equal to
© A S M A T U L L A H K H A N
Describe precedence and associativity of operators 57

cont…
Precedence Operator Operator Meaning Associativity
8 & bitwise AND Left to Right
bitwise EXCLUSIVE
9 ^ Left to Right
OR
10 | bitwise OR Left to Right
11 && logical AND Left to Right
12 || logical OR Left to Right

13 ?: conditional operator Left to Right

© A S M A T U L L A H K H A N
Describe precedence and associativity of operators 58

cont…
Precedence Operator Operator Meaning Associativity

= assignment
*= assign multiplication
/= assign division
%= assign remainder
+= assign addition
14 -= assign subtraction Right to Left
&= assign bitwise AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift

15 , separator Left to Right


© A S M A T U L L A H K H A N
59

Assignment - 4
1. Define Operator. Mention its types.
2. Define associativity and precedence of an operator.
3. Explain Arithmetic operators along with their precedence and associativity.
4. Explain Relational operators along with their precedence and associativity.
5. Explain Logical operators along with their precedence and associativity.
6. Explain Bit-wise operators along with their precedence and associativity.
7. What is Ternary operator? Give an example.
8. What is comma operator? Give an example.
9. Explain Increment ++ and Decrement -- operators.
10. What is sizeof operator? Give an example.
© A S M A T U L L A H K H A N
60

Define expression
• An expression is an executable statement or an instruction formed using collection
of operators and operands that represents a specific value.
• Operator is a symbol that performs tasks like arithmetic operations, logical operations, and
conditional operations, etc.
• Operands are the values on which the operators perform the task.

• An expression is a formula in which operands are linked to each other by the use of
operators to compute a value.
• Based on the operator position, the expressions are divided into THREE types.

1. Infix Expression
2. Postfix Expression
3. Prefix Expression
© A S M A T U L L A H K H A N
61

Define expression cont…

1. Infix Expression 2. Postfix Expression 3. Prefix Expression


• The expression in which • The expression in which • The expression in which
the operator is used the operator is used after the operator is used
between operands is operands is called postfix before operands is called
called infix expression. expression. prefix expression.

• Infix expression general • Postfix expression • Prefix expression general


structure. general structure. structure.
Operand1 Operand2 Operator Operator Operand1 Operand2
Operand1 Operator Operand2

© A S M A T U L L A H K H A N
Describe evaluation of Arithmetic, Relational 62

and logical expressions


• Based on the operator functionality, the expressions are divided
into FOUR types
1. Arithmetic expressions
2. Relational expressions
3. Logical expressions
4. Conditional expressions

© A S M A T U L L A H K H A N
Describe evaluation of Arithmetic, Relational 63

and logical expressions cont…


• C Expressions
1. Arithmetic expressions
• An arithmetic expression is an expression that consists of operands and arithmetic
operators.
• An arithmetic expression computes a value of type int, float or double.
• Evaluation of Arithmetic Expressions
• The expressions are evaluated by performing one operation at a time.
• The precedence and associativity of operators decide the order of the evaluation of individual
operations.

© A S M A T U L L A H K H A N
Describe evaluation of Arithmetic, Relational 64

and logical expressions cont…


• C Expressions Description of each operation Evaluation of expression
1. Arithmetic An expression is given. 6*2/( 2+1 * 2/3 +6) +8 * (8/4)
expressions 2 is multiplied by 1, giving value 2. 6*2/(2+2/3 + 6) + 8 * (8/4)
• Example: 2 is divided by 3, giving value 0. 6*2/(2+0+6) + 8 * (8/4)
2 is added to 6, giving value 8. 6*2/ 8+ 8 * (8/4)
6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)
8 is divided by 4, giving value 2. 6*2/8 + 8 * 2
6 is multiplied by 2, giving value 12. 12/8 +8 * 2
12 is divided by 8, giving value 1. 1+8*2
8 is multiplied by 2, giving value 16. 1 + 16
1 is added to 16, giving value 17. 17
© A S M A T U L L A H K H A N
Describe evaluation of Arithmetic, Relational 65

and logical expressions cont…


• C Expressions
2. Relational expressions
• A relational expression is an expression used to compare two operands.
• It is a condition which is used to decide whether the action should be taken
or not.
• In relational expressions, a numeric value cannot be compared with the string
value.
• The result of the relational expression can be either zero or non-zero
value.
• Here, the zero value is equivalent to a false and non-zero value is equivalent to true.

© A S M A T U L L A H K H A N
Describe evaluation of Arithmetic, Relational 66

and logical expressions cont…


• C Expressions Relational
Description
Expression
2. Relational expressions This condition is used to check whether the
#include <stdio.h> x is an even number or not. The relational
x%2 = = 0
int main() expression results in value 1 if x is an even
{ number otherwise results in value 0.
It is used to check whether a is not equal to
int x=4;
a!=b b. This relational expression results in 1 if a
if(x%2==0)
is not equal to b otherwise 0.
{
printf("The number x is even"); It is used to check whether the expression
a+b = = x+y
} "a+b" is equal to the expression "x+y".
else It is used to check whether the value of a is
printf("The number x is not even"); a>=9
greater than or equal to 9.
return 0;
}
© A S M A T U L L A H K H A N
Describe evaluation of Arithmetic, Relational 67

and logical expressions cont…


• C Expressions Logical Expressions Description
3. Logical expressions It is a test condition to check whether the x
is greater than 4 and x is less than 6. The
• A logical expression is an ( x > 4 ) && ( x < 6 )
result of the condition is true only when
expression that computes both the conditions are true.
either a zero or non-zero It is a test condition used to check whether
value. x is greater than 10 or y is less than 11. The
x > 10 || y <11
• It is a complex test result of the test condition is true if either
condition to take a of the conditions holds true value.
decision. It is a test condition used to check whether
x is not greater than 10 and y is equal to 2.
! ( x > 10 ) && ( y = = 2 )
The result of the condition is true if both
the conditions are true.

© A S M A T U L L A H K H A N
Describe evaluation of Arithmetic, Relational 68

and logical expressions cont…


#include <stdio.h>
#include <stdio.h>
• C Expressions int main()
int main()
{
{
3. Logical int x = 4;
int x = 4;
expressions int y = 9;
int y = 10;
if ( (x <6) || (y>10))
if ( (x <10) && (y>5))
{
{
printf("Condition is true");
printf("Condition is true");
}
}
else
else
printf("Condition is false");
printf("Condition is false");
return 0;
return 0;
}
}

© A S M A T U L L A H K H A N
Describe evaluation of Arithmetic, Relational 69

and logical expressions cont…


• C Expressions
4. Conditional expressions
• A conditional expression is an expression that returns 1 if the condition is true otherwise 0.
• A conditional operator is also known as a ternary operator.
• Syntax of Conditional operator
• Suppose exp1, exp2 and exp3 are three expressions.
exp1 ? exp2 : exp3
• The above expression is a conditional expression which is evaluated on the basis of the
value of the exp1 expression.
• If the condition of the expression exp1 holds true, then the final conditional expression
is represented by exp2 otherwise represented by exp3.

© A S M A T U L L A H K H A N
Describe evaluation of Arithmetic, Relational 70

and logical expressions cont…


#include<stdio.h>
• C Expressions
#include<string.h>
4. Conditional expressions int main()
{
int age = 25;
char status;
status = (age>22) ? 'M': 'U';
if(status == 'M')
printf("Married");
else
printf("Unmarried");
return 0;
}
© A S M A T U L L A H K H A N
71

Assignment - 5
1. What is an Expression in C Language?

2. How many types of expressions are there? List them.

3. Explain evaluation of 6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)

© A S M A T U L L A H K H A N
72

Illustrate type conversion techniques


• In a programming language, when an EXPRESSION contains similar datatype values then it is evaluated
without any problem.
• But if the expression contains two or more different datatype values then they must be converted to the
single datatype of destination datatype.
• Here, the destination is the location where the final result of that expression is stored.

• Example:
• In EXPRESSIONS such as, Multiplication of an integer data value with float data value and storing the result into a float
variable, the integer value must be converted to float value so that the final result is a float datatype value.

• In a c programming language, the data conversion is performed in two different methods as follows...
1. Type Conversion
2. Type Casting

© A S M A T U L L A H K H A N
Illustrate type conversion techniques 73

cont…
1. Type Conversion
• The type conversion is the process of converting a data value from one data type to another data
type automatically by the compiler.
• Type conversion is also called implicit type conversion.
• Example:
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i
x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x
i = ch ; =======> Here the ASCII value of A (65) is assigned to i

© A S M A T U L L A H K H A N
Illustrate type conversion techniques 74

cont… #include<stdio.h>
1. Type Conversion #include<conio.h>

void main(){
int i = 95 ;
float x = 90.99 ;
char ch = 'A' ;

i=x;
printf("i value is %d\n", i);
x=i;
printf("x value is %f\n", x);
i = ch ;
printf("i value is %d\n", i);

}
© A S M A T U L L A H K H A N
Illustrate type conversion techniques 75

cont…
2. Typecasting
• Compiler converts data from one data type to another data type implicitly.
• When compiler converts implicitly, there may be a data loss.

• USER can also convert the data from one data type to another data type using explicit type
conversion.
• To convert data from one type to another type we specify the target data type in parenthesis as a
prefix to the data value that has to be converted.
• To perform this we use the unary cast operator.
• Typecasting is also called as explicit type conversion.
• The general syntax of typecasting is as follows:
(TargetDatatype) DataValue
© A S M A T U L L A H K H A N
Illustrate type conversion techniques 76

cont… #include<stdio.h>
#include<conio.h>
2. Typecasting
• Example void main(){
int a, b, c ;
int totalMarks = 450, maxMarks = 600 ;
float avg ;
float average ;
printf( "Enter any three integer values : “);
average = (float) totalMarks / maxMarks * 100 ; scanf(“%d%d%d”, a, b, c);

avg = (a + b + c) / 3 ;
printf("avg before casting = %d\n“, avg);

avg = (float)(a + b + c) / 3 ;
printf( "avg after casting = %d\n“, avg);

return 0;
}
© A S M A T U L L A H K H A N
77

Assignment - 6
1. Differentiate between Type-casting and Type-convertion

© A S M A T U L L A H K H A N
78

Define and List Pre-processor directives


• The C preprocessor is used by compiler to transform source code
before compilation.
• It is called preprocessor because it allows us to add macros.
• A macro is a segment of code which is replaced by the value of macro.
• Macro is defined by #define directive.
• There are two types of macros:
1. Object-like Macros …. (#define PI 3.14)
2. Function-like Macros …. (#define MIN(a,b) ((a)<(b)?(a):(b)))

• Preprocessor directives are executed before compilation.


• All preprocessor directives starts with hash # symbol.

© A S M A T U L L A H K H A N
Define and List Pre-processor directives 79

cont…
• List of Pre-processor directives • List of Pre-processor directives
1. #undef - used to destroy a macro that was already 6. #elif - is a #else followed by #if in one statement.
created using #define.
7. #endif - is used terminate preprocessor conditional
2. #ifdef - returns TRUE if the macro is defined and macro.
returns FALSE if the macro is not defined.
8. #include - is used to insert specific header file into
3. #ifndef - returns TRUE if the specified macro is not C program.
defined otherwise returns FALSE.
9. #error - is used to print error message on stderr.
4. #if - uses the value of specified macro for
10. #pragma - is used to issue a special command to
conditional compilation.
the compiler.
5. #else - is an alternative for #if.

© A S M A T U L L A H K H A N
Discuss #include and #define Pre-processor 80

directives
• C #include
• The #include preprocessor directive is used to paste code of given in a header-file into current
source code file. It is used to include system-defined and user-defined header files.
• If included file is not found, compiler renders error.
• There are TWO variants to use #include directive.
1. #include <filename>
2. #include "filename"
• The #include <filename> tells the compiler to look for the directory where system header files
are held.
• In UNIX, it is \usr\include directory.

• The #include "filename" tells the compiler to look in the current directory from where program
is running.
© A S M A T U L L A H K H A N
Discuss #include and #define Pre-processor 81

directives cont…
• C #include example
• Let's see a simple example of #include directive. In this program,
#include<stdio.h>
we are including stdio.h file because printf() function is defined in
this file int main()
• #include notes: {
• Note 1: In #include directive, comments are not recognized. printf("Hello C");
So in case of #include <a//b>, a//b is treated as filename.
• Note 2: In #include directive, backslash is considered as return 0;
normal text not escape sequence. So in case of #include <a\
nb>, a\nb is treated as filename.
}
• Note 3: You can use only comment after filename otherwise it
will give error.

© A S M A T U L L A H K H A N
Discuss #include and #define Pre-processor 82

directives cont…
• C #define
#include <stdio.h> #include <stdio.h>
• The #define
preprocessor
directive is used to #define PI 3.14 #define MIN(a,b) ((a)<(b)?(a):(b))
define constant or
micro substitution. main() void main()
It can use any basic { {
data type.
printf("%f",PI); printf("Minimum between 10 and 20
• Syntax } is: %d\n", MIN(10,20));
#define token valu }
e
Output: Output:
3.140000 Minimum between 10 and 20 is: 10
© A S M A T U L L A H K H A N
83

Assignment - 7
1. What is a Preprocessor directive? List any five of them.
2. What is #include?
3. What is a macro?
4. What is #define? Give an example.

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 84

conio.h, math.h, string.h Header files


• Header File
• A header file is a file with extension .h which contains C function declarations
and macro definitions to be shared between several source files.
• There are two types of header files:
1. System defined header file: The header file which is predefined is known as a system
defined header file.
2. User-defined header file: The header file which is defined by the user is known as a
user-defined header file.
• Including a header file is equal to copying the content of the header file.

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 85

conio.h, math.h, string.h Header files


• <stdio.h> Header File
• It is used for performing input and output operations with the help of
using printf() and scanf() function.
• The stdio.h header defines
• three variable types,
• several macros, and
• various functions for performing input and output.

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 86

conio.h, math.h, string.h Header files


<stdio.h> Header File – Built-in Functions
Function Description
This function is used to print the character, string, float, integer, octal and hexadecimal
printf()
values onto the output screen
scanf() This function is used to read a character, string, numeric data from keyboard.
getc() It reads character from file
gets() It reads line from keyboard
getchar() It reads character from keyboard
putc() writes a character to file
puts() It writes line to o/p screen
putchar() It writes a character to screen
clearerr() This function clears the error indicators
fopen() All file handling functions are defined in stdio.h header file
fclose() closes an opened file

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 87

conio.h, math.h, string.h Header files cont…


<stdio.h> Header File – Built-in Functions
Function Description
getw() reads an integer from file
putw() writes an integer to file
fgetc() reads a character from file
fputc() writes a character to file
fgets() reads string from a file, one line at a time
fputs() writes string to a file
feof() finds end of file
fgetchar() reads a character from keyboard
fgetc() reads a character from file
fprintf() writes formatted data to a file
fscanf() reads formatted data from a file
fgetchar() reads a character from keyboard
fputchar() writes a character from keyboard

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 88

conio.h, math.h, string.h Header files cont…


<stdio.h> Header File – Built-in Functions

Function Description
fseek() moves file pointer position to given location
SEEK_SET moves file pointer position to the beginning of the file
SEEK_CUR moves file pointer position to given location
SEEK_END moves file pointer position to the end of file.
f tell() gives current position of file pointer
rewind() moves file pointer position to the beginning of the file
sprint() writes formatted output to string
sscanf() Reads formatted input from a string
remove() deletes a file
fflush() flushes a file

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 89

conio.h, math.h, string.h Header files cont…


• <conio.h> Header File
• The conio.h header file used in C programming language contains functions for
console input/output.
• Some of its most commonly used functions are
• clrscr(),
• getch(),
• getche(),
• kbhit(), etc.
• They can be used to clear screen, change color of text and background, move text,
check whether a key is pressed or not and to perform other tasks.
• The Borland Turbo C++ compiler supports "conio.h," but the GCC compiler doesn't.

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 90

conio.h, math.h, string.h Header files cont…


• <conio.h> Header File – Built-in Functions
Functions Description

clrscr() This function is used to clear the output screen.

getch() It reads character from keyboard

getche() It reads character from keyboard and echoes to o/p screen

textcolor() This function is used to change the text color

textbackground() This function is used to change text background

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 91

conio.h, math.h, string.h Header files cont…


• <math.h> Header File
• The C <math.h> header file declares a set of functions to perform
mathematical operations such as:
• sqrt() to calculate the square root,
• log() to find natural logarithm of a number etc.

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 92

conio.h, math.h, string.h Header files cont…


• <math.h> Header File – Built-in Functions
Function Description
This function returns the nearest integer which is less than or equal to the argument passed to this
floor ( )
function.
This function returns the nearest integer value of the float/double/long double argument passed to this
round ( ) function. If decimal value is from “.1 to .5”, it returns integer value less than the argument. If decimal
value is from “.6 to .9”, it returns the integer value greater than the argument.
This function returns nearest integer value which is greater than or equal to the argument passed to
ceil ( )
this function.
sin ( ) This function is used to calculate sine value.
cos ( ) This function is used to calculate cosine.
cosh ( ) This function is used to calculate hyperbolic cosine.
exp ( ) This function is used to calculate the exponential “e” to the x th power.

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 93

conio.h, math.h, string.h Header files cont…


• <math.h> Header File – Built-in Functions
Function Description
tan ( ) This function is used to calculate tangent.
tanh ( ) This function is used to calculate hyperbolic tangent.
sinh ( ) This function is used to calculate hyperbolic sine.
log ( ) This function is used to calculates natural logarithm.
log10 ( ) This function is used to calculates base 10 logarithm.
sqrt ( ) This function is used to find square root of the argument passed to this function.
pow ( ) This is used to find the power of the given number.
trunc () This function truncates the decimal value from floating point value and returns integer value.

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 94

conio.h, math.h, string.h Header files cont…


• <string.h> Header File
• String is an array of characters.
• <string.h> header file supports all the string functions in C language.
• The string.h header defines
• one variable type - size_t - This is the unsigned integral type and is the result of
the sizeof keyword,
• one macro – NULL - This macro is the value of a null pointer constant, and
• various functions for manipulating arrays of characters.

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 95

conio.h, math.h, string.h Header files cont…


• <string.h> Header File – Built-in Functions
String functions Description
strcat ( ) Concatenates str2 at the end of str1
strncat ( ) Appends a portion of string to another
strcpy ( ) Copies str2 into str1
strncpy ( ) Copies given number of characters of one string to another
strlen ( ) Gives the length of str1
strcmp ( ) Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if str1 > str2
Same as strcmp() function. But, this function negotiates case. “A” and “a” are
strcmpi ( )
treated as same.

© A S M A T U L L A H K H A N
Define Header file and discuss stdio.h, 96

conio.h, math.h, string.h Header files cont…


• <string.h> Header File – Built-in Functions
String functions Description
strchr ( ) Returns pointer to first occurrence of char in str1
strrchr ( ) last occurrence of given character in a string is found
strstr ( ) Returns pointer to first occurrence of str2 in str1
strrstr ( ) Returns pointer to last occurrence of str2 in str1
strdup ( ) Duplicates the string
strlwr ( ) Converts string to lowercase
strupr ( ) Converts string to uppercase
strrev ( ) Reverses the given string
strset ( ) Sets all character in a string to given character
strnset ( ) It sets the portion of characters in a string to given character
strtok ( ) Tokenizing given string using delimiter

© A S M A T U L L A H K H A N
97

Assignment -8
1. Define a Header File. List any three header files used in C
Language.
2. What is “stdio.h”? List any five built-in functions of it.
3. What is “conio.h”? List any five built-in functions of it.
4. What is “math.h”? List any five built-in functions of it.
5. What is “string.h”? List any five built-in functions of it.

© A S M A T U L L A H K H A N
Illustrate getchar(), putchar(), scanf(), printf() 98

with programs
• putchar(), getchar() function in C:
• putchar() function is a file handling function in C programming language which is used to write a character on
standard output/screen.
• getchar() function is used to get/read a character from keyboard input.
File operation Declaration & Description

Declaration: int putchar(int char)


In a C program, we can use putchar function as below.
putchar()
putchar(char);
where, char is a character variable/value.

Declaration: int getchar(void)


In a C program, we can use getchar function as below.
getchar()
getchar(char);
where, char is a character variable/value.

© A S M A T U L L A H K H A N
Illustrate getchar(), putchar(), scanf(), printf() 99

with programs cont…


• putchar(), getchar() function in C:

1 #include <stdio.h>
2 int main()
3 {
4 char c;
5 printf("Enter some character. Enter $ to
6 exit...\n");
Output:
7 while (c != '$');
8 { Enter some character. Enter $ to exit…
9 c = getchar(); A
10 printf("\n Entered character is: "); Entered character is: A
11 putchar(c); B
12 printf("\n") Entered character is: B
13 } $
14 return 0; Entered character is: $
15 }

© A S M A T U L L A H K H A N
Illustrate getchar(), putchar(), scanf(), printf() 100

with programs cont…


• printf() function in C:
• The printf() function is used to print #include<stdio.h>
#include<conio.h>
string or data values or a combination
of string and data values on the output void main()
screen (User screen). {
printf("Hello! Welcome to CS205 programming in
• The printf() function is built-in function C Language !");
defined in a header file called "stdio.h". }
• We need to include the respective Output:
header file (stdio.h) using the #include
statement. Hello! Welcome to CS205 programming in C
Language !
• Syntax:
printf("message to be display!!!");
© A S M A T U L L A H K H A N
Illustrate getchar(), putchar(), scanf(), printf() 101

with programs cont…


• printf() function in C:
#include<stdio.h>
• The printf() function is also used to #include<conio.h>
display data values.
void main()
• When we want to display data {
values we use format string of the int i = 10;
data value to be displayed. float x = 5.5;
printf("Integer value = %d, float value = %f", i, x);
• Syntax:
}
printf("format string",variableName);
Output:

Integer value = 10, float value = 5.5

© A S M A T U L L A H K H A N
Illustrate getchar(), putchar(), scanf(), printf() 102

with programs cont…


• printf() function in C:
#include<stdio.h>
• The printf() function returns an #include<conio.h>
integer value equivalent to the total
number of characters it has printed. void main()
{
• Syntax: int i;
i = printf("Hello! C Language !\n");
i = printf("message to be display!!!"); printf(“There are %d characters in above printf
statement“, i);
}

Output:

Hello! C Language !
There are 20 characters in above printf statement
© A S M A T U L L A H K H A N
Illustrate getchar(), putchar(), scanf(), printf() 103

with programs cont…


• scanf() function in C:
• The scanf() function is used to read #include<stdio.h>
multiple data values of different data #include<conio.h>
types from the keyboard. void main()
• The scanf() function is built-in function {
defined in a header file called "stdio.h". int i;
printf("\nEnter any integer value: ");
• When we want to use scanf() function in scanf("%d",&i);
our program, we need to include the printf("\nYou have entered %d number",i);
respective header file (stdio.h) using }
#include statement. Output:
• Syntax:
Enter any integer value: 45
scanf("format strings", &variableNames); You have entered 45 number
© A S M A T U L L A H K H A N
Illustrate getchar(), putchar(), scanf(), printf() 104

with programs cont…


• scanf() function in C:
#include<stdio.h>
• The scanf() function returns an #include<conio.h>
integer value equal to the total
number of input values read using void main()
{
scanf function. int i, j, k;
• Syntax: printf("\nEnter any two integer value: ");
i = scanf("%d%d", &j, &k);
i = scanf("format strings",&variableNames); }

Output:

Enter any integer value: 45


You have entered 45 number

© A S M A T U L L A H K H A N
105

Assignment - 9
1. Explain the following input output predefined functions with suitable examples
a. scanf()
b. printf()
c. getchar()
d. putchar()

© A S M A T U L L A H K H A N
106

Completion of Unit – II – Review of Contents


1. Describe character set, C Tokens-Keywords, 9. Illustrate type conversion techniques.
Variables, Identifiers, Constants and Variables.
2. Define Data type. Classify data types and explain 10. Define and List Pre-processor
with examples directives
3. Explain declaration of a variable and assigning 11. Discuss #include and #define Pre-
values to variables
processor directives.
4. Define operator.
5. Classify and Explain operators with examples
12. Define Header file and discuss stdio.h,
conio.h, math.h, string.h Header files.
6. Describe precedence and associativity of operators
7. Define expression 13. Illustrate getchar(), putchar(), scanf(),
printf() with programs.
8. Describe evaluation of Arithmetic, Relational and
logical expressions
Thanks for Learning
© A S M A T U L L A H K H A N

You might also like