1. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 1
Pro
gra
m
mi
ng
in
C
Chapter-2
1 1
UNIT-II
Basics Of C Programming
Prof. Zaibunnisa Malik
Research Scholar, D.Litt,
M.E(Comp. Sci.), B.E(Comp. Sci.), LMISTE,
CCNA, MCSE
Principal(In charge Unaided Section) &
HOD, Computer Engineering Department,
M.H.Saboo Siddik Polytechnic, Mumbai-08.
Mobile: 9819898203
2. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 2
Pro
gra
m
mi
ng
in
C
PROGRAMMING IN C SYLLABUS OVERVIEW
TEACHING AND EXAMINATION SCHEME
Teaching
scheme
CR
ED
IT
EXAMINATION SCHEME
L T P
THEORY PRACTICAL
Paper
HRS
ESE PA TOTAL ESE PA TOTAL
Max Min Max Min Max Min Max Min Max Min Max Min
3 2 2 7 3 70 28 30* 00 100 40 25@ 10 25 10 50 20
3. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 3
Pro
gra
m
mi
ng
in
C
UNIT-2 Basics Of C Programming
4. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 4
Pro
gra
m
mi
ng
in
C
2.1 Introduction to C Programming
History Of C
ALGOL
o The root of all modern languages is
ALGOL Introduced in the early 1960s.
o ALGOL was the first computer
language to use a block structure.
o ALGOL gave the concept of
structured programming to the
computer science.
Peter Naur
5. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 5
Pro
gra
m
mi
ng
in
C
HISTORY OF C
BCPL
o In 1967, Martin Richards developed a
language called (Basic Combined
Programming Language).
o In 1970, Ken Thompson created a
language using many features of
BCPL and called it simply B.
o Both BCPL and B were “typeless”
system programming languages.
Martin Richards
Ken
Thompson
6. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 6
Pro
gra
m
mi
ng
in
C
In 1972 C was evolved from ALGOL, BCPL and
B by Dennis Ritchie at the Bell Laboratories.
C uses many concepts from theses languages and
added the concept of data types and other powerful
features.
It is strongly associated with UNIX.
UNIX is one of the most popular network
operating systems in use today.
HISTORY OF C
7. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 7
Pro
gra
m
mi
ng
in
C
Traditional C
o During 1970s C had evolved into what is now known as
“traditional C”.
o The language became more popular after publication of
the book ‘The C programming language’ by Brian
Kerningham and Dennis Ritchie in 1978.
o For many years, C was used mainly in academic
environments.
o Today , C is running under a variety of operating
system and hardware platforms.
HISTORY OF C
8. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 8
Pro
gra
m
mi
ng
in
C
HISTORY OF C
Brian Kerningham Dennis
Ritchie
The Book was so popular that the language came to be
known as “K&R C” among the programming community.
9. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 9
Pro
gra
m
mi
ng
in
C
ANSI C
o In 1983 American National Standards Institute (ANSI)
appointed a technical committee to define a standard
for C.
o In December 1989 the committee approved a version of
C which is known as ANSI C.
o It was then approved by the International Standards
Organization (ISO) in 1990.
o This version of C is also referred to as C89.
HISTORY OF C
HISTORY OF C
10. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 10
Pro
gra
m
mi
ng
in
C
HISTORY OF C
ANSI / ISO C
During 1990s, C++, a language entirely based on C,
underwent a number of improvements and became an
ANSI/ISO approved language in November 1977.
C++ added several new features to C to make it only a true
object- oriented language but also a more versatile
language.
During the same period, Sun Microsystems of USA created a
new language java modelled on C and C++.
11. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 11
Pro
gra
m
mi
ng
in
C
HISTORY OF C
C99
o C99 (previously known as C9X) is an informal name for
ISO/IEC 9899: 1999.
o It extends the previous version (C90) with new features
for the language and the standard library.
o C99 is, for the most part, backward compatible with
C89, but it is stricter in some ways.
12. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 12
Pro
gra
m
mi
ng
in
C
HISTORY OF C
13. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 13
Pro
gra
m
mi
ng
in
C
Programming languages
• Various programming languages
• Some understandable directly by computers
• Others require “translation” steps
• Machine language
• Natural language of a particular computer
• Consists of strings of numbers(1s, 0s)
• Instruct computer to perform elementary operations
one at a time
• Machine dependent
14. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 14
Pro
gra
m
mi
ng
in
C
Programming languages
• Assembly Language
• English like abbreviations
• Translators programs called “Assemblers” to convert
assembly language programs to machine language.
• E.g. add overtime to base pay and store result in gross pay
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY
15. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 15
Pro
gra
m
mi
ng
in
C
Programming languages
High-level languages
◦ To speed up programming even further
◦ Single statements for accomplishing substantial tasks
◦ Translator programs called “Compilers” to convert high-
level programs into machine language
◦ E.g. add overtime to base pay and store result in gross pay
grossPay = basePay + overtimePay
16. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 16
Pro
gra
m
mi
ng
in
C
Development with C
Four stages
Editing: Writing the source code by using some IDE
or editor
Preprocessing or libraries: Already available
routines
compiling: translates or converts source to object
code for a specific platform
source code -> object code
linking: Resolves external references and produces
the executable module
17. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 17
Pro
gra
m
mi
ng
in
C
Basics of C Environment
C systems consist of 3 parts
Environment
Language
C Standard Library
Development environment has 6 phases
Edit
Pre-processor
Compile
Link
Load
Execute
18. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 18
Pro
gra
m
mi
ng
in
C
Basics of C Environment
19. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 19
Pro
gra
m
mi
ng
in
C
Basics of C Environment
20. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 20
Pro
gra
m
mi
ng
in
C
General Structure of C program
1
• Documentations (Documentation Section)
2
• Pre-processor Statements (Link Section)
3
• Global variable / Function Declaration
4
• The main() function
5
• User Defined Functions
21. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 21
Pro
gra
m
mi
ng
in
C
Documentation Section
The documentation section is the part of the program where
the programmer gives the details associated with the program.
He usually gives the name of the program, the details of the
author and other details like the time of coding and
description. It gives anyone reading the code the overview of
the code.
Example
/*
* File Name: Helloworld.c
* Author: zeba Malik
* date: 29/11/2018
* description: a program to display hello world
* no input needed
*/
22. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 22
Pro
gra
m
mi
ng
in
C
Pre-processor Statements (Link Section)
Header Files Inclusion: The first and foremost component is the inclusion of
the Header files in a C program.
A header file is a file with extension .h which contains C function declarations
and macro definitions to be shared between several source files.
Some of C Header files:
stdio.h Defines core input and output functions
stdlib.h Defines numeric conversion functions, pseudo-random network
generator, memory allocation
string.h Defines string handling functions
math.h Defines common mathematical functions
conio.h Defines the console input output file.
Syntax to include a header file in C: #include
23. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 23
Pro
gra
m
mi
ng
in
C
EXAMPLE PROGRAM USING #DEFINE PREPROCESSOR DIRECTIVE IN C:
include <stdio.h>
#define height 100
#define pi 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '?'
void main()
{
printf("value of height : %d n", height );
printf("value of pi : %f n", number );
printf("value of letter : %c n", letter );
printf("value of letter_sequence : %s n",letter_sequence);
printf("value of backslash_char : %c n",backslash_char);
}
Output:
value of height : 100
value of pi : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
24. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 24
Pro
gra
m
mi
ng
in
C
Global variable / Function Declaration
This part of the code is the part where the Global Variable / Function
variables are declared. All the global variable used are declared in this part.
The user-defined functions are also declared in this part of the code.
There are some variables that are used in more than one function, such
variables are called global variables.
In C there are two types of variable declaration,
Local variable declaration: Variables that are declared inside the main
function.
Global variable declaration: Variables that are declared outside the main
function.
• int a=7;
• float area(float r);
25. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 25
Pro
gra
m
mi
ng
in
C
main() function
• Main() method is the compulsory part for any c program.
• C language is a function oriented programming language, so every c
program must have at least one function and that must be main.
• Main is a user defined method which specifies the starting point of the
program execution.
• Every c program execution starts with main method and ends with main
method itself.
• Every C-programs needs to have the main function. Each main function
contains 2 parts. A declaration part and an Execution part. The declaration
part is the part where all the variables are declared. The execution part
begins with the curly brackets and ends with the curly close bracket. Both
the declaration and execution part are inside the curly braces.
26. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 26
Pro
gra
m
mi
ng
in
C
User Defined Functions
• In this section of the program we write the actual code for the
userdefined methods.
• Userdefined methods can be implemented either before or
after the method.
• If it is implemented after the main then it must be declared
either inside or before the main method.
• If it is implemented before the main then the declaration can
be ignored.
• If the program is a multi-function program, then the
subprogram section contains all user-defined functions that
are called in the main() function.
27. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 27
Pro
gra
m
mi
ng
in
C
Example
/* File Name: areaofcircle.c
* Author: Zeba Malik
* date: 09/08/2019
* description: a program to calculate area of circle
*user enters the radius
*/
#include<stdio.h> //link section
#define pi 3.14; //definition section
float area(float r); //global declaration
int main() //main function
{
float r;
printf(" Enter the radius:n");
scanf("%f",&r);
printf("the area is: %f",area(r));
return 0;
}
float area(float r)
{
return pi * r * r;//sub program
}
28. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 28
Pro
gra
m
mi
ng
in
C
2.2 Data Concepts.
29. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 29
Pro
gra
m
mi
ng
in
C
C Tokens
30. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 30
Pro
gra
m
mi
ng
in
C
C Tokens
C tokens are the basic buildings blocks in C language which
are constructed together to write a C program. Each and
every smallest individual unit in a C program is known as C
tokens. C has Six types of tokens:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
31. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 31
Pro
gra
m
mi
ng
in
C
C Keywords
All keywords have fixed meaning & there meanings cannot be
changed during the execution of a program. Keywords served as
basic building block for program statements. White spaces are not
allowed in keywords. Keywords may not be used as an identifier. ‘C’
has 32 keywords, all keywords written in lower case. For example, if,
int, for, float, while etc.
32. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 32
Pro
gra
m
mi
ng
in
C
C Identifier
Identifier refers to the name of variable, functions and array. These are user define
names & consist of a sequence of letter & digits both uppercase and lowercase
letters are permitted.
Rule of identifier:
1. First character must be an alphabet and underscore.
2. Must consist of only letters, digits and underscore.
3. Cannot use a keyword.
4. Must not contain white space.
For example:
int price;
int tv_price;
Here, price & tv_price; is an identifier which denotes a variable of type
integer.
33. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 33
Pro
gra
m
mi
ng
in
C
C Constants
Constants refers to
fixed values that do
not change during
the execution of a
program.
Basic types of C
constants are shown
in the flowchart.
34. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 34
Pro
gra
m
mi
ng
in
C
Integer Constants
• C integer constant is a decimal, octal
(Value starts with 0) or hexadecimal
number (Value starts with 0x).
• Integer constants are always
positive until you specify a
negative(-) sign.
Decimal
Constants
Octal
Constants
HexaDecimal
Constants
10 012 0xA
1024 02000 0x400
12789845 060624125 0xC32855
Rule for Integer Constant:
• An integer constant must have at
least one digit.
• It must not have a decimal point.
• It can either be positive or
negative.
• No commas or blanks are allowed
within an integer constant.
• If no sign precedes an integer
constant, it is assumed to be
positive.
• The allowable range for integer
constants is -32768 to 32767.
35. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 35
Pro
gra
m
mi
ng
in
C
Example Program
#include<stdio.h>
void main()
{
const int a=10; // Decimal int
const int b= 012; // Octal int
const int c=0xA; // Hexadecimal
printf(" %d n %d n %d",a,b,c);
}
OUTPUT:
10
10
10
36. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 36
Pro
gra
m
mi
ng
in
C
Real Constants
The default form of real constant is double
andit must have adecimal point. You can
represent the negative numbers in real
constants. It may be in fractional form or
exponential form.
Ex: 3.45, -2.58, 0.3E-5 (equal to 0.3 x 10-5)
Representation Value Type
0 0.0 double
6.77 6.77 double
-6.0f -6.0 float
3.1415926536L 3.1415926536 long double
Rule for Constructing Real Constant:
• A real constant must have at
least one digit
• It must have a decimal point
• It could be either positive or
negative
• If no sign precedes real
constant, it is assumed to be
positive.
• No commas or blanks are
allowed within a real
constant.
37. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 37
Pro
gra
m
mi
ng
in
C
Character Constants
Every number, symbol or a digit in a single quotes called character
constants. Character constants are of two types:
1. Single Character Constants
A character constant is a single character, enclosed in single
quotation marks. e.g., ‘A’ ‘B’ ‘1’.
Characters are stored internally in computer as coded set of binary
digits, which have positive decimal integer equivalents. The value of
a character constant is the numeric value of the character in the
machine’s character set.
For example, on ASCII machine the value of ‘A’ is 65.
38. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 38
Pro
gra
m
mi
ng
in
C
Character Constants
2. String Constant
It is collection of characters enclosed in
double quotes. It may contain letters,
digits, special
characters and blank space. Example:
“Hello World!"
Strings are nothing but array of characters
ended with null character (“0”).This null
character indicates the end of the string.
Strings are always enclosed by double
quotes. Wheras,character is enclosed by
single quotes in C.
Rule for Constructing Character
Constant:
• A character constant is a
single alphabet, a single digit
or a single special symbol
enclosed within single quotes.
• The maximum length of a
character constant is 1
character.
• String constants are enclosed
within double quotes.
39. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 39
Pro
gra
m
mi
ng
in
C
BACKSLASH / ESCAPE SEQUENCE CHARACTER CONSTANTS
• There are some
characters which have
special meaning in C
language.
• They should be
preceded by backslash
symbol to make use of
special function of
them.
• Given below is the list of
special characters and
their purpose.
40. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 40
Pro
gra
m
mi
ng
in
C
EXAMPLE PROGRAM USING CONST KEYWORD IN C
#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '?'; /*special char cnst*/
printf("value of height :%d n", height );
printf("value of number : %f n", number );
printf("value of letter : %c n", letter );
printf("value of letter_sequence : %s n", letter_sequence);
printf("value of backslash_char : %c n", backslash_char);
}
Output :
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
41. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 41
Pro
gra
m
mi
ng
in
C
Special Symbols
The following special symbols are used in C having some special meaning and
thus,cannot be used for some other purpose.
[ ] ( ) { } , ; *= #
Brackets []: These opening and closing brackets are used as array element reference.
These are used to indicate single & multidimensional subscripts.
Braces {}: Opening and closing curly braces are used to mark start and end of a block of
code containing more than one statement.
Comma ( , ): To separate more than one statement, Comma is used for example in for loop
comma separates initialization, condition & increment.
Semicolon ( ; ): Used at the end of statements for termination.
Parenthesis () : Are used to indicate function parameters & function calls.
Asterick ( * ): This special symbol is used to create a pointer variable.
Assignment Operator ( = ): For assigning values, this special symbol is used.
Preprocessor ( # ): This you must have seen attached with the header files. This is
automatically used by the compiler to transform your program before actual compilation.
42. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 42
Pro
gra
m
mi
ng
in
C
C DATA TYPES
43. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 43
Pro
gra
m
mi
ng
in
C
44. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 44
Pro
gra
m
mi
ng
in
C
C PRIMITIVE DATA TYPES
Sr.no Data type Format Byte Value Range
01 signed char %c 1 -27
to +27
-1 -128 to + 127
02 unsigned char %c 1 0 to +28
-1 0 to 255
03 short signed int %d 2 -215
to +215
-1 -32768 to + 32767
04 short unsigned int %u 2 0 to +216
-1 0 to 65535
05 long signed int %ld 4 -231
to +231
-1 -2147483648 to +2147483647
06 long unsigned int %lu 4 0 to +232
-1 0 to 4294967295
07 float %f 4 -231
to +231
-1 -3.4e38 to +3.4e38
08 double %lf 8 -263
to +263
-1 -1.7e308 to +1.7e308
09 long double %Lf 10 -279
to +279
-1 -1.7e4932 to +1.7e4932
The Size and range are compiler dependent, the above figure are 16-bit compiler.
45. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 45
Pro
gra
m
mi
ng
in
C
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
int main(int argc, char** argv)
{
printf("CHAR_BIT : %dn", CHAR_BIT);
printf("CHAR_MAX : %dn", CHAR_MAX);
printf("CHAR_MIN : %dn", CHAR_MIN);
printf("INT_MAX : %dn", INT_MAX);
printf("INT_MIN : %dn", INT_MIN);
printf("LONG_MAX : %ldn", (long) LONG_MAX);
printf("LONG_MIN : %ldn", (long) LONG_MIN);
printf("SCHAR_MAX : %dn", SCHAR_MAX);
printf("SCHAR_MIN : %dn", SCHAR_MIN);
printf("SHRT_MAX : %dn", SHRT_MAX);
printf("SHRT_MIN : %dn", SHRT_MIN);
printf("UCHAR_MAX : %dn", UCHAR_MAX);
printf("UINT_MAX : %un", (unsigned int) UINT_MAX);
printf("ULONG_MAX : %lun", (unsigned long) ULONG_MAX);
printf("USHRT_MAX : %dn", (unsigned short) USHRT_MAX);
return 0;
}
CHAR_BIT : 8
CHAR_MAX : 127
CHAR_MIN : -128
INT_MAX : 2147483647
INT_MIN : -2147483648
LONG_MAX : 9223372036854775807
LONG_MIN : -9223372036854775808
SCHAR_MAX : 127
SCHAR_MIN : -128
SHRT_MAX : 32767
SHRT_MIN : -32768
UCHAR_MAX : 255
UINT_MAX : 4294967295
ULONG_MAX : 18446744073709551615
USHRT_MAX : 65535
Given below is an example to get the size of various type on a machine using different constant
defined in limits.h header file −
EXAMPLE OF C DATA TYPES
46. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 46
Pro
gra
m
mi
ng
in
C
EXAMPLE OF C DATA TYPES
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
int main(int argc, char** argv) {
printf("Storage size for float : %d n", sizeof(float));
printf("FLT_MAX : %gn", (float) FLT_MAX);
printf("FLT_MIN : %gn", (float) FLT_MIN);
printf("-FLT_MAX : %gn", (float) -FLT_MAX);
printf("-FLT_MIN : %gn", (float) -FLT_MIN);
printf("DBL_MAX : %gn", (double) DBL_MAX);
printf("DBL_MIN : %gn", (double) DBL_MIN);
printf("-DBL_MAX : %gn", (double) -DBL_MAX);
printf("Precision value: %dn", FLT_DIG );
return 0;
}
The header file float.h defines macros that allow you to use these values and other
details about the binary representation of real numbers in your programs. The
following example prints the storage space taken by a float type and its range values
Storage size for float : 4
FLT_MAX : 3.40282e+38
FLT_MIN : 1.17549e-38
-FLT_MAX : -3.40282e+38
-FLT_MIN : -1.17549e-38
DBL_MAX : 1.79769e+308
DBL_MIN : 2.22507e-308
-DBL_MAX : -1.79769e+308
Precision value: 6
47. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 47
Pro
gra
m
mi
ng
in
C
Variables in C
Variables are names used to refer to some memory locations of computer.
The piece of information stored at this location is referred as value of a
variable.
The variables are not fixed values and might change during the execution
of a program.
C variable is a named location in a memory where a program can
manipulate the data. This location is used to hold the value of the variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char etc.
48. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 48
Pro
gra
m
mi
ng
in
C
Syntax to declare a variable
4 www.programming9.com
Syntax:
Datatype Variablename;
• int d;
• float a, b;
• double f;
• char ch; etc.,
49. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 49
Pro
gra
m
mi
ng
in
C
Defining a Variable
• int a=10, b=20;
• float f=23.145;
• double d=20.0;
• char ch='x';
In RAM (Physical Memory)
50. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 50
Pro
gra
m
mi
ng
in
C
RULES FOR NAMING C VARIABLE:
1. Variable name must begin with letter or
underscore.
2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than
underscore.
5. sum, height, _value are some examples for
variable name
51. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 51
Pro
gra
m
mi
ng
in
C
DECLARING & INITIALIZING C VARIABLE:
1. Variables should be declared in the C program before its use.
2. Memory space is not allocated for a variable while declaration. It
happens only on variable definition.
3. Variable initialization means assigning a value to the variable.
52. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 52
Pro
gra
m
mi
ng
in
C
TWO TYPES OF VARIABLES IN C PROGRAM
Local variable
• The scope of local variables
will be within the function
only.
• These variables are declared
within the function and can’t
be accessed outside the
function.
#include<stdio.h>
void test();
int main()
{
int m = 22, n = 44;
printf("n values : m = %d and n = %d", m, n);
test();
}
void test()
{
int m = 50, n = 80;
printf("nvalues : m = %d and n = %d", m, n);
}
OUTPUT:
values : m = 22 and n = 44
values : a = 50 and b = 80
53. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 53
Pro
gra
m
mi
ng
in
C
GLOBAL VARIABLE IN C
• The scope of global variables will
be throughout the program.
These variables can be accessed
from anywhere in the program.
• This variable is defined outside
the main function. So that, this
variable is visible to main
function and all other sub
functions.
#include<stdio.h>
void test();
int m = 22, n = 44;
int a = 50, b = 80;
int main()
{
printf("All variables are accessed from main function");
printf("nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
test();
}
void test()
{
printf("nnAll variables are accessed from"
" test function");
printf("nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
}
All variables are accessed from main function
values : m = 22 : n = 44 : a = 50 : b = 80
All variables are accessed from test function
values : m = 22 : n = 44 : a = 50 : b = 80
54. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 54
Pro
gra
m
mi
ng
in
C
OPERATORS IN C
The symbols which are used to perform logical and mathematical operations in a
C program are called C operators. C supports a rich set of built in operators. We
have already used several of them, such as +, -, *, /, %. Operators are used to
perform a program to manipulate data & variables. Operators are classified into a
number of categories:
1. Arithmetic Operators
2. Relational Operator
3. Logical Operator
4. Assignment Operator
5. Increment & Decrement Operator
6. Conditional Operator
7. Bitwise Operator
8. Special Operator (Sizeof())
55. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 55
Pro
gra
m
mi
ng
in
C
1. Arithmetic Operator
C Arithmetic operators are used to perform mathematical
calculations like addition, subtraction, multiplication, division
and modulus in C programs.
Example: “c=a+b;”
56. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 56
Pro
gra
m
mi
ng
in
C
Arithmetic Example
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %dn", c );
c = a - b;
printf("Line 2 - Value of c is %dn", c );
c = a * b;
printf("Line 3 - Value of c is %dn", c );
c = a / b;
printf("Line 4 - Value of c is %dn", c );
c = a % b;
printf("Line 5 - Value of c is %dn", c );
c = a++;
printf("Line 6 - Value of c is %dn", c );
c = a--;
printf("Line 7 - Value of c is %dn", c );
}
OUTPUT:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
57. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 57
Pro
gra
m
mi
ng
in
C
2. Relational Operator
Relational operators are used to find the relation between two
variables i.e. to compare the values of two variables in a C program.
For example, we may compare the age of 2 persons, or the price of
2 items and so on.
Example: “age>=60;”
58. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 58
Pro
gra
m
mi
ng
in
C
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
printf("Line 1 - a is equal to bn" );
} else {
printf("Line 1 - a is not equal to bn" );
}
if ( a < b ) {
printf("Line 2 - a is less than bn" );
} else {
printf("Line 2 - a is not less than bn" );
}
if ( a > b ) {
printf("Line 3 - a is greater than bn" );
} else {
printf("Line 3 - a is not greater than bn" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b ) {
printf("Line 4 - a is either less than or equal to bn" );
}
if ( b >= a ) {
printf("Line 5 - b is either greater than or equal to bn" );
}
}
OUTPUT:
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
59. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 59
Pro
gra
m
mi
ng
in
C
3. Logical Operator
These operators are used to perform logical operations on the
given expressions. There are 3 logical operators in C language.
They are, logical AND (&&), logical OR (||) and logical NOT (!). It
returns Boolean values (0,1). Truth Table:
Example: “a==b && a%2==0”
60. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 60
Pro
gra
m
mi
ng
in
C
Example of Logical Operator
#include <stdio.h>
main() {
int a = 5;
int b = 20;
int c ;
if ( a && b ) {
printf("Line 1 - Condition is truen" );
}
if ( a || b ) {
printf("Line 2 - Condition is truen" );
}
/* lets change the value of a and b */
a = 0;
b = 10;
if ( a && b ) {
printf("Line 3 - Condition is truen" );
} else {
printf("Line 3 - Condition is not truen" );
}
if ( !(a && b) ) {
printf("Line 4 - Condition is truen" );
}
}
OUTPUT:
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
61. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 61
Pro
gra
m
mi
ng
in
C
4. Assignment Operator
In C programs, values for the variables are assigned using
assignment operators. For example, if the value “10″ is to be
assigned for the variable “sum”, it can be assigned as “sum = 10;”.
Other assignment operators in C language are given below.
62. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 62
Pro
gra
m
mi
ng
in
C
Assignment Operator Example
#include <stdio.h>
main() {
int a = 21;
int c ;
c = a;
printf("Line 1 - = , Value of c = %dn", c );
c += a;
printf("Line 2 - +=, Value of c = %dn", c );
c -= a;
printf("Line 3 - -= , Value of c = %dn", c );
c *= a;
printf("Line 4 - *=, Value of c = %dn", c );
c /= a;
printf("Line 5 - /=, Value of c = %dn", c );
c = 200;
c %= a;
printf("Line 6 - %=, Value of c = %dn", c );
c <<= 2;
printf("Line 7 - <<=, Value of c = %dn", c );
c >>= 2;
printf("Line 8 - >>=, Value of c = %dn", c );
c &= 2;
printf("Line 9 - &=, Value of c = %dn", c );
c ^= 2;
printf("Line 10 - ^=, Value of c = %dn", c );
c |= 2;
printf("Line 11 - |=, Value of c = %dn", c );
}
63. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 63
Pro
gra
m
mi
ng
in
C
OUTPUT:
Line 1 - =, Value of c = 21
Line 2 - +=, Value of c = 42
Line 3 - -=, Value of c = 21
Line 4 - *=, Value of c = 441
Line 5 - /=, Value of c = 21
Line 6 - %=, Value of c = 11
Line 7 - <<=, Value of c = 44
Line 8 - >>=, Value of c = 11
Line 9 - &=, Value of c = 2
Line 10 - ^=, Value of c = 0
Line 11 - |=, Value of c = 2
64. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 64
Pro
gra
m
mi
ng
in
C
5. Increment / Decrement Operator
Increment operators are used to increase the value of the variable
by one and decrement operators are used to decrease the value of
the variable by one in C programs.
Syntax:
Increment operator : ++var_name; (or) var_name++;
Decrement operator : -- var_name; (or) var_name --;
They are of 2 types of Increment/decrement operator i.e
1. prefix/postfix Increment
2. Prefix/postfix Decrement
prefix increment (++a) postfix increment (a++)
prefix decrement(- -a) postfix decrement (a- -)
65. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 65
Pro
gra
m
mi
ng
in
C
Increment / Decrement Operator
• Difference between ++ and -- operator as postfix and prefix:
• When ++ is used as prefix (like: ++var), ++var will increment the
value of var and then return it but, if ++ is used as postfix (like:
var++), operator will return the value of operand first and then
only increment it.
• Example:
a=10;
b=a++;
B=++a;
a=11
a=11
b=10
b=11
66. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 66
Pro
gra
m
mi
ng
in
C
EXAMPLE
Example:
Increment operator: ++ i; i ++; Decrement operator: --i; i--;
/* prefix operators */
#include<stdio.h>
int main() {
int a = 7, b = 12, c;
c = b * (++a) + 5 * (++a);
printf(“ a = %d”, a);
printf(“n b = %d”,b);
printf(“n c = %d”,c);
}
Output:
a = 9
b = 12
c = 153 ( 12 * 9 + 5 * 9)
/* prefix and postfix operators */
#include<stdio.h>
int main() {
int a = 7, b = 12, c;
c = b * (a++) + 5 * (++a);
printf(“ a = %d”, a);
printf(“n b = %d”,b);
printf(“n c = %d”,c);
}
Output:
a = 9
b = 12
c = 136 ( 12 * 8 + 5 * 8)
/* postfix operators */
#include<stdio.h>
int main() {
int a = 7, b = 12, c;
c = b * (a++) + 5 * (a++);
printf(“ a = %d”, a);
printf(“n b = %d”,b);
printf(“n c = %d”,c);
}
Output:
a = 9
b = 12
c = 119 ( 12 * 7 + 5 * 7)
67. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 67
Pro
gra
m
mi
ng
in
C
6. Conditional / Ternary Operator
Conditional operators return one value if condition is true and
returns another value is condition is false. This operator is also
called as ternary operator.
Syntax : (Condition? true_value: false_value);
Example: (A > 100? 0: 1);
In above example, if A is greater than 100, 0 is returned else 1 is
returned.
68. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 68
Pro
gra
m
mi
ng
in
C
Example
#include <stdio.h>
void main()
{
int Large,x=10, y=20 ;
Large = ( x>y ? x : y ) ;
printf("x value is %dn", x);
printf("y value is %dn", y);
printf("Largest=%d",Large);
}
Output:
x value is 10
y value is 20
Largest=20
69. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 69
Pro
gra
m
mi
ng
in
C
7. Bitwise Operator
These operators are used to perform bit operations. Decimal values are
converted into binary values which are the sequence of bits and bit
wise operators work on these bits. Bit wise operators in C language
are & (bitwise AND), | (bitwise OR), ^ (XOR), ~ (bitwise NOT) << (left
shift) and >> (right shift).
~ Bitwise NOT
70. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 70
Pro
gra
m
mi
ng
in
C
Bitwise Operator
Bitwise NOT
A (42) : 00000000 00101010
-----------------------------------
~ (-43) : 11111111 11010101
-----------------------------------
& -- Bitwise AND
| -- Bitwise OR
^ -- Bitwise XOR
~ -- Bitwise NOT
A B A & B A | B A ^ B ~A
1 1 1 1 0 0
1 0 0 1 1 0
0 1 0 1 1 1
0 0 0 0 0 1
Bitwise AND
A (42) : 00000000 00101010
B (15) : 00000000 00001111
-----------------------------------
& (10) : 00000000 00001010
-----------------------------------
Bitwise OR
A (42) : 00000000 00101010
B (15) : 00000000 00001111
-----------------------------------
| (47) : 00000000 00101111
-----------------------------------
Bitwise XOR
A (42) : 00000000 00101010
B (15) : 00000000 00001111
-----------------------------------
& (37) : 00000000 00100101
-----------------------------------
71. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 71
Pro
gra
m
mi
ng
in
C
BITWISE SHIFT OPERATORS
Bitwise Left Shift ( << )
A (43) : 00000000 00101011
-----------------------------------
A << 2 : 00000000 10101100
-----------------------------------
Bitwise Right Shift ( >> )
(positive values)
A (43) : 00000000 00101011
-----------------------------------
A >> 2 : 00000000 00001010
-----------------------------------
Bitwise Right Shift ( >> )
(negetive values)
A (-44) : 11111111 11010100
-----------------------------------
A >> 2 : 11111111 11110101
-----------------------------------
Note : Right shift operator fills the left vacant fields with ‘zeros’ for positive
numbers, with ‘ones’ for negative numbers.
72. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 72
Pro
gra
m
mi
ng
in
C
Bitwise Operator Example
#include <stdio.h>
main() {
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %dn", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %dn", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %dn", c );
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %dn", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %dn", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %dn", c );
}
OUTPUT:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
73. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 73
Pro
gra
m
mi
ng
in
C
8. Special Operators
Some of special operators that C language offers.
74. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 74
Pro
gra
m
mi
ng
in
C
Precedence and Associativity of Operators
X=(A*B)+C-D+(E/F)
75. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 75
Pro
gra
m
mi
ng
in
C
C Type Casting Cont.……
76. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 76
Pro
gra
m
mi
ng
in
C
C Type Casting Cont.……
Typecasting is simply a mechanism by which we can change the data type
of a variable, no matter how it was originally defined. When a variable is
typecasted into a different type, the compiler basically treats the variable
as of the new data type.
CASTING DATA TYPES:
Result type of arithmetic phrase depends on operand types inside it.
When a phrase is consisted of various data types, result type is set by
defined casting rules. Rules for casting various data types in C language
are oriented to higher data type. There are two ways of casting data types
in C:
1. Implicit(automatic) casting
2. Explicit(given) casting
77. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 77
Pro
gra
m
mi
ng
in
C
Implicit(automatic) casting Cont.……
Implicit(automatic) casting: Implicit Casting (automatic
transformation) works in a way that a variable (operand) of
data type that is smaller in length (than data type of second
variable) (operand), transforming internally to variable of
data type with longer number length. It may sound mixed up.
Example:
int a;
float f, g;
g = a + f; // a transforms to float
78. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 78
Pro
gra
m
mi
ng
in
C
Automatic / Implicit Type Casting
1. char and short operands are converted to int
2. Lower data types are converted to the higher
data types and result is of higher type.
3. The conversions between unsigned and
signed types may not yield intuitive results.
4. Example
float f; double d; long l;
int i; short s;
d + f f will be converted to double
i / s s will be converted to int
l / i i is converted to long; long
result
Hierarchy
Double
float
long
Int
Short and char
79. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 79
Pro
gra
m
mi
ng
in
C
Explicit Type Casting
Explicit Casting (given transformation) of data types
has higher priority then automatic transformation.
General declaration of explicit (given) cast (cast operator):
(data_type) operand
Operand can be variable or phrase.
int a;
float c=10.5;
Example:
a = (int) c; /*a=c syntax error*/ invalid
b = (double)d + c;
80. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 80
Pro
gra
m
mi
ng
in
C
Explicit Type Casting
The general form of a type casting operator is
(type-name) expression
It is generally a good practice to use explicit casts than to rely
on automatic type conversions.
Example
C = (float)9 / 5 * ( f – 32 )
float to int conversion causes truncation of fractional part
double to float conversion causes rounding of digits
long int to int causes dropping of the higher order bits.
81. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 81
Pro
gra
m
mi
ng
in
C
Explicit Type Casting
Some examples:
Example 1:
float a = 5.25;
int b = (int)a; /*Explicit casting from float to int.
The value of b here is 5*/
Example 2:
char c = ’A’;
int x = (int)c; /*Explicit casting from char to int.
The value of x here is 65: the ASCII code of ‘A’*/
82. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 82
Pro
gra
m
mi
ng
in
C
Explicit Type Casting
Example 3:
int x=7, y=5 ;
float z;
z=x/y;
/*Here the value of z is 1*/
If we want to get the exact value of 7/5 then we need explicit casting from int to float:
int x=7, y=5;
float z;
z = (float)x/(float)y;
/*Here the value of z is 1.4*/
Example 4:
int x=70;
char c =(char)x;
/*The value of c here is F: the ASCII code of 70*/
83. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 83
Pro
gra
m
mi
ng
in
C
Sr.
No Type Casting Type Conversion
1 Type casting is a mechanism in which one data type is
converted to another data type using a casting ()
operator by a programmer.
Type conversion allows a compiler to convert one data type to
another data type at the compile time of a program or code.
2 It can be used both compatible data type and
incompatible data type.
Type conversion is only used with compatible data types, and
hence it does not require any casting operator.
3 It requires a programmer to manually casting one data
into another type.
It does not require any programmer intervention to convert one
data type to another because the compiler automatically
compiles it at the run time of a program.
4 It is used while designing a program by the
programmer.
It is used or take place at the compile time of a program.
5 When casting one data type to another, the destination
data type must be smaller than the source data.
When converting one data type to another, the destination type
should be greater than the source data type.
6 It is also known as narrowing conversion because one
larger data type converts to a smaller data type.
It is also known as widening conversion because one smaller
data type converts to a larger data type.
7 It is more reliable and efficient. It is less efficient and less reliable.
8 There is a possibility of data or information being lost in
type casting.
In type conversion, data is unlikely to be lost when converting
from a small to a large data type.
9 Float b = 3.0;
int a = (int) b
int x = 5, y = 2, c;
float q = 12.5, p;
p = q/x;
84. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 84
Pro
gra
m
mi
ng
in
C
2.3 Basic Input Output in C
• A program without any input or output has no meaning.
• Input process Output Ex. marks sheet of students
• Reading the data from input devices and displaying the result are
the two main tasks of any program.
• Input/output functions are the links between the user and the
terminal.
• Input functions are used to read data from keyboard are called
standard input functions.
– scanf(), getchar(),getche(),getch(),gets() etc.
• Output functions are used to display the result on the screen are
called standard output functions.
– printf(), putchar(),putche(),putch(),puts() etc.
85. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 85
Pro
gra
m
mi
ng
in
C
Basic Input Output in C
• In C, the standard library stdio.h provides functions for input
and output.
• The instruction #include<stdio.h> tells the compiler to search for
a file named stdio.h and places its contents at this point in the
program.
• The contents of the header file become part of the source code
when it is compiled.
• The input/output functions are classified into two types –
1. Formatted functions
2. Unformatted functions
86. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 86
Pro
gra
m
mi
ng
in
C
Formatted Functions
• Formatted functions allow the input read input from the keyboard or
the output displayed on screen to be formatted according to our
requirements.
– Input function: scanf()
– Output function: printf()
• Ex: consider the following data:
– 50, 13.45, Ram
– Int, float, char variables
• This is possible using the scanf function.
• scanf stands for scan formatted.
• The built-in function scanf() can be used to enter input data into the
computer from a standard input device.
87. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 87
Pro
gra
m
mi
ng
in
C
Formatted Functions
• The general form of scanf is,
scanf(“control string” , arg1, arg1,….. argn);
– Control string format in which data is to be entered.
– arg1,arg2… location where the data is stored.
– preceded by ampersand (&)
• The control string consists of individual groups of data formats, with one group for
each input data item.
• Each data format must begin with a percentage sign.
• General form of control string:
[whitespace character][ordinary character]%[field width] conversion character
– Whitespace characters [optional]
– Ordinary characters [Optional]
– Field width [Optional]
88. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 88
Pro
gra
m
mi
ng
in
C
Formatted Functions
89. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 89
Pro
gra
m
mi
ng
in
C
EXAMPLE
// Whitespace characters example
#include<stdio.h>
#include<conio.h>
void main()
{
int n1; char ch; clrscr();
printf("Enter a number: ");
scanf(“ %d",&n1); printf("Enter a
character: ");
scanf(“ %c",&ch);
printf("nNumber: %d t Character: %c",n1,ch);
getch();
}
OUTPUT:
Enter a number: 12
Enter a character: A
Number: 12 Character: A
90. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 90
Pro
gra
m
mi
ng
in
C
EXAMPLE
// Ordinary characters
#include<stdio.h>
#include<conio.h>
void main()
{
int day, year, month;
clrscr();
printf(“enter day month year in DD-MM-YYY format”);
scanf(“%d-%d-%d”,&day,&month,&year);
getch();
}
91. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 91
Pro
gra
m
mi
ng
in
C
michhane
//Field width example
#include<stdio.h>
#include<conio.h>
void main(){
int d;
printf(“Enter Max 5 numbers”);
scanf(“%5d”,&d);
printf(“Entered Numbers: %d”,d);
getch();
}
92. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 92
Pro
gra
m
mi
ng
in
C
michhane
//Input String
#include<stdio.h>
#include<conio.h>
void main()
{
char string[10];
printf(“Enter Your Name”);
scanf(“%s”,string);
printf(“Your Name is %s”);
getch();
}
93. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 93
Pro
gra
m
mi
ng
in
C
#include<stdio.h>
#include<conio.h>
void main()
{
char string[10];
printf("Enter Your Name:");
scanf("%s",string);
printf("My Name is %s",string);
getch();
}
94. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 94
Pro
gra
m
mi
ng
in
C
michhane • some versions of scanf() support the following conversion
specifications for strings:-
%[character]
–only characters specified within the brackets are
allowed in the input string.
%[^character]
–the character specified after the caret are not allowed
95. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 95
Pro
gra
m
mi
ng
in
C
#include<stdio.h>
#include<conio.h>
void main()
{
char string[10];
printf("Enter Your Name in uppercase:");
scanf("%[A-Z]",string);
printf("Your Name is %s",string);
getch();
}
96. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 96
Pro
gra
m
mi
ng
in
C
#include<stdio.h>
#include<conio.h>
void main()
{
char string[10];
printf("Enter Your Name:"); scanf("%[^n]",string);
printf("My Name is %s",string);
getch();
}
%[^n] tells the compiler to read a string until a newline character is
entered
97. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 97
Pro
gra
m
mi
ng
in
C
Reading Mixed Data Types
• printf(“enter an integer, floating number, gender and name:”);
scanf(“%d %f %c%s”,&i,&n1,&gender,&name);
• scanf() can contain mixed mode data.
• care should be taken to ensure that the input data items match
the control specification.
98. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 98
Pro
gra
m
mi
ng
in
C
Formatted Output
• refers to the output of data that has been arranged in a particular
format.
• printf() is a built in function which is used to output data from the computer
onto a standard device i.e. screen
• General form:
printf(“control string”,arg1,arg2,.....,arg n)
• The control string consists of four types of items -
– characters that will be printed on the screen as they appear.
– format specifications that define the output format for display of each item
– escape sequence characters such as n, t etc.
– any combination of characters, format specifications and escape
sequences.
99. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 99
Pro
gra
m
mi
ng
in
C
• The control string has the form:
%[flag] [field width][.precision] conversion character
• Flags [optional]
– “ – “ indicates data item to be left-justified
– “+” indicates a positive or negative sign to precede
– “0” indicates leading 0’s to appear instead of leading blanks
• Field width[optional]
– Same as before
• Precision [optional]
– The operation of precision field depends on the type of conversion. It
must start with a period (.).
100. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 100
Pro
gra
m
mi
ng
in
C
Unformatted Functions
• Doesn’t allow user to read or display data in desired format.
• These library functions basically deals with a single character or
a string of characters.
• The functions getchar(), putchar(), gets(), puts(), getch(),
putch(), getche(), putche() are considered as unformatted
functions.
101. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 101
Pro
gra
m
mi
ng
in
C
• getchar()
–Reads a character from a standard input device.
–It takes the form:
Character_variable= getchar();
–Character_variable is a valid C char type variable.
–When this statement is encountered, the computer waits
until a key is pressed and then assigns this character to
character_variable.
102. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 102
Pro
gra
m
mi
ng
in
C
• putchar()
–Displays a character to
the standard output
device.
–Its form:
putchar(character_varia
ble);
–Where character_variable
is a char type variable
containing a character
#include<stdio.h>
void main()
{
char gender;
clrscr();
printf(“Enter gender M or F”: );
gender=getchar();
printf(“Your Gender is: “);
putchar(gender);
getch();
}
103. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 103
Pro
gra
m
mi
ng
in
C
• getch() and getche()
– Reads single character the instant it is typed without waiting
for the enter key to be hit.
– getch() doesn’t print the character entered
– getche() displays the character when entered.
– General form
• character_variable=getch();
• character_variable=getche();
– In both functions, the character typed is assigned to the char type
variable character_variable.
104. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 104
Pro
gra
m
mi
ng
in
C
• putch()
–The function putch() prints a character onto the screen
–General form
• putch(character_variable);
–Character variable is a char type.
NOTE: These three functions are defined under the
standard library functions conio.h
105. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 105
Pro
gra
m
mi
ng
in
C
void main()
{
char ch1, ch2;
clrscr();
printf("Enter 1st character: ");
ch1=getch();
printf("n Enter 2nd character");
ch2=getch();
printf("n first character: ");
putch(ch1);
printf("nSecond character: ");
putch(ch2);
getch();
}
106. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 106
Pro
gra
m
mi
ng
in
C
• gets()
– Used to read string of text, containing whitespaces,
until a new line character is encountered.
– General form
gets(string_variable);
• puts()
– Used to display the string onto the terminal
– General form:
puts(string_variable);
107. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 107
Pro
gra
m
mi
ng
in
C
void main()
{
char name[20];
clrscr();
printf("Enter your name:");
gets(name);
printf("Your Name is: ");
puts(name);
getch();
}
108. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 108
Pro
gra
m
mi
ng
in
C
C – printf and scanf
• printf() and scanf() functions are inbuilt library functions in C
programming language which are available in C library by
default. These functions are declared and related macros are
defined in “stdio.h” which is a header file in C language.
• We have to include “stdio.h” file as shown in below C program to
make use of these printf() and scanf() library functions in C
language.
KEY POINTS TO REMEMBER IN C PRINTF() AND SCANF():
• printf() is used to display the output and scanf() is used to read the inputs.
• printf() and scanf() functions are declared in “stdio.h” header file in C library.
• All syntax in C language including printf() and scanf() functions are case
sensitive.
Note: C language is case sensitive. For example, printf() and scanf() are different from
Printf() and Scanf(). All characters in printf() and scanf() functions must be in lower case.
109. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 109
Pro
gra
m
mi
ng
in
C
C – printf and scanf
1. PRINTF() FUNCTION IN C LANGUAGE:
• In C programming language, printf() function is used to
print the (“character, string, float, integer, octal and
hexadecimal values”) onto the output screen.
• We use printf() function with %d format specifier to
display the value of an integer variable.
• Similarly %c is used to display character, %f for float
variable, %s for string variable, %lf for double
and %x for hexadecimal variable.
• To generate a newline,we use “n” in C printf()
statement.
110. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 110
Pro
gra
m
mi
ng
in
C
EXAMPLE PROGRAM FOR C PRINTF() FUNCTION:
#include <stdio.h>
main()
{ char ch = 'A';
char str[20] = “zebamalik.com";
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf("Character is %c n", ch);
printf("String is %s n" , str);
printf("Float value is %f n", flt);
printf("Integer value is %dn" , no);
printf("Double value is %lf n", dbl);
printf("Octal value is %o n", no);
printf("Hexadecimal value is %x n", no);
return 0;}
Output:
Character is A
String is zebamalik.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96
111. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 111
Pro
gra
m
mi
ng
in
C
#include <stdio.h>
int main()
{
int a=15;
float b=1845.78;
float c=18.75;
float d=1.45387;
printf("1=%dn",a);
printf("2=%8dn",a);
printf("3=%08dn",a);
printf("4=%fn",b);
printf("5=%fn",c);
printf("6=%fn",d);
printf("7=%8fn",b);
printf("8=%08fn",b);
printf("9=%8.4fn",b);
return 0;
}
1=15
2= 15
3=00000015
4=1845.780029
5=18.750000
6=1.453870
7=1845.780029
8=1845.780029
9=1845.7800
112. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 112
Pro
gra
m
mi
ng
in
C
C – printf and scanf
2. SCANF FUNCTION IN C LANGUAGE:
• In C programming language, scanf() function is used to
read character, string, numeric data from keyboard
• Consider below example program where user enters a
character. This value is assigned to the variable “ch” and
then displayed.
• Then, user enters a string and this value is assigned to
the variable “str” and then displayed.
• The format specifier %d is used in scanf() statement. So
that, the value entered is received as an integer and %s
for string.
• Ampersand is used before variable name “ch” in scanf()
statement as &ch.
113. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 113
Pro
gra
m
mi
ng
in
C
EXAMPLE PROGRAM FOR C PRINTF AND SCANF FUNCTIONS IN C PROGRAMMING LANGUAGE:
#include <stdio.h>
void main()
{
char ch;
char str[100];
printf("Enter any character n");
scanf("%c", &ch);
printf("Entered character is %c n", ch);
printf("Enter any string ( upto 100
character ) n");
scanf("%s", str);
printf("Entered string is %s n", str);
}
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
Saboo_Siddik_Polytechnic
Entered string is Saboo_Siddik_Polytechnic
114. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 114
Pro
gra
m
mi
ng
in
C
EXAMPLE PROGRAM FOR C PRINTF AND SCANF FUNCTIONS IN C PROGRAMMING LANGUAGE:
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character n");
scanf("%c", &ch);
printf("Entered character is %c n", ch);
printf("Enter any string ( upto 100 character ) n");
scanf("%s", &str);
printf("Entered string is %s n", str);
}
Enter any character
a
Entered character is a
Enter any string (upto 100 character )
Hello World
Entered string is Hello World
115. 13/04/202 PIC-22215(CO2I ) Prof. ZAIBUNNISA MALIK’s LECTURE SLIDE , PRINCIPAL(UNAIDED), MHSSP 115
Pro
gra
m
mi
ng
in
C