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

EST 102 - Module 2

The document provides an overview of module 2 of an EST 102 C programming course. It covers the basic structure of C programs, including character sets, tokens, identifiers, variables and data types, constants, and input/output operations. It also discusses operators and expressions, including arithmetic, relational, logical, assignment, and bitwise operators as well as operator precedence. Finally, it covers control flow statements such as if statements, switch statements, loops (while, do-while, for), and break and continue statements.

Uploaded by

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

EST 102 - Module 2

The document provides an overview of module 2 of an EST 102 C programming course. It covers the basic structure of C programs, including character sets, tokens, identifiers, variables and data types, constants, and input/output operations. It also discusses operators and expressions, including arithmetic, relational, logical, assignment, and bitwise operators as well as operator precedence. Finally, it covers control flow statements such as if statements, switch statements, loops (while, do-while, for), and break and continue statements.

Uploaded by

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

EST 102 – MODULE 2

PROGRAM BASICS
MODULE 2 - 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, Break and Continue
statements.(Simple programs covering control flow)

2
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

● Developed at Bell Laboratories during 1972-1973.

3
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.
4
▪ A C program is divided into different sections. There are six main sections to a
basic c program. The six sections are,

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

5
STRUCTURE OF A C PROGRAM

6
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\n",d_sum);


return 0;
}
7
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.
8
LANGUAGE

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

9
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

10
Alphabets
▪ C language supports all the alphabets from the English language. Lower and

upper case letters together support 52 alphabets.

▪ Lower case letters - a to z

▪ Upper case letters - A to Z

Digits
▪ C language supports 10 digits which are used to construct numerical values

in C language.

▪ Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

11
Special Symbols
▪ Special Symbols are + - * / % = & % # ~ ! ( ) [ ] { }

_ ^ , ; . < > ? \ | ‘ “ blank space.


▪ Space , tab and newline are called white space

characters

12
13
TOKEN
▪ 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.

14
▪ In a c program tokens are of the following types:

➢ 1. Keywords

➢ 2. Identifiers

➢ 3. Constants

➢ 4. Strings

➢ 5. Special Symbols

➢ 6. Operators

15
Keywords

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.

16
Identifier
▪ 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. Case
-
sensitive
-

Keywords can not be used as identifiers.


17
Identifier

▪ Examples for valid identifiers



A, sum, Sum_of_Numbers, Avg2, _int, FOR

▪ Examples for Invalid identifiers



2to4 - starts with a digit

A-b - Special charater -

▪ Mark, mark, MARK - Represents 3 identifiers.

▪ Use meaningful words as identifiers.

18
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

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

➢ Size varies from one compiler to another.

20
Data Type Qualifiers in C
➢ Data type qualifiers are :


short, long


signed, unsigned

➢ Usage is :

● short int - 2 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 int.
21
Data Type Qualifiers in C
➢ sizeof(short int) <= sizeof (int)

➢ sizeof (int) <= sizeof (long int)

➢ Qualifiers with char

● signed char - value (-128 to +127)

● unsigned char - value ( 0 to 255)

➢ The data type double can also be qualified using long double.

➢ These qualifiers are keywords in C.

22
23
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.

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

25
26
Declaration

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

▪ Examples:

● int number, mark, sum;

● float average;

● char flag;

27
Declaration

▪ 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 = ’ ‘;
28
Constants
▪ 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

29
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 constant can be preceded by a minus (-) sign if desired.



The value of a constant cannot exceed specified minimum and
maximum bounds.


For each type of constant, these bounds will vary from one C compiler
to another. 30
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).

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

▪0 1 743 5280 32767 9999

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

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

● 743 does not begin with 0.

● 05280 Illegal digit (8). 0777.777 Illegal character ( . ).


34
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

35
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)

36
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 to 32767.

( -(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: 52000U

▪ If 2 bytes are used for representing, then the range will be 0 to 216-1.

(0-65535)
37
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.

● However, the U must precede the L. Eg. 12345678UL decimal (unsigned long)
38
● Several unsigned and long integer constants are shown below :

● Constant Number System

● 50000U decimal (unsigned)


● 123456789L decimal (long)
● 123456789UL decimal (unsigned long)
● 0123456L octal (long)
● 07777771U octal (unsigned) hexadecimal
● 0X50000U (unsigned) hexadecimal
● 0XFFFFFUL (unsigned long)

39
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

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

● 1,000.0 Illegal character (, ).


2.34E+10.2 The exponent must be an integer quantity (it cannot contain
a decimal point).


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

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

42
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’ - 65 ’B’ - 66

● ‘a’ - 97 ’b’ - 98

● ‘ ‘ - 32

● ‘0’ - 48

43
String Constant
▪ A string constant consists of any number of consecutive characters

(including none), enclosed in double quotation marks.

▪ Examples :

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


“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 string

constant, as the last character within the string.


44
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).

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

46
Character Escape Seauence

bell (alert) \a

Backspace \b

horizontal tab \t

vertical tab \v

newline (line feed) \n

form feed \f

carriage return \r

quotation mark (") \”

Apostrophe (') \

question mark (?) \?

Backslash (\) \\

Null \0
47
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’.

48
49
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 form.

50
CONSOLE I/O FUNCTIONS CONTD..

51
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)

52
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, and

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

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

expressions.

53
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

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

55
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”, f_sum,f_sum); // 7472.342789 7.472343e+03

▪ printf(%6d”,d_sum);

▪ printf(%2.3f”,f_sum);

56
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 required


formatting information, and arg1,..., argn are arguments that represent the
individual input data items.
57
Reading Input data - scanf()

▪ Arguments are addresses of variables

58
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);

59
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( )

60
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 the

input charater.

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

▪ Common usage is


putchar(character_item)

▪ 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(66) //
B 62
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

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

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

66
Operators in C
▪ Categories of operators :

● Arithmetic operators

● Unary operators

● Relational operators

● Logical operators

● Assignment operators

● Conditional operator

● Bitwise operators

67
Arithmetic Operators in C
▪ Arithmetic operators :

● There are five arithmetic operators in C. They are

Operator Purpose
+ Addition

Sutraction
-
Multiplication
*
Division
/
% Remainder of integer
division
(modulus operator) 68
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).

69
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).

70
Unary Operators in C
▪ Operators that act upon a single operand to produce a new value.

▪ Unary Minus (-)

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

▪ Increment operator (++)

● causes its operand to be increased by 1.

▪ Decrement operator (--)

● causes its operand to be decreased by 1.

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

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

● int a=5;

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

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

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

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

●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
c = a++ + b; printf(“c = %d a=%d”,c,a); c = ++a + b;

// c= 8 a=6
printf(“c = %d a=%d”,c,a);

// c= 10 73
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); // a = 4

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

74
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); // a = 5

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

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

75
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);

76
#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));

}
Output
1
4
4
8
77
Relational Operators:
▪ There are four relational operators in C.
Operator Meaning

▪ < less than

▪ <= less than or equal to

▪ > greater than

▪ >= greater than or equal to


▪ There are two equality operators in C.
Operator Meaning

▪ == equal to

▪ != not equal to

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

▪ For example, 5!=5 will return 0.

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

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

81
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).

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

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

84
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 assign

the value on the right to the variable on the left.

For example: a = 10;


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

initially value stored in a is 8. Then (a -= 6) = 2.

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

initially value stored in a is 6. Then (a /= 2) = 3.

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

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

89
90
▪ 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 01011000.

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

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

93
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\n");

scanf("%d%d",&d_num1,&d_num2);
d_large = d_num1>d_num2 ?d_num1:d_num2;
printf("Largest=%d\n",d_large);

94
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 integer values

1 and 0, respectively

95
Expressions in C
▪ An expression can be :

● A constant


A variable or


Operands connected with operators

▪ Examples


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

mark a+b, a*b, a-b,



a<=b
a/b, a<b,

96
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.
97
Operator Precedence and associativity

98
Operator Precedence and associativity

99
Operator Precedence and associativity
PUMA RELL TAC
Parenthese, dot, arrow
Operator Category Operators Associativity
Unary Operators - ++ -- ! sizeof (type) R->L
&
Arithmetic multiply, divide * / % L->R
and remainder
Arithmetc add and subtract + - L->R

Relational Operators < <= > L->R


>=
Equality Operators == != L->R
Logical and && L->R
Logical or || L->R
Conditional operator ? : R->L
Comma operators
Assignment = += -= *= /= %= R->L 100
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);
101
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.

102
Type Conversions in C

▪ Implicit type conversion :

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

104
Control Structures
CONTROL FLOW
S TATE ME NT

C provides two styles of flow control:


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

105
Branching

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.

106
Syntax – if Statement

if (condition)
{
Block of statements;
}

107
//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_num is less than 20\n" );

}
printf("value of number is : %d\n", d_num);
}

108
Syntax – if else Statement

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

109
#include <stdio.h>
void main()

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

{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}

110
Syntax if….else if….else / Else-if ladder
if (expression)
{
Block of statements;
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
}

111
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");
}
}

112
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;
}

113
/*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 100",n);


return 0;

114
The switch statement
▪ Switch statement in C 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.

▪ If a case match is NOT found, then the default statement is executed, and the control

goes out of the switch block.

115
switch( expression )
{
case value-1:
Block-1;
Break;

case value-2:
Block-2;
Break;

case value-n:
Block-n;
Break;

default:
Block-1;

Break;

}
Statement-x;
116
#include <stdio.h>
int main() {

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

break;

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

break;

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

break;

default:
printf("Out of range");

break;

}
return 0;
} 117
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.

118
119
#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("Even\n");
else
printf("Odd\n");
END:printf("End");
}
120
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 display the result status as defined below
▪ Total Marks - Result
● [80,100] – First class with distinction

[60,80) - First class

[40,60) - Passed

[0,40) - Failed

▪ Using switch-case develop a simple menu driven calculator program.

121
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

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

123
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;
}

124
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).

125
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;
}

126
▪Instead of incrementing we can even decrement a loop counter void
main( )

{
int k = 4 ; while
( k >= 1 )

{
printf ( "decrement counter”) ; k
= k- 1 ;

}
}

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

128
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);
}

129
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);
130
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.

131
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);
}
132
133
134
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.

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

136
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 update expression is updated.

▪ Again the test expression is evaluated.

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

expression is false, the loop terminates.

137
The syntax of the for loop is:

for (initialization ; test expression; update statement)

// statements inside the body of loop

138
▪ 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;
▪ Update Expression: After executing loop body this expression

increments/decrements the loop variable by some value. for example: i++;

139
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);
}
return 0;
}
140
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;

}
141
for (num=10; num<20; num=num+1)
{ for (i=1,j=1;i<10 && j<10; i++, j++)
//Statements
}
int num=10;
for (;num<20;num++) When you have a for loop that ends with a
{ //Statements semicolon, it means that there is no body for the
} loop. Basically its an empty loop. It can be useful
for finding the length of a string, number of
for (num=10; num<20; ) elements in a array, and so on.
{ int i;
//Statements
num++;
for (i = 0; s<=n ; ++i);
}
int num=10; for
(;num<20;)

{
//Statements
num++;
142
}
BREAK AND CONTINUE
STATEMENT
▪ The break and continue statement are used to alter the flow of a 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.

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

144
How break statement works?

145
▪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!”);
}

146
#include <stdio.h>
int main() {

int i;
float number, sum = 0.0;
for (i = 1; i <= 10; ++i)

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

}
printf("Sum = %.2f", sum);
}
147
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

148
How continue statement works?

149
▪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!”);
}

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

{
int i,num,f,n;
Scnf(“%d”&n);
for(i=0;i<n;i++)

{
scanf(“%d”,&num);
if(num<0)
continue;
for(f=1;num>=1; num--)

{
f=f*num;
}
printf(“\nFactorial of %d is %d”,num,f);
}
}

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

152
Program to print half pyramid of *
*
* *
* * *
* * * *
* * * * *
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= i; j++)
{
printf("* ");
}
printf("\n");
}

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

You might also like