0% found this document useful (0 votes)
14 views

Introduction to C-programming

c programming

Uploaded by

Haf hafeefa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Introduction to C-programming

c programming

Uploaded by

Haf hafeefa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 155

Day 2

22-08-2024
PROGRAM BASICS
PROGRAM BASICS
▪Basic structure of C program: Character set, Tokens, Identifiers in C,

Variables
and Data Types , Constants, Console IO Operations, printf and scanf

▪Operators and Expressions: Expressions and Arithmetic Operators,

Relational and
Logical Operators, Conditional operator, size of operator, Assignment
operators and Bitwise Operators. Operators Precedence

▪Control Flow Statements: If Statement, Switch Statement, Unconditional

Branching using goto statement, While Loop, Do While Loop, For Loop,
3
Break and
C PROGRAM
INTRODUCTION

Martin Richards developed a language and
named it as BCPL(Basic Combined Programming
Language).

Ken Thomson developed a new language by
modifying BCPL and
is named it a B, the first letter of BCPL.

Dennis Ritchie modified the B language and is
named it as C.

C is the next letter in BCPL

C is the next letter coming after B in
alphabetical order also
4
C PROGRAM
INTRODUCTION

C is a high level programming language

C also supports low level programming
features

Bit-wise operations
● Register operations


Accessing memory locations using
● pointers
So it can be termed as a middle level language.

C is a structured programming language.

Programs written in C are efficient and fast.

It was actually developed as a language for writing
efficient
programs in UNIX systems. 5
▪A C program is divided into different sections. There are six main
sections a basic c program. The six sections are,

▪Documentation
▪Link
▪Definition
▪Global Declarations
▪Main functions
▪Subprograms

6
STRUCTURE OF A C
PROGRAM

7
A sample C
program
//Program to add two
numbers
#include<stdio.h>

int main()
{
int d_num1,d_num2,d_sum;

printf("Enter two numbers\n");

scanf("%d

%d",&d_num1,&d_num2);

d_sum=d_num1+d_num2;

printf("The sum of two numbers is %d\ 8


n",d_sum); return 0;
Points to remember

➢ Every statement in C should end with a semicolon.


➢ In C everything is written in lower case. However upper case letters
used for symbolic names representing constants.

➢ All the statements starting with # (hash) symbol are known as


preprocessor directives/commands, therefore #define and
#include are also known as preprocessor directives

➢ stdio.h is a header file, for standard input output functions.

➢ Single line comment is represented using //

➢ Multiple line comment is represented using /*……………….*/


➢ Comment lines are not executable statements and therefore
anything between/*and*/ is ignored by the compiler.
9
LANGUA
GE
▪A language is a finite set of character set (alphabets)

▪Various components in a language is formed from the alpahbet set

based on
a set of rules called grammars.

▪Statements are formed using keywords and identifiers based on


grammar
rules.

1
0
CHARACTER
SET
▪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. C language

character set contains the following set of characters...

✓ 1. Alphabets

✓ 2. Digits

✓ 3. Special characters
1
1
Alphabe
ts
▪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 1
2
Special Symbols
▪Special Symbols are + - * / % = & % # ~ !
()[]{}
_ ^ , ; . < > ? \ | ‘ “ blank space.
▪Space , tab and newline are called white
space
characters

1
3
1
4
TOKE
N
Every C program is a collection of instructions and every

instruction is a collection of some individual units.

▪Every smallest individual unit of a C program is called


token.

▪Every instruction in a C program is a collection of tokens.

▪Tokens are used to construct C programs and they are said to be

the basic building blocks of a C program.

1
5
▪In a c program tokens are of the following
types:
➢ 1. Keywords
➢ 2. Identifiers
➢ 3. Constants
➢ 4. Strings
➢ 5. Special Symbols
➢ 6. Operators

1
6
Keywor
ds Keywords are specific reserved words in C each of which has a

specific
feature associated with it.

They are having special predefined
meaning.
▪Keywords are always in
lowercase.

1
7
Identifi
er
▪An identifier is a collection of characters which acts as the name of

variable, function, array, pointer, structure, etc.

▪ Rules for Creating Identifiers

- First character must always be a letter


(alphabet) or underscore( _ )
- Following characters can be letters, digits or _
-
Special characters are not allowed (except _ )
-

-
Can be of any length, ANSI C recognizes first 31

characters.
-Keywords can not be used as
identifiers.
Case sensitive 1
8
Identifi
er
▪Examples for valid
identifiers

A, sum, Sum_of_Numbers, Avg2,
_int, FOR
▪Examples for Invalid
identifiers

2to - starts with a

4 digit Special
A-b charater -
▪ Mark, mark, MARK - Represents 3
-
identifiers.

▪Use meaningful words as identifiers.

1
9
Data Types
▪Data types in the c programming language are used to specify what kind

of
value can be stored in a variable.

▪The memory size and type of the value of a variable are

determined by the variable data type.

▪In the c programming language, data types are classified as follows

▪ 1. Primary data types (Basic data types OR Predefined data types)

▪ 2. Derived data types (Secondary data types OR User-defined data


types)

▪ 3. Enumeration data types

▪ 4. Void data type


2
0
Primitive Data Types
➢ char: The most basic data type in C. It stores a single character and

requires a
single byte of memory in almost all compilers.

➢ int: As the name suggests, an int variable is used to store a decimal integer. It

requires 2 or 4 bytes of memory.

➢ float: It is used to store real numbers (numbers with floating point value)

with
single precision. It requires 4 bytes of memory.

➢ double: It is used to store floating point numbers with double precision. Memory

required is 8 bytes.

➢ There is no boolean data type in C.

2
➢ Size varies from one compiler to another. 1
Data Type Qualifiers
in C
➢ Data type qualifiers
are :

short,
long

signed,
unsigned
➢ Usage is
:

short -2
int bytes

long int - 4 bytes (or 8 bytes)


signed int - same as int (-ve and +ve)


unsigned int - 0 to maximum

➢ If no data type is specified with these qualifiers then default


datatype is int.

➢ The datatype int will sometimes be same as either short int or long 2
int. 2
Data Type Qualifiers
in C
➢ sizeof(short int) <= sizeof
(int)

➢ sizeof (int) <= sizeof (long


int)

➢ ●
signed
Qualifiers with char - value (-128 to
char +127)

unsigned char - value
( 0 to 255)
long
➢ The data type double can also be qualified double.
➢ using qualifiers are keywords
These
in C.

2
3
2
4
void data
type
▪The void data type means nothing or no value.

▪Generally, the void is used to specify a function which does not return
any
value.

▪We also use the void data type to specify empty parameters of a
function.

2
5
Variabl
es
▪ A variable is an identifier that is used to represent some specified

type of information within a designated portion of the program.

▪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.

▪The data item can be accessed in the program simply by

referring to the variable name.

2
6
2
7
Declarati
on
▪A declaration associates a group of variables with a specific data type.

▪All variables must be declared before they can appear in executable statements.

▪A declaration consists of a data type, followed by one or more variable names,

ending with
a semicolon.

▪General form is :
▪ datatype identifier-1, identifer-2, ....,
identifier-n;
▪ Example
s:

int number, mark,
sum;


float average;


char flag;
2
8
Declarati
on
▪Initial values can be assigned to variables within a type declaration.

▪To do so, the declaration must consist of a data type, followed by a

variable
name, an equal sign (=) and a constant of the appropriate type.

▪A semicolon must appear at the end, as usual.

▪General form :

datatype variable =
constant;

int count =
0;

float sum =
0.0;

char space = ’ ‘;
2
9
Constan
ts
▪Constants are items whose value does not change during the

execution of
the program.

▪There are four basic types of constants in C


Integer constant


Floating point constant


Character constant


String constant

3
0
Numeric
Constants
▪Numeric constants


Integer constant


Floating point constant

▪The following rules apply to all numeric-type constants.


Commas and blank spaces cannot be included within the
constant.


The value
constant
of acan be preceded
constant cannotby a minus
exceed (-) sign if
specified

desired.
minimum and maximum bounds.


For each type of constant, these bounds will vary from one C
compiler
to 3
another. 0
Integer
Constants
▪An integer constant is an integer-valued number.

▪Thus it consists of a sequence of digits.

▪Integer constants can be written in three different number


systems:


decimal (base 10),


octal (base 8) and


hexadecimal (base 16).

3
2
Decimal Integer
Constants
▪A decimal integer constant can consist of any combination of digits

taken
from the set 0 through 9.

▪If the constant contains two or more digits, the first digit

must be something other than 0.

▪Several valid decimal integer constants are shown


below.
1 743 5280 32767
▪0 9999

3
3
Decimal Integer
Constants
▪The following decimal integer constants are written incorrectly

for the reasons stated.


12,245 illegal character (, )


36.0illegal character (.)


10 20 30illegal character (blank space)


123-45-6789 illegal character (-)


0900 the first digit cannot be a zero.

3
4
Octal Integer
Constants
▪An octal integer constant can consist of any combination of digits

taken
from the set 0 through 7.

▪However the first digit must be 0, in order to identify the constant as

an
octal number.

▪Several valid octal integer constants are shown below.


0 01 0743 077777
▪The following octal integer constants are written incorrectly for the

reasons stated.

3

743 does not begin with 0. 5
Hexadecimal Integer
Constants
▪A hexadecimal integer constant must begin with either 0x or 0X.

▪It can then be followed by any combination of digits taken from the

sets
0 through 9 and a through f (either upper- or lowercase).

▪Note that the letters a through f (or A through F) represent the

(decimal) quantities 10 through 15, respectively.

▪Several valid hexadecimal integer constants are shown


below.


0X29 0x1 0X7FFF 0xabcd

3
6
Hexadecimal Integer
Constants
▪The following hexadecimal integer constants are written incorrectly

for the reasons stated :


0X12.34 Illegal character ( . )


0BE38 Does not begin with 0x
or 0X

0x.4bffIllegal character ( . )

0XDEFG Illegal character
(G)

3
7
Integer
Constants
▪The magnitude of an integer constant can range from some minimum to

some maximum value that varies from one computer to another (and
from one
compiler to another, on the same computer).

▪ If 2 bytes are used for representing the integer then the range is -32768

to32767. ( -(215) to
(215-1) )

▪If 4 bytes are used the the range will be - (231) to (231-1)

▪ Unsigned integer constants

▪They are identified by appending the letter U (either upper- or lowercase)

to the end of the constant. Ex:


3
52000U 8
Long Integer
Constants
▪Represents large range of integer numbers.

▪Identified by appending the letter L (either upper- or lowercase) to the

end of the constant.


Eg. 23252000L


If 4 bytes are used for representing, then the range will be - (231) to
231-1.


Unsiged Long Integer Constants

An unsigned long integer may be specified by appending the letters UL to
the
end of the constant.


The letters may be written in either upper or lowercase. 3
9

Several unsigned and long integer constants are shown
below :


Constant Number System

50000U decimal

123456789 (unsigned)
L decimal (long)

123456789 decimal (unsigned
UL long) octal (long)

0123456L octal (unsigned)

07777771U hexadecimal

0X50000U (unsigned)

0XFFFFFUL hexadecimal
(unsigned long)

4
0
Floating Point
Constants
▪A floating-point constant is a base-10 number that contains either a

decimal
point or an exponent (or both).

▪Several valid floating-point constants are shown below.



0. 1. 0.2 827.602


50000. 0.000743 12.3
315.0066

2.1E-80.006e-3 1.6667E+8
.12121212e12
▪The number 1.2 x 10-3 would be written as 1.2E-3 or
1.2e-3.

▪This is equivalent to 0.12e-2, or 12e-4, etc

4
1
Floating Point
Constants
▪The following are not valid floating-point constants for the reasons
stated.


1 Either a decimal point or an exponent must be
present.
2.34E+10.2 The exponent must be an integer quantity (it cannot


1,000.0 Illegal character (, ).

contain a decimal point).



3.47E 10 Illegal character (blank space) in the
exponent.

4
2
Floating Point
Constants
▪Integer constants are exact quantities, whereas floating-point

constants are approximations.

▪The floating-point constant 1.0 might be represented within the

computer's memory as 0.99999999. . . , even though it might


appear as 1.0 when it is displayed

▪Therefore floating-point values cannot be used for certain purposes,

such as counting, indexing, etc., where exact values are required.

4
3
Character
Constants
▪A character constant is a single character, enclosed in single
quotation marks.

‘A’ ’9’ ’+’ ’ ‘ ’&’

▪Each constant have an internal integer value.

▪ASCII (American Standard Code for Information Interchange) – is 7


bit code.

▪Now using Extended ASCII – which is 8 bit code


‘A’ -
- 97 65 ’B’
’b’ - - 66

‘a’
98

‘ ‘
- 32

‘0’
- 48
4
4
String
Constant
▪A string constant consists of any number of consecutive

characters (including none), enclosed in double quotation


marks.

▪Examples :

“Welcome ”green” ”Abdul Khalam “$10.35
” Azad” ”

“a+b” ” “
”line1\nLine2\nLine3”

“She said, \” It is Ok \” “ printed as She said “It is
Ok”
▪A null string is represented as “”

▪The compiler automatically places a null character (\0) at the end of

every
4
string constant, as the last character within the string. 5
String
Constant
▪Lenght of a string constant is the number of characters in it.


Length of “abcd” is 4


Length of “a\nb” is 3
▪A character constant (e.g. ‘A’ ) and the corresponding single-

character
string constant ( "A" ) are not equivalent.

▪A character constant has an equivalent integer value, whereas

a string constant does not have an equivalent integer value

▪Single character string constant consists of two characters - the

specified character followed by the null character (\0).


4
6
Escape
Sequences
▪It is used for representing the nonprintable characters

(backspace, tab, newline, null,....) and some special characters


(‘, “, \ etc).

▪An escape sequence always begins with a backward slash ( \

) and is followed by one or more special characters.

▪Such escape sequences always represent single character, even though

they are written in terms of two or more characters.

▪For example, a line feed (LF), which is referred to as a newline in C,

can
be represented as \n.
4
7
Charact Escape
er Seauence
bell \a
(alert)
Backspa \b
ce
horizontal \t
tab
vertical \
tab v
newline (line \n
feed)
form \f
feed
carriage \r
return
quotation mark \”
(")
Apostrophe \
(')
question mark ’
(?) \
Backslash ?
\\
(\)
Nul \
4
l 0
7
Escape
Sequences
▪Of particular interest is the escape sequence \0.

▪This represents the null character (ASCII 0)

▪It is used to indicate the end of a string.

▪Note that the null character constant ‘\0’ is not equivalent to the

character constant ‘0’.

4
9
5
0
CONSOLE I/O
FUNCTIONS
▪A console comprises the screen and the keyboard.

▪The Console Input and Output functions can be classified into two
categories:

1. Formatted console I/O functions:


These functions allow the user to read the input from the keyboard and
the output displayed on the VDU, used for performing input/output
operations at console and the resulting data is formatted and transformed.

2. Unformatted console I/O functions:


Unformatted console input/output functions are used for performing
input/output operations at console and the resulting data is left
unformatted and untransformed i.e. it is left in its raw and original
5
form. 1
CONSOLE I/O FUNCTIONS
CONTD..

5
2
FORMATTED I/O
FUNCTIONS
▪They provide the flexibility to receive the input in

some fixed format and to give the output in desired


format.

▪The printf() and scanf() functions comes under this


category.
▪Both functions are inbuilt library functions, defined in

stdio.h (header file)

5
3
Writing output data -
printf()
▪The printf function can be used to output any combination of numerical

values,
single characters and strings.

▪In general terms, the printf function is written as



printf ( control_string, arg1, arg2, . . . , argn)
where control_string refers to a string that contains formatting information,

▪arg1,
andarg2, . . . , argn are arguments that represent the individual output
data
items.

▪The arguments can be constants, single variable or array names, or more

complex expressions.

5
4
Writing output data - printf()
▪The control_string consists of individual groups of characters,

with one character group for each output data item.

▪Each character group must begin with a percent sign (%).

▪In its simplest form, an individual character group will consist of the

percent sign, followed by a conversion character indicating the type of


the corresponding
data item.

▪Multiple character groups can be contiguous, or they can be separated

by
other characters, including whitespace characters

5
5
Convertion characters– for printf()
and scanf()

5
6
Writing output data - printf()

▪printf(“%d”, d_sum);

▪printf(“%f”, f_sum);

▪printf(“%d %f %s”, d_sum,f_sum,”hello”);

▪printf(“Sum of %d and %d is %d”, d_first,d_second,d_sum);

▪printf(“Sum of %d and %d is %d”,


d_first,d_second,d_first+d_second);

▪f_sum = 7472.342789
printf(“%f %e”, // 7.472343e+
f_sum,f_sum); 7472.342789 03
▪printf(%6d”,d_sum
);

▪printf(%2.3f”,f_su
m); 5
7
Reading Input data - scanf()
▪Input data can be entered into the computer from a standard input

device
by means of the C library function scanf.

▪This function can be used to enter any combination of numerical

values,
single characters and strings.

▪The function returns the number of data items that have been

entered successfully.

▪In general terms, the scanf function is written as

▪ scanf(control_string , arg1, arg2, . . . , argn)


▪ where control_string refers to a string containing certain 5
8
required formatting information, and arg1,..., argn are arguments
Reading Input data -
scanf()
▪Arguments are addresses of
variables

5
9
Reading Input data -
scanf()
▪scanf(“%d %d”,&d_first,&d_second);

▪scanf(“%f %c”,&f_v1,&c_v2);

▪scanf(“%d-%d-
%d”,&d_day,&d_month,&d_year);

6
0
UNFORMATTED CONSOLE I/O
FUNCTIONS
▪The unformatted console input/output functions deal with a

single character or a string of characters.

▪We often want a function that will read a single character the instant it

is
typed without waiting for the ENTER key to be hit as in scanf( )

6
1
Character Input
▪In C language getchar() function is used to read a character

through the keyboard.

▪This function returns the character read.

▪Common usage is


ch = getchar(); where ch is a char or int
variable.

▪The function declaration of this in stdio.h header file is int


getchar(void)

▪For giving input, type a character followed by ENTER key.

▪If ENTER key is pressed without giving a character then ENTER key is

taken as 6
2
Character
Output
▪In C language putchar() function is used to output a to the
display
character device.

▪ Common
usage is

putchar(character_ite
m)
▪ The character_item can be expressed as :


A char/int constant or A char/int variable or A
char/int expression

▪ The single character is displayed on the screen.

▪ Examples:

putchar(‘A’ //
) A

putchar(6 //
B 6
6)
2
Character
Output
▪Examples: char ch=’Z’; int
i=66;


putchar(ch) //
Z


putchar(i) // B


putchar(ch+32)
// z


putchar(‘a’-32)
// A


putchar(i+1) //
C 6
4
6
5
▪Write a program to read and display a number.

▪Write a program to find the sum of two numbers.

▪Write a program to find the area and perimeter of a


circle.

▪Write a program to swap two numbers.

6
6
Operators in
C
▪The data items that operators act upon are called operands.

▪Some operators require two operands, while others act upon

only one operand.

▪ Most operators allow the individual operands to be


expressions.

6
7
Operators in
C
▪Categories of operators :


Arithmetic
operators


Unary operators


Relational
operators


Logical operators


Assignment
operators


Conditional
operator 6
8
Arithmetic Operators
in C
▪Arithmetic operators :


There are five arithmetic operators in C.
They are
Operator Purpose
+ Addition

-
Sutraction

*
Multiplication

/
Division
% Remainder of 6
9
Arithmetic Operators
in C
▪There is no exponentiation operator in C.

▪The operands acted upon by arithmetic operators must represent


numeric
values.

▪Thus, the operands can be


integer quantities,


Floating-point quantities or

characters (remember that character constants represent
integer values, as determined by the computer’s
character set).

7
0
Arithmetic Operators
in C
▪The remainder operator (%) requires that


both operands be integers and the second operand be
nonzero.

▪Similarly, the division operator (/) requires that



the second operand be
nonzero.
▪Division of one integer quantity by another is referred to as

integer division.

▪This operation always results in a truncated quotient (ie.


Interger part
only).

7
1
Unary Operators
in C
▪Operators that act upon a single operand to produce a
new value.
▪Unary Minus (-)


Ex:- - -
root1 (x+y
-743 )

causes its operand to be increased by 1.


▪Increment operator

(++)
▪Decrement operator (--)


causes its operand to be decreased by 1.

▪The operand used with each of these operators must be a single


variable.
7
2
Increment Operators
in C
▪Pre-increment operator - ++<id> - incremented value of
<id>is used


Ex :- ++a where a is an interger
variable.

▪First increment the variable and use the incremented value.


printf ("a = %d\n", a);//
int a=5; a=5


printf ("a = %d\n", + //
+a);

printf ("a = %d\n", a);
//
a=6 a

7
3
Increment Operators
Post-increment
in C operator: <id>++
- value of <id>is used
then incremented and


Ex :- a++ where a is an interger variable.
▪ Use the current vaule of the operand and then incremented
by 1.
int

a=5,b=3;

printf ("a = %d\n", a); // a=
5

printf ("a = %d\n", a++); // a=
5

printf ("a = %d\n", a); a =6
// a=%d”,c,a); c=+

c = a++ + b; printf(“c +a + b; // c= 8
= %dprintf(“c = %da= a=6

%d”,c,a); // c= 7
3
Decrement Operators
in C
▪Pre-decrement operator:


Ex :- --a where a is an interger variable.

▪First decrement the variable and then use the decremented


value.


int a=5;

printf ("a = %d\n", a);// a=5


printf ("a = %d\n", //
--a);

printf ("a = %d\n", a);
//
a=4 a

75
Decrement Operators
in C
▪Post-decrement operator:


Ex :- a-- where a is an interger variable.

▪Use the current value of the operand and then it will be


decremented by 1
● int a=5;

● printf ("a = %d\n", // a = 5


a);
● printf ("a = %d\n", // a = 5
a--);
● printf ("a = %d\n", // a =
a); 4

76
The sizeof Operator
in C
▪The sizeof operator returns the size of the its operand in
bytes

▪Usage is
Example Output
printf(“%ld”, sizeof 123); 4
printf(“%ld”, sizeof “abcd”); 5
printf(“%ld”, sizeof 12.3); 8
char ch;
1
printf (“%ld”, sizeof ch);

77
#include
<stdio.h> void
main()
{
printf("%ld\n",
sizeof(char)); printf("%ld\
n", sizeof(int));
printf("%ld\n",

} sizeof(float)); printf("%ld\
n", sizeof(double));
Outp
ut
1
4
4
8
78
Relational
Operators:
▪There are four relational operators

in C. Operator Meaning

▪ < less than

▪ <= less than or equal to

▪ > greater than


>= greater than or equal
▪Theretoare two equality operators

in C. Operator Meaning

▪ == equal to

▪ != not equal
to

79
Relational Operators:

▪These are used for comparison of the values of two operands.


▪1. Equal to operator: Represented as ‘==’, the equal to operator
checks
whether the two given operands are equal or not. If so, it returns

1. Otherwise it returns 0.
▪For example, 5==5 will return 1.
▪2. Not equal to operator: Represented as ‘!=’, the not equal to
operator checks
whether the two given operands are equal or not. If not, it returns 1.
Otherwise it returns 0. It is the exact boolean complement of the
‘==’ operator.

80
▪For example, 5!=5 will return 0.
▪ 3. Greater than operator: Represented as ‘>’, the greater than

operator checks
whether the first operand is greater than the second operand or not.
If so, it returns 1. Otherwise it returns 0.

▪ For example, 6>5 will return 1.


▪ 4. Less than operator: Represented as ‘<‘, the less than operator

checks
whether the first operand is lesser than the second operand. If so, it
returns

1. Otherwise it returns 0.
▪ For example, 6<5 will return 0.

81
▪5. Greater than or equal to operator: Represented as ‘>=’, the

greater than or
equal to operator checks whether the first operand is greater than or
equal to the second operand. If so, it returns 1 else it returns 0.

▪ For example, 5>=5 will return 1.


▪6. Less than or equal to operator: Represented as ‘<=’, the less

than or equal to
operator checks whether the first operand is less than or equal to the
second operand. If so, it returns 1 else 0.

▪ For example, 5<=5 will also return 1.

82
Logical Operators:
▪They are used to combine two or more conditions/constraints or to

complement the evaluation of the original condition under


consideration. They are described below:

▪1. Logical AND operator: The ‘&&’ operator returns 1 when both

the conditions under consideration are satisfied. Otherwise it returns


0. For example, a && b returns 1 when both a and b are 1 (i.e. non-
zero).

83
▪2. Logical OR operator: The ‘||’ operator returns 1 even if one (or both)

of the conditions under consideration is satisfied. Otherwise it returns 0.


For example, a
|| b returns 1 if one of a or b or both are 1 (i.e. non-zero). Of course, it
returns 1 when both a or b are 1.

84
▪3. Logical NOT operator: The ‘!’ operator returns 1 if the condition

in consideration is not satisfied. Otherwise it returns 0. For example, !


a
returns 1 if a is 0, i.e. when a=0.

85
Assignment Operators:

▪Assignment operators are used to assign value to a variable.

▪The left side operand of the assignment operator is a variable and

right
side operand of the assignment operator is a value.

▪The value on the right side must be of the same data-type of

variable on
the left side otherwise the compiler will raise an error.

Different types of assignment operators are shown below:


▪1. “=”: This is the simplest assignment operator. This operator is used

to
86
assign the value on the right to the variable on the left.
▪2. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This

operator first adds the current value of the variable on left to the value
on right and then
assigns the result to the variable on the left.

Example: (a += b) can be written as (a = a + b)

If initially value stored in a is 5. Then (a += 6) = 11.


▪3. “-=”: This operator is combination of ‘-‘ and ‘=’ operators. This

operator first
subtracts the value on right from the current value of the variable on left
and then assigns the result to the variable on the left.
Example: (a -= b) can be written as (a = a - b) If
87
initially value stored in a is 8. Then (a -= 6) = 2.
▪4. “*=”: This operator is combination of ‘*’ and ‘=’ operators. This

operator first multiplies the current value of the variable on left to the
value on right and then assigns the result to the variable on the left.

Example: (a *= b) can be written as (a =

a * b) If initially value stored in a is 5. Then (a

*= 6) = 30.
▪5. “/=”: This operator is combination of ‘/’ and ‘=’ operators. This

operator first
divides the current value of the variable on left by the value on right
and then assigns the result to the variable on the left.
Example: (a /= b) can be written as (a = a / b)
If 88
Bitwise Operators:

▪The Bitwise operators are used to perform bit-level operations on the


operands.
▪The operands are first converted to bit-level and then the

calculation is performed on the operands.

▪The mathematical operations such as addition, subtraction, multiplication etc.

can be performed at bit-level for faster processing.

▪1. & (bitwise AND) in C takes two numbers as operands and does AND on

every bit of two numbers. The result of AND is 1 only if both bits are 1.

▪2. | (bitwise OR) in C takes two numbers as operands and does OR on every

bit of two numbers. The result of OR is 1 if any of the two bits is 1.

89
▪3. ^ (bitwise XOR) in C takes two numbers as operands and does XOR

on every
bit of two numbers. The result of XOR is 1 if the two bits are different.

▪4. ~ (bitwise NOT) in C takes one number and inverts all bits of it.

90
91
▪5. >> (right shift) in C takes two numbers, right shifts the bits of the
first

operand, the second operand decides the number of places to shift.

➢ eg: lets take N=32; which is 100000 in Binary Form.

➢ Now, if “N is right-shifted by 2” i.e N=N>>2 then N will become


001000
▪6. << (left shift) in C takes two numbers, left shifts the bits of the first
operand,

the second operand decides the number of places to shift.

➢ eg: lets take N=22; which is 00010110 in Binary Form.

➢ Now, if “N is left-shifted by 2” i.e N=N<<2 then N will become 92


01011000.
Conditional
Operator
▪Conditional operator is of the form


Expression1 ? Expression2 : Expression3 .
▪Here, Expression1 is the condition to be evaluated. If the

condition(Expression1) is True then we will execute and return the result


of Expression2 otherwise if the
condition(Expression1) is false then we will execute and return the
result of Expression3.

▪We may replace the use of if..else statements by conditional operators.

93
Conditional
Operator
▪Note that only one of the embedded expressions (either

expression-2 or expression-3) is evaluated when determining


the value of a conditional expression.

▪Example


a>b?a:
b

small = a < b ? a : b

▪Precedence of conditinal operator is just above the assignment


operators

▪The associativity is Right to Left.

94
Largest of two numbers using conditional operator
(ternary
operator)
//Program to find the largest of two numbers
#include<stdio.h>
{
void main()
int
d_num1,d_num2,d_large;
printf("Enter two numbers\
scanf("%d%d",&d_num1,&d_num2);
n");
d_large = d_num1>d_num2 ?
d_num1:d_num2;
printf("Largest=%d\n",d_large);

95
Expressions in
C
▪An expression represents a single data item, such as a

number or a character.

▪The expression may consist of a single entity, such as a

constant, a variable, an array element or a reference to a


function.

▪It may also consist of some combination of such entities, interconnected

by one
or more operators.

▪Expressions can also represent logical conditions that are either true or
false.

▪However, in C the conditions true and false are represented by the


96
integer
Expressions in
C
▪An expression can
be :


A constant

A variable or


Operands connected with
operators
▪Exampl
es

32, ‘A’, 3.14
“String”, Sum, average,

name,
a*b, a-

mark b, a<
=b
a+b, a/b,
97
Operator Precedence and
associativity
▪Operator Precedence :


Defines the order in which operators in an expression will be
evaluated.
The operator with higher precedence will be evaluated before
evaluating an operator with a lower precedence.


Eg. 2*3 +4;

▪Associativity of
operator:

Defines the order in which operators of the same precedence in an
expression will be evaluated.


It can be either left to right or right to
left. 98
Operator Precedence and
associativity

99
Operator Precedence and
associativity

10
0
Operator Precedence and
associativity PUMA RELL
Parenthese,
Operator dot, arrow Operator
Category TAC Associativity
s
Unary Operators - ++ sizeof R->L
-- ! (type)
&
Arithmetic multiply, * / % L->R
divide and remainder
Arithmetc add and + - L->R
subtract
Relational Operators < <= > L->R
>
=
Equality Operators == != L->R
Logical and && L->R
Commor
Logical || L->R
10
1
Operator Precedence and
associativity

int a = 5, b = 6, c = 4,result1;
result1 = a-- * b -++c;
printf("\n%d",result1);

result1 = --a * b -++c;


printf("\n%d",result1);

10
2
Type Conversions in C
▪Implicit type conversion :


Both the operands must be of same type for an arithmetic operation.


If the operands are of different types, then the system automatically converts the type
of operand with lower precision to the type of other.


This is also used when LHS of an assignment operrator is having lower precision
than that of the RHS operand.


It is performed only if the operand data types are compatible.

10
3
Type Conversions
in C
▪Implicit type
conversion :

10
4
Type Conversions
in C
▪Explicit type conversion (type
casting) :

Programmer can force the system to convert the data type of an
expression .


The syntax
is:

( <data
type> )<exp>


Eg. (float) 3/4;

It is treated as a unary
operator.

10
5
Control Structures
CONTROL FLOW
S TATE ME NT

C provides two styles of flow control:


✓ Branching
✓ Looping
▪Branching is deciding what actions to take.
▪looping is deciding how many times to take a certain
action.

10
6
Branchi
ng
1) if statement

▪This is the simplest form of the branching statements.

▪It allows the compiler to test the condition first and then, depending

upon
the result it will execute the statement.

▪If the condition is true then the statement or block of statements

within if statement is executed

▪otherwise these statements are skipped.

10
7
Syntax – if
Statement

if (condition)
{
Block of
statements;
}

10
8
//Example – if
Statement #include
<stdio.h>

void main ()
{
int d_num = 10;
if( d_num < 20 )

{
//if
condition is
true then
print the
following

printf("d_nu
m is less
than 20\ 10
n" ); 9
Syntax – if else
Statement

if (expression)
{
Block of
statements;
}
else
{
Block of
statements;
}

11
0
#include
<stdio.h> void
main()

{
int
m=40,n=20;
if(m==n)

{
pri
ntf
("
m
an
d
n
ar
e
eq 11
ua 1
Syntax if….else if….else / Else-if
ladder
if (expression)
{
Block of statements;
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
}
11
2
Write a program to test whether a number is negative or
positive or zero?
#include <stdio.h>

void main()

{
int n;
printf("Enter the value of n");

scanf("%d",&n);

if( n > 0)
{
printf("Positive");
}
else if(n < 0)
{
printf("Negative");
else {
} printf("Zero"
);

} }

11
3
Nested if
statement
▪ Placing if statement inside another if statement is
called Nested if.
Syntax of Nested if statement
if (expression)
{
Block of statements;

if(expression)

{
Block of statements;
}
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
}
11
4
/*Check if a number is less than 100 or not. If it is less than 100 then check if it is odd or even*/
#include
<stdio.h>

int main()
{
int n;
printf("Enter a number:");
scanf("%d",&n); if(n<100)

{
printf("%d is less than 100\n",n);
if(n%2==0)
printf("%d is
even",n); else

printf("%d is
odd",n);
}
else printf("%d is equal to or greater than
return 100",n);
0;
}

11
5
The switch
▪ Switch statement in C statement
tests the value of a variable and compares it
with
multiple cases.

▪Once the case match is found, a block of statements associated

with that particular case is executed.

▪Each case in a block of a switch has a different name/number which is

referred to
as an identifier.

▪The value provided by the user is compared with all the cases inside the

switch
block until the match is found.
11
▪If a case match is NOT found, then the default statement is executed, and the 6
switch( expressio
n)
{
case value-1:
Block-
1;
Break;

case value-2:
Block-
2;
Break;

case value-n:
Block-
n;
Break;

default:
Block-
1;

Break; 11
7
#include
<stdio.h> int
main() {

int num;
printf("Enter
the
number\
n");
scanf("%d",&nu
m); switch
(num) {
case 7:

printf("Value is

7"); break;

case 8:
printf("Value is
8");

break;

case 9:
printf("Value is
9");

break;

} default: 11
printf("Out of 7
goto
statement
▪In C programming, goto statement is used for altering the normal

sequence of program execution by transferring control to some


other part of the
program.

▪The goto statement is a jump statement which is sometimes also


referred to
as
unconditional jump statement.

▪The goto statement can be used to jump from anywhere to

anywhere
within a function.
11
9
12
0
#include
<stdio.h> void
main()

{
int n;
printf("Enter
the value of
n");
scanf("%d",
&n);

if(n<0)
goto
END;

if(n % 2
==0)

printf("E
12
ven\n"); 1
Class Work

▪Program to find largest of 3 integer values.

▪Program to read the total marks obtained by a student in an


examination (out
▪ of 500)and
Total display the result status as defined below
- Result
Marks – First class with
● [80,100] distinction

[60,80
● ) - First class

● [40,60 - Passed
) - Failed
[0,40)
▪Using switch-case develop a simple menu driven calculator
program.

12
2
LOOP CONTROL
STRUCTURE
▪This involves repeating some portion of the program either a

specified number of times or until a particular condition is


being satisfied.

▪This repetitive operation is done through a loop control


instruction.

▪The three types of loops available in C are:

▪ while statement

▪ do-while statement

▪ for statement
12
3
LOOP CONTROL
STRUCTURE CONTD..
▪A looping process, in general, would include the following four steps:

1. Setting and initialization of a condition variable.

2. Execution of the statements in the loop.


3. Test for a specified value of the condition variable for execution of
the loop.

4. Incrementing or updating the condition variable.

12
4
WHILE
LOOP
▪It is an entry control loop.
▪In a while loop, loop control variable should be initialized before the loop
begins.
▪The loop variable should be updated inside the body of the while

Syntax
initialize loop counter;
while (test loop counter using a condition)
{
statement(s);
…………
increment loop counter;
}
12
5
How while loop
works?

➢ The while loop evaluates the test expression inside the


parenthesis ().
➢ If the test expression is true, statements inside the body of while
loop are executed. Then, the test expression is evaluated again.

➢ The process goes on until the test expression is evaluated to


false.

➢ If the test expression is false, the loop terminates (ends).

12
6
Example 1: while loop
// Print numbers from 1 to
5
#include <stdio.h>

int main()
{
int i = 1;
while(i <= 5)

{
printf("%d\n", i);
++i;
}
return 0;
}
12
7
▪Instead of incrementing we can even decrement a loop
counter
void main( )
{
int k = 4 ;
while ( k >=
1)
{
printf ( "decrement
counter”) ;
k= k- 1 ;
}
}

12
8
▪ Q) Write a program to find the largest of N numbers.
▪ Q) Write a program to find the factorial of a number.
▪ Q) Write a program to find the sum of the first N natural
numbers.
▪ Q) Write a program to find xn, where n is an integer number and x
is a nonzero number.
▪ Q) Write a program to find the largest digit in a positive integer.

12
9
Q) Write a program to read a number and find sum of digits
of a numbers.
#include <stdio.h>
void main()
{
int d_N,d_sum=0,temp;
printf("Enter the value of
n"); scanf("%d",&d_N);

while ( d_N > 0 )


{
temp = d_N%10;
d_sum = d_sum +
temp;
d_N = d_N/10;

}
printf("Sum = %d",d_sum);
}
13
0
DO –WHILE
LOOP
▪It is an exit control loop. That is, it evaluates its test expression

at the bottom of the loop after executing its loop body


statement.

▪do -while loop execute at least once even when the test

expression evaluates to false initially.

Syntax
do
{
Statement 1;
………
} while (condition); 13
1
How do...while loop
works?

➢ The body of do...while loop is executed once. Only then, the test
expression
is evaluated.

➢ If the test expression is true, the body of the loop is executed again and
the
test expression is evaluated.

➢ This process goes on until the test expression becomes false.

➢ If the test expression is false, the loop ends.


13
2
Q) Write a program to find sum of first n natural numbers
using do..while ?
#include <stdio.h>

void main()

{
int n,i,sum=0;
printf("Enter the value of n");
scanf("%d",&n);

i=1;
do
{
sum = sum + i;

i++;

}while(i<=n);
printf("Sum =
%d",sum); 13
3
13
4
13
5
Q) Write a program to find the first composite number from a
given set of
N numbers.
Q) Write a program to find the factors of odd numbers from a
given set of
N numbers.
Q) Write a program to print fibonacci numbers less than N, where
N is a
positive integer. ( 0, 1, 1, 2, 3, 5, 8....)
Q) Write a program to find the single digit sum of a given
number. Digit sum
operation is repeated until it result in a sum which is a single
decimal digit.

13
6
FOR
LOOP
▪A for loop is a repetition control structure which allows us to write a

loop
that is executed a specific number of times.

▪The loop enables us to perform n number of steps together in one line.

▪In for loop, a loop variable is used to control the loop.

▪First initialize this loop variable to some value, then check whether

this variable is less than or greater than counter value. If statement


is true, then loop
body is executed and loop variable gets updated . Steps are repeated
till exit condition comes.
13
7
How for loop works?

▪The initialization statement is executed only once.

▪Then, the test expression is evaluated. If the test expression is evaluated

to
false, the for loop is terminated.

▪However, if the test expression is evaluated to true, statements inside

the
body of the for loop are executed, and the increment expression is
incremented.

▪Again the test expression is evaluated.

▪This process goes on until the test expression is false. When


13
8
the test expression is false, the loop terminates.
The syntax of the for
loop is:

for (initialization ; test expression; increment


statement)

// statements inside the body of loop

13
9
▪ Initialization Expression: In this expression we have to initialize the

loop
counter to some value. for example: int i=1;

▪ Test Expression: In this expression we have to test the condition. If the

condition evaluates to true then we will execute the body of loop and go
to update
expression otherwise we will exit from the for loop. For example: i

<= 10;
▪ Increment Expression: After executing loop body this expression

increments/decrements the loop variable by some value. for


example: i++;
14
0
Example 1: for loop
// Print numbers from 1 to
10
#include <stdio.h>

int main()
{ int i;

for (i = 1;
i < 11; +
+i)
{
printf("%
d ", i);
} 14
1
Example 2: for loop
// Program to calculate the sum of first n natural
numbers
// Positive integers 1,2,3...n are known as natural
numbers

#include <stdio.h>

int main()
{
int num, count, sum = 0; printf("Enter
a positive integer: ");
scanf("%d", &num);
// for loop terminates when num is less than
count for(count = 1; count <= num; +
+count)

{
sum += count;
}
} printf("Sum = %d", sum);
return 0; 14
2
for (num=10; num<20;
num=num+1)
for (i=1,j=1;i<10 && j<10; i++, j++)
{
//Statements
}
int num=10; When you have a for loop that ends with a
for (;num<20;num++) semicolon, it means that there is no body
{ //Statements
for the loop. Basically its an empty loop. It
}
can be useful for finding the length of a
for (num=10; string, number of elements in a array, and
num<20; )
so on.
{
//Statements int i;
num++; for (i = 0; s<=n ; ++i);
}
int num=10;
for
(;num<20;)
{
//
Statements
14
num++;
} 2
BREAK AND
CONTINUE
▪The break and continue statement are used to alter the flow of a

STATEMENT
program.
▪Loops are used to execute certain block of statements for n number

of
times until the test condition fails.

▪There will be some situations where, we have to terminate the loop

without executing all the statements.

▪In these situations we use break statement and continue statement.

14
4
break
statement

▪The break statement ends the loop immediately when it is encountered.

▪Its syntax is:

break;
▪The break statement is almost always used with switch-case statement

and
inside the loop.

14
5
How break statement
works?

14
6
▪Example –
break #include
<stdio.h> void
main()

{
int i;
for(i=0;i<5;i++)
{
printf(“%d”,i
); break;

printf(“This will not


appear!”);
}
printf(“\nOnly this will
appear!”);
} 14
7
#include
<stdio.h> int
main() {

int i;
float number,
sum = 0.0;
{
for (i = 1; i
printf("Enter n%d: ", i);
<= 10; ++i)
scanf("%f", &number);
if (number < 0.0)
break;
sum +=

} number;
printf("Sum = %.2f",
sum);
14
} 8
continue statement
▪The continue statement skips the current iteration of the

loop and continues with the next iteration.

▪Its syntax is:

continue;
▪When continue is encountered inside any loop, control automatically

passes to the beginning of the loop

14
9
How continue statement
works?

15
0
▪Example – continue
#include <stdio.h>
void main()

{
int i;
for(i=1;i<20;i++)

{
if(i%2==0)
continue;
printf(“%d
”,i);

}
printf(“\nFinally this
will appear!”);
} 15
1
▪Example –
continue
#include
<stdio.h> void
main()

{
int i,num,f,n;
Scnf(“%d”&n);
{
for(i=0;i<n;i++)
scanf(“%d”,&nu
m); if(num<0)
continue;
for(f=1;num>=1;
num--)
{
f=f*num;
}
printf(“\nFactorial of %d is
%d”,num,f);
}
}

15
2
1. Read a Natural Number and check whether the number is
prime or not 2.Read a Natural Number and check whether the
number is Armstrong or not
3. Program to print half pyramid of numbers 1

2 2
3 3 3
4 4 4 4
5 5 5 5 5
4. Write a program to find the nth fibonacci number.

15
3
Program to print half pyramid
of *
*
* *
* * *
* * * *
* * *
* * for (i
= 1; i <= rows; i++)
{
for (j = 1; j
<= i; j++)
{
printf("* ");
}
printf("\n"); 15
4
Program to print inverted half pyramid
of *
* * * * *
* * * *
* * *
* *
*
for (i = rows; i >= 1; i--)
{
for (j = 1; j <= i; j++)
{
printf("* ");
}
printf("\n");
}
15
5

You might also like