[go: up one dir, main page]

0% found this document useful (0 votes)
34 views136 pages

Unit II

Uploaded by

vamikaguntur
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)
34 views136 pages

Unit II

Uploaded by

vamikaguntur
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/ 136

Introduction to Computer Science and Programming

Using C

( B.Tech-CSE-M & R)

Unit- II

AYUSH BIJOURA, ASSISTANT PROFESSOR


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
SRM UNIVERSITY AP
1
Learning Objectives

C PROGRAMMING BASICS:
Structure of a C program, identifiers Basic data types and sizes. Constants,
Variables Arithmetic, relational and logical operators, increment and
decrement operator’s Conditional operator, assignment operator, expressions
Type conversions, Conditional Expressions Precedence andorder of evaluation,
Sample Programs.

SELECTION & DECISION MAKING: if-else, null else, nested if,


examples, multi-way selection: switch, else-if, examples.

ITERATION: Loops - while, do-while and for, break, continue,


initialization and updating, event and counter controlled loops and examples.

2
Structure of a C program

Documentation:
It specifies
• the description of the program
• the name of the program
• the creation date and time of the program.
It is specified at the start of the program in the form of
comments.
// description, name of the program, programmer name,
date, time etc.
or
/*
description, name of the program, programmer name,
date, time etc.
3
*/
Structure of a C program

Preprocessor Section:
All the header files of the program will be declared in the preprocessor section of the
program.
Header files help us to access other’s improved code into our code.
A copy of these multiple files is inserted into our program before the process of
compilation.

#include:
An include directive tells the pre-processor to include the contents of the
specified file at the point in the program.
Path names must either be enclosed by double quotes or angle brackets.

Example:
#include<stdio.h>
#include<math.h> 4
Structure of a C program

Some of C Header files:


• <stdio.h> (Standard input-output header) Used to perform input
and output operations in C like scanf() and printf().
• <string.h> (String header) Perform string manipulation operations
like strlen and strcpy.
• <conio.h> (Console input-output header) Perform console input and
console output operations like clrscr() to clear the screen and
getch() to get the character from the keyboard.
• <stdlib.h> (Standard library header) Perform standard utility
functions like dynamic memory allocation, using functions such as
malloc() and calloc().
• <math.h> (Math header ) Perform mathematical operations like
sqrt() and pow(). To obtain the square root and the power of a
number respectively.
• <ctype.h>(Character type header) Perform character type functions
like isaplha() and isdigit(). To find whether the given character is an
5
alphabet or a digit respectively.
Structure of a C program

Definition:
Preprocessors are the programs that process our source code before the
process of compilation.
Preprocessor directives start with the ‘#’ symbol. The #define
preprocessor is used to create a constant throughout the program.
Whenever this name is encountered by the compiler, it is replaced by the
actual piece of defined code.
#define:
ANSI C allows the declaration of constants. This directive is used to tell
the pre-processor to perform a search-and-replace operation.

Example:
#define PI 3.14159
#define Tax-rate 0.0735
6
Structure of a C program

Global Declaration:
• The global declaration section contains global variables, function
declaration, and static variables.
• Variables and functions which are declared in this scope can be used
anywhere in the program.
• Creates the global variable before main().
Example:
#include<stdio.h>
int a=50, b=40;
int main()
{
printf("a = %d and b=%d",a,b);
}

7
Structure of a C program

main() Function:
• Every C program must have a main function which is the entry point
of the C program.
• Every C program must have one and only one main function.
• Operations like declaration and execution are performed inside the
curly braces of the main program.
• The return type of the main() function can be int as well as void too.
• void() main tells the compiler that the program will not return any
value.
• The int main() tells the compiler that the program will return an
integer value.
Example:
void main()
or
int main()
8
Structure of a C program

Sub Programs:
User-defined functions are called in this section of the
program.
The control of the program is shifted to the called function
whenever they are called from the main or outside the main()
function.
These are specified as per the requirements of the
programmer.
Example:
int sum(int x, int y)
{
return x+y;
} 9
Structure of a C program

10
Structure of a C program

/*This program converts the given miles into kilometers */


#include<stdio.h> // Link
#define KM_PER_M 1.609 // Definition of Symbolic constants
float mToKm(float); // Global declaration and initialization
void main()
{
float m = 3.5; // local declaration and initialization
float k; // local declaration
k = mToKm(m); // Executable part
printf(“%f”,k); // Executable part
}
// Sub program section
float mToKm(float m)
{
float k;
k = m*1.609;
return k;
}
11
Tokens in C
Tokens in C is the most important element to be used in creating a
program in C. We can define the token as the smallest individual element
in C. For `example, we cannot create a sentence without using words;
similarly, we cannot create a program in C without using tokens in C.
Therefore, we can say that tokens in C is the building block or the basic
component for creating a program in C language.

12
Keywords

Keywords in C can be defined as the pre-defined or the reserved


words having its own importance, and each keyword has its own
functionality. Since keywords are the pre-defined words used by the
compiler, so they cannot be used as the variable names.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
13
Keywords

Example:
#include<stdio.h>
int main()
{
float a, b;
printf("Showing how keywords are used.");
return 0;
}
• float and return are keywords.
• float keyword is used to declare variables.
• return is used to return an integer type value in this program.

14
Identifiers

Identifiers in C are used for naming variables, functions, arrays,


structures, etc. Identifiers in C are the user-defined words. It can be
composed of uppercase letters, lowercase letters, underscore, or digits, but
the starting letter should be either an underscore or an alphabet.
Identifiers cannot be used as keywords.
Example:
int amount;
double totalbalance;
In the above example, amount and totalbalance are
identifiers, and int and double are keywords.

15
Learning Objectives

Rules for naming identifiers:


• An identifier can only have alphanumeric characters (a-z , A-Z , 0-9)
(i.e. letters and digits) and underscore( _ ) symbol.
• Identifier names must be unique.
• The first character must be an alphabet or underscore.
• You cannot use a keyword as an identifier.
• It must not contain white spaces.
• Identifiers are case-sensitive.

16
Keyword vs Identifier

Keyword Identifier
Keywords are predefined and specific A particular name generated by the
reserved words, which hold special programmer to define a variable,
meaning. Keywords help in defining any structure, class, or function is called an
statement in the program. identifier.

A keyword begins with lowercase. In the identifier, the first character may
begin with uppercase, lowercase or
underscores.
It defines the type of entity. It classifies the name of the entity.
It can only have alphabetical characters. It can have numbers, alphabetical
characters, and underscores.
It should be lowercase. It can be both upper and lowercase.
It helps in defining a particular property It helps in locating the name of the entity.
that subsists in a computer language.

double, int, auto, char, break, and more Test, count1, high_speed, etc are examples
are examples of keywords. of identifiers.
17
Constants

Constants in C
A constant is a value assigned to the variable which will remain the same
throughout the program, i.e., the constant value cannot be changed.
There are two ways of declaring constant:
•Using const keyword
•Using #define pre-processor
Constant Example
Integer constant 10, 11, 34, etc.
Floating-point constant 45.6, 67.8, 11.2, etc.
Octal constant 011, 088, 022, etc.
Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.
Character constant 'a', 'b', 'c', etc.
String constant "java", "c++", ".net", etc. 18
Constants

Putting const either before or after the


type is possible.
int const SIDE = 10;
or
const int SIDE = 10;

Types of constants
1. Numeric Constants
• Integer Constants
• Real Constants
2. Character Constants
• Single Character Constants
• String Constants
• Backslash Character Constants
19
Strings

Strings in C are always represented as an array of characters having null


character '\0' at the end of the string. This null character denotes the end of the
string. Strings in C are enclosed within double quotes, while characters are
enclosed within single characters.

Now, we describe the strings in different ways:


char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the
'a' array.
char a[] = "javatpoint"; // The compiler allocates the memory at the run
time.
char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented
in the form of characters.

20
Variables

• Variable primary purpose is to store data in memory for later use.


• Constants do not change during the program execution; the value of a
variable may change during execution.
• Declaring a variable in C, is asking the operating system to reserve a
piece of memory with that variable name.
Different types of variables are
1. char - Typically a single octet(one byte). It is an integer type.
2. int - The most natural size of integer for the machine.
3. float - A single-precision floating point value.
4. double - A double-precision floating point value.
5. void - Represents the absence of type.
Variable syntax1:
type variable_list;
• type must be a valid C data type
• variable_list may consist of one or more identifier names separated by
commas 21
Variables

❑ Types of Variables in C
local variable
global variable
static variable

22
Variables

❑ Local Variable

A variable that is declared inside the function or block is


called a local variable.
#include<stdio.h> void function1(){
void main() int x=10;//local variable
{ }
int x=50, y=40;
printf("x = %d and y=%d",x, y);
}

23
Variables

❑ Advantages:
• The same name of a local variable can be used in different
functions as it is only recognized by the function in which it is
declared.
• Local variables use memory only for the limited time when the
function is executed; after that same memory location can be
reused.

❑ Disadvantages:
• The scope of the local variable is limited to its function only and
cannot be used by other functions.
• Data sharing by the local variable is not allowed.

24
Variables

❑ Global Variable
A variable that is declared outside the function or block is called a
global variable. Any function can change the value of the global
variable. It is available to all the functions.
#include<stdio.h>
int a=50, b=40; // global variable
void main()
{
printf("a = %d and b=%d",a,b);
}

25
Variables

❑ Advantages:
•Global variables can be accessed by all the functions present in the
program.
•Only a single declaration is required.
•Very useful if all the functions are accessing the same data.

❑ Disadvantages:

•The value of a global variable can be changed accidentally as it can


be used by any function in the program.
•If we use a large number of global variables, then there is a high
chance of error generation in the program.

26
Data Types

Variables in C are associated with the data type. Each data type requires
an amount of memory and performs specific operations.
The data type in a programming language is the collection of data with
values having fixed meanings and characteristics. Some of them are an
integer, floating points, characters, etc. Usually, programming languages
specify the range values for a given data type.
C data types are used for
Identify the type of a variable when it is declared.
Identify the type of return value of a function.
Identify the type of parameter expected by a function.
The syntax of the data type is as follows:
27
data_type variable_name;
Data Types

28
Learning Objectives

1. Integer (int): Refers to positive and negative whole numbers (without decimal),
such as 10, 12, 65, 3400, etc.
2. Character (char): Refers to all the ASCII character sets within single quotes
such as ‘a’, ‘A’, etc.
3. Floating-point (float): Refers to all the real number values or decimal points,
such as 3.14, 10.09, 5.34, etc. The precision of up to 6 digits.
4. Double (double): Used when the range exceeds the numeric values that do not
come under either floating-point or integer data type. The precision of up to 10
digits.
5. Void (void): As the name suggests, it holds no value and is generally used for
specifying the type of function or what it returns. If the function has a void type,
it means that the function will not return any value.
Modifiers are C keywords that modify the meaning of fundamental data types. It
indicates how much memory will be allocated to a variable. To adjust the memory
allocated for a variable, modifiers are prefixed with fundamental data types. C
Programming Language has four data type modifiers:
• long
• short 29
Data Types

30
Data Types

❑ User Defined Data Types


The user-defined data types are defined by the user himself. The data
types that are derived from the primitive or built-in datatypes are
referred to as Derived Data Types. They are function, array, pointer,
and so on.
❑ Derived Types

The data types that are derived from the primitive or built-in datatypes
are referred to as Derived Data Types.

31
Data Types

Example:
#include <stdio.h> Output:
int main() { Integer datatype : 10
// datatypes Character datatype : S
int a = 10; Float datatype : 2.880000
char b = 'S'; Double Float datatype :
float c = 2.88; 28.888000
double d = 28.888;
printf("Integer datatype :
%d",a);
printf("Character datatype :
%c",b);
printf("Float datatype :
%f",c);
printf("Double Float datatype
: %lf",d); 32
Data Types

#include <stdio.h>
int main() {
int numbers[5];
// Declares an integer array with a size of 5 ele
ments
// Assign values to the array elements
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Display the values stored in the array
printf("Values in the array: ");
for (int i = 0; i < 5; i++) { Output:
printf("%d ", numbers[i]); Values in the array: 10 20
} 30 40 50
printf("\n");
return 0;
33
}
Data Types

Enumeration (or enum) is a user-defined data type in C. It is mainly used


to assign names to integral constants, the names make a program easy to
read and maintain.

enum flag {const1, const2, ..., constN};

Example:

#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
34
}
Data Types

#include<stdio.h>
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep,
Oct, Nov, Dec};
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
return 0;
}

Output: 0 1 2 3 4 5 6 7 8 9 10 11
35
Data Types

36
Operators in C
❑ What is an
AnOperator?
operator is a symbol that tells the compiler to
perform a certain operation (arithmetic,
comparison, etc.) using the values provided along
with the operator.

For example, ‘+’ is an operator used for addition, as


shown below:
C= A+B

Here, ‘+’ is the operator known as the addition 37


Operators in C

38
Operators in C

❑ Unary Operators:
Operators that operate or work with a single operand
are unary operators. For example: Increment(++) and
Decrement(–) Operators.

Ex: int a=10; Printf(“++a = %d”, ++a)

Output: 11;

39
Operators in C

❑ Binary Operators:
Operators that operate or work with two operands
are binary operators. For example: Addition(+),
Subtraction(-), multiplication(*), Division(/) operators

Ex: int a=10,b=20; Printf(“a+b=%d”, a+b)

Output: 30;

40
Arithmetic Operators
Meaning of
❑ Arithmetic Operator
Operator

Operator:
An arithmetic operator
+
addition or
unary plus

performs mathematical subtraction


- or unary
operations such as addition, minus
subtraction, multiplication,
* multiplication
division etc on numerical
/ division
values (constants and
variables). remainder
after division
%
(modulo
division)
41
Arithmetic Operators
// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c; Output:
c = a+b; a+b = 13
printf("a+b = %d \n",c);
c = a-b; a-b = 5
printf("a-b = %d \n",c); a*b = 36
c = a*b;
printf("a*b = %d \n",c); a/b = 2
c = a/b;
printf("a/b = %d \n",c);
Remainder when
c = a%b; a divided by b=1
printf("Remainder when a divided by b = %d
\n",c);
return 0;
}
42
Relational Operators

❑ Relational
A Operators:
relational operator checks the relationship between
two operands. If the relation is true, it returns 1; if the
relation is false, it returns value 0.

43
Relational Operators

Meaning Meaning
Operator of Example Operator of Example
Operator operator

5 == 3 is 5 != 3 is
Not
== Equal to evaluated != evaluat
equal to
to 0 ed to 1

5 > 3 is Greater 5 >= 3 is


Greater
> evaluated >= than or evaluat
than
to 1 equal to ed to 1

5 < 3 is Less 5 <= 3 is


< Less than evaluated <= than or evaluat
to 0 equal to ed to 0
44
Relational Operators
#include <stdio.h>
int main() Output:
{ 5 == 5 is 1
int a = 5, b = 5, c = 10; 5 == 10 is 0
printf("%d == %d is %d \n", a, b, a == b);
5 > 5 is 0
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b); 5 > 10 is 0
printf("%d > %d is %d \n", a, c, a > c); 5 < 5 is 0
printf("%d < %d is %d \n", a, b, a < b); 5 < 10 is 1
printf("%d < %d is %d \n", a, c, a < c); 5 != 5 is 0
printf("%d != %d is %d \n", a, b, a != b);
5 != 10 is 1
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b); 5 >= 5 is 1
printf("%d >= %d is %d \n", a, c, a >= c); 5 >= 10 is 0
printf("%d <= %d is %d \n", a, b, a <= b); 5 <= 5 is 1
printf("%d <= %d is %d \n", a, c, a <= c); 5 <= 10 is 1
return 0;
45
}
Logical operators

❑ Logical Operators
An expression containing logical operator returns
either 0 or 1 depending upon whether expression
results true or false. Logical operators are
commonly used in decision making in C
programming

46
Logical operators

Operator Meaning Example

If c = 5 and d = 2
Logical AND. True
then, expression
&& only if all operands
((c==5) && (d>5))
are true
equals to 0.

If c = 5 and d = 2
Logical OR. True
then, expression
|| only if either one
((c==5) || (d>5))
operand is true
equals to 1.

Logical NOT. True If c = 5 then,


! only if the operand expression !(c==5)
is 0 equals to 0.

47
Logical operators

#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result; Output:
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result); (a == b) && (c > b)
result = (a == b) && (c < b); is 1
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b); (a == b) && (c < b)
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
is 0
printf("(a != b) || (c < b) is %d \n", result); (a == b) || (c < b) is
result = !(a != b);
printf("!(a != b) is %d \n", result); 1
result = !(a == b); (a != b) || (c < b) is
printf("!(a == b) is %d \n", result);
return 0; 0
} !(a != b) is 1 !(a ==48
Logical operators
❑ Explanation of logical operator program
(a == b) && (c > 5) evaluates to 1 because both operands (a ==
b) and (c > b) is 1 (true).
(a == b) && (c < b) evaluates to 0 because operand (c < b) is 0
(false).
(a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
(a != b) || (c < b) evaluates to 0 because both operand (a !=
b) and (c < b) are 0 (false).
!(a != b) evaluates to 1 because operand (a != b) is 0 (false).
Hence, !(a != b) is 1 (true).
!(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a
== b) is 0 (false).
49
Bitwise operators

❑ Bitwise Operators
During computation, mathematical operations like:
addition, subtraction, multiplication, division, etc
are converted to bit-level which makes processing
faster and saves power. Bitwise operators are used
in C programming to perform bit-level operations.

50
Bitwise operators

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

51
Bitwise operators

❑ Bitwise AND Operator & - Bitwise OR


Operator |
The output of bitwise AND is 1 if the
corresponding bits of two operands is 1. If
either bit of an operand is 0, the result of
corresponding bit is evaluated to 0.
The output of bitwise OR is 1 if at least one
corresponding bit of two operands is 1. In C
Programming, bitwise OR operator is denoted
by |
52
Bitwise operators

❑ Bitwise AND
12 = 00001100 (In #include <stdio.h>
Binary) int main()
{
25 = 00011001 (In
int a = 12, b = 25;
Binary) printf("Output = %d",
Bit Operation of 12 and a & b);
25 return 0;
00001100 }
& Output = 8
00011001
________ 53
Bitwise operators

❑ Bitwise OR
12 = 00001100 (In Binary) #include <stdio.h>
25 = 00011001 (In Binary) int main()
Bitwise OR Operation of 12 {
and 25
00001100 int a = 12, b = 25;
| printf("Output =
00011001 %d", a | b);
________ return 0;
00011101 = 29 (In decimal) }
Output = 29
54
Bitwise operators

❑ Bitwise XOR (exclusive OR) Operator ^


The result of bitwise XOR operator is 1 if the
corresponding bits of two operands are
opposite. It is denoted by ^.
12 = 00001100 (In Binary) #include <stdio.h>
25 = 00011001 (In Binary) int main()
{
Bitwise XOR Operation of 12 int a = 12, b = 25;
and 25 printf("Output = %d", a ^
00001100 b);
^ return 0;
00011001 }
________ Output = 21
55
00010101 = 21 (In decimal)
Bitwise operators

❑ Shift Operators
There are two shift operators in C
programming:
•Right shift operator
•LeftShift
Right shift operator.
Operator:
Right shift operator shifts all bits towards right by certain
number of specified bits. It is denoted by >>.
Left Shift Operator:
Left shift operator shifts all bits towards left by a certain number of
specified bits. The bit positions that have been vacated by the left shift
operator are filled with 0. The symbol of the left shift operator is <<.
56
Bitwise operators

•The left operand specifies the value to be shifted and the right
operand specifies the number of positions that the bits in the
value have to be shifted.

a = 00010000
b=2
a << b = 01000000
a >> b = 00000100

57
Bitwise operators

#include <stdio.h> 212 = 11010100 (In binary)


int main() 212 >> 2 = 00110101 (In binary)
{ [Right shift by two bits]
int num=212, i;
212 >> 0 = 11010100 (No Shift)
for (i = 0; i <= 2; ++i)
{
printf("Right shift by %d: %d\n", i,
212 = 11010100 (In binary)
num >> i);
} 212<<2 = 1101010000 (In binary)
printf("\n"); [Left shift by one bit]
for (i = 0; i <= 2; ++i)
{ Output:
printf("Left shift by %d: %d\n", i, Right Shift by 0: 212
num << i); Right Shift by 1: 106
} Right Shift by 2: 53
return 0; Left Shift by 0: 212
} Left Shift by 1: 424
Left Shift by 2: 848 58
Assignment operators

❑ Assignment Operators
An assignment operator is used for assigning a value
to a variable. The most common assignment operator
is =
Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b
59
Assignment operators
#include <stdio.h>
int main()
{
int a = 5, c; Output:
c = a;
printf("c = %d\n", c);
c=5
c += a; c = 10
printf("c = %d\n", c); c=5
c -= a;
printf("c = %d\n", c);
c = 25
c *= a; c=5
printf("c = %d\n", c); c=0
c /= a;
printf("c = %d\n", c);
c %= a;
printf("c = %d\n", c);
return 0;
}
60
Conditional operators

The conditional operator is also known as a ternary


operator. The conditional statements are the
decision-making statements which depends upon the
output of the expression. It is represented by two
symbols, i.e., '?' and ':'.
1.Expression1? expression2: expres
sion3;

61
Conditional operators

#include <stdio.h>
int main()
{
Output:
int age; Enter your age17
printf("Enter your age"); not eligible for
scanf("%d",&age); voting
(age>=18)? (printf("eligible
for voting")) : (printf("not eli
gible for voting"));
return 0;
}
62
Ooperator Precedence

Highest on top
The concept of operator
++ -- (Postfix)
precedence in C helps in
++ -- (Prefix)
determining which operators
* / %
will be given priority when
+ -
there are multiple operators in
<< >>
the expression.
< >

Result?? &
|
&&
||

63
Ooperator Precedence
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
+ - ! ~ ++ - -
Unary Right to left
(type)* & sizeof
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
= += -= *= /=
Assignment %=>>= <<= &= ^= Right to left
|=
Comma , Left to right 64
Ooperator Precedence

❑ Let's understand through an example.


6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)

Evaluation of expression Description of each operation


6*2/( 2+1 * 2/3 +6) +8 * (8/4) An expression is given.
6*2/(2+2/3 + 6) + 8 * (8/4) 2 is multiplied by 1, giving value 2.
6*2/(2+0+6) + 8 * (8/4) 2 is divided by 3, giving value 0.
6*2/ 8+ 8 * (8/4) 2 is added to 6, giving value 8.
6*2/8 + 8 * 2 8 is divided by 4, giving value 2.
12/8 +8 * 2 6 is multiplied by 2, giving value 12.
1+8*2 12 is divided by 8, giving value 1.
1 + 16 8 is multiplied by 2, giving value 16.
17 1 is added to 16, giving value 17.
65
Ooperator Precedence

#include <stdio.h>
main() {
int a = 20;
int b = 10; Output:
int c = 15;
int d = 5;
Value of (a + b) * c / d is :
int e; 90
e = (a + b) * c / d; Value of ((a + b) * c) / d is
printf("Value of (a + b) * c / d is : : 90
%d\n", e );
Value of (a + b) * (c / d) is
e = ((a + b) * c) / d;
printf("Value of ((a + b) * c) / d is : %d\n" : 90
, e ); Value of a + (b * c) / d is :
e = (a + b) * (c / d); 50
printf("Value of (a + b) * (c / d) is :
%d\n", e );
e = a + (b * c) / d;
printf("Value of a + (b * c) / d is : %d\n" 66
, e );
Ooperator Precedence

67
Ooperator Precedence

❑ Let's understand through an example.

68
Ooperator Precedence

❑ Let's understand through an example.

69
Expressions

❑ Expressions in C?
Expressions are the combination of variables, operands, and
operators. The result would be stored in the variable once the
expressions are processed based on the operator's precedence.

❑ Example:z = a+b-(a*c)

70
Expressions

❑ Types of Expressions
Arithmetic expressions
Relational expressions
Logical expressions
Conditional expressions

71
Expressions

Arithmetic expressions: The arithmetic expression is evaluated in


specific order considering the operator's precedence, and the result of
an expression will be based on the type of variable.

Arithmetic expressions: a=2,b=3, c=4 z = a + b - (a*c) z =


2+3-(2*4) -?
#include <stdio.h>
void main() Output:
{
int a=2,b=3,c=4,z; -3
z=a+b-(a*c);
printf("Result=
%d",z);
} 72
Expressions

Relational Expressions: Relational operators >, <, ==,!= etc


are used to compare 2 operands. Relational expressions consisting of
operands, variables, operators, and the result after evaluation would
be either true or false.

Ex - Relational Expressions: a=5 b=4 c=3 z = a+b*c >


a*b+c z= ?
#include <stdio.h>
void main() Output:
{
????? ??????
}

73
Expressions

Logical Expressions: Relational expressions and


arithmetic expressions are connected with the logical
operators, and the result after an evaluation is stored in
the variable, which is either true or false.
Ex - Logical Expressions: a=5 b=4 c=3 z=(a+b)>c &&
a<b z=?
#include <stdio.h>
void main() Output:
{
????? ??????
}
74
Expressions

Conditional Expressions: A conditional expression is


an expression that returns 1 if the condition is true
otherwise 0. A conditional operator is also known as a
ternary operator.
Ex-Conditional Expressions: a=5, b=3, c=1 z = (a * b) < c ? 1 : 0
z=?
#include <stdio.h>
void main() Output:
{
????? ??????
}
75
Type Conversion

C provides the facility, where the data type of one operand is


converted into the data type of another operand. This is known as
type conversion.

76
Type Conversion

❑ Implicit type conversion (Automatic): The type conversion is


the process of converting a data value from one data type to
another data type automatically by the compiler. The implicit
type conversion is automatically performed by the compiler.

❑ Explicit type conversion (Type casting): Explicit type


conversion rules out the use of a compiler for converting one
data type to another instead the user explicitly defines within the
program the data type of the operands in the expression.

Syntax:
(datatype) expression
77
Type Conversion
❑ Implicit type conversion
#include<stdio.h>
Example
#include<conio.h>
void main(){ Output:
int i = 95 ; i value is 90
float x = 90.99 ; x value is
char ch = 'A' ; 90.000000
i=x; i value is 65
printf("i value is %d\n",i);
x=i;
printf("x value is %f\n",x);
i = ch ;
printf("i value is %d\n",i);
} 78
Type Conversion

#include <stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c Output:
// y implicitly converted to
int. ASCII
x = 107, z =
// value of 'a' is 97 108.000000
x = x + y;
// x is implicitly converted to
float
float z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0; 79
Type Conversion
❑ Explicit type conversion
Example
#include<stdio.h>
int main()
{
Output:
double x = 1.2;
sum = 2
// Explicit conversion from
double to int
int sum = (int)x + 1;
printf("sum = %d", sum);
return 0;
}
80
SELECTION & DECISION
MAKING
❑ Conditional Statements
A program is a set of statements which are normally executed
sequentially in the order in which they appear. This happens when no
options or no repetitions of certain calculations are necessary. However,
in practice, we have a number of situations where we may have to
change the order of execution of statements based on certain conditions,
or repeat a group of statements until certain specified conditions are
met. This involves a kind of decision making to see whether a particular
condition has occurred or not and then direct the computer to execute
certain statements accordingly.
C language possesses such decision- making capabilities by supporting
the following statements.
1) if statements
2) switch statements
3) Conditional operator statement 81
SELECTION & DECISION
MAKING
These statements are popularly known as decision-making
statements. Since these ‘control’ the flow of execution, they are
also known as control statements.
Program Control Structure: The structure of the program
which decides the order of program statements execution is
called ‘control structure’. There are three types of control
structures.
− Sequence: In this control structure, the instructions are
executed linearly from top to bottom
− Selection: This control structure makes decision according to
some predefined condition.
82
− Iteration: This control structure executes certain instructions
SELECTION & DECISION
MAKING
❑ Simple-if Statement:
The if statement is a decision making statement. It is used to control the
flow of execution of the statements and also used to test logically whether
the condition is true or false. It is always used in conjunction with
condition. If the condition is true, then the True statements are executed.
The 'True statements' may be a single statement or group of statements. If
the condition is false then the true statements are not executed, instead the
program skip past it. The condition is given
1. if (bank byisthe
balance relational operator like
zero)
==,! =, <=, >=, etc. Borrow money
2. if(room is dark)
Put on lights
3 .if(code is M)
Person is male
4 .if(age is more then 55 )
Person is retired 83
SELECTION & DECISION
MAKING
1. Write a program to determine
whether a person is eligible to vote
#include<stdio.h>
Output:
#include<conio.h> Enter the age : 19
int main() You are eligible to
{ vote
int age;
printf("Enter the age : ");
scanf("%d",&age);
if(age>=18)
{
printf("You are eligible to vote");
}
getch();
return 0;
} 84
SELECTION & DECISION
MAKING
1. Write a program to determine the character entered by the user
#include<stdio.h>
Output:
#include<ctype.h>
Enter any key : s
#include<conio.h> The User has entered a character
int main()
{
char ch;
printf("Enter any key : ");
scanf("%c",&ch);
if(isalpha(ch)>0)
printf("\n The User has entered a character");
if(isdigit(ch)>0)
printf("\nThe user has entered a digit");
if(ispunct(ch)>0)
printf("\nThe user has entered a punctuation mark..");
if(isspace(ch)>0)
printf("\nThe user has entered a white space character");
}
85
SELECTION & DECISION MAKING

❑ If-else statement
The if..else statement is an extension of the simple if statement. It is
basically two way decision making statement and always used in
conjunction with condition. It is used to control the flow of execution and
also used to carry out the logical test and then pick one of the two
possible actions depending on the logical test.

After it has been evaluated, if its value is true, statement1 is executed, otherwise
statement2 is executed.
86
Note : it's impossible for both statements to be executed in the same evaluation.
SELECTION & DECISION
MAKING
1. Write a program to find the largest of two
numbers
#include<stdio.h>
int main()
{ Output:
int a,b,large; Enter the values
printf("\nEnter the values of a and b : "); of a and b : 12 13

scanf("%d%d",&a,&b); Large = 13
if(a>b)
large=a;
else
large=b;
printf("\n Large = %d",large);
}
87
SELECTION & DECISION
MAKING
1. Write a program to find whether the
given number is even or odd
#include<stdio.h>
int main()
Output:
{
int num;
printf("Enter any number : ");
??????
scanf("%d",&num);
if(num%2==0)
printf("\n %d is an even number
",num);
else
printf("\n %d is an odd number
",num);
88
}
SELECTION & DECISION
MAKING
❑ Write a program to enter a character and then
determine whether it is a vowel or not?

Output:

??????
❑ Write a program to find whether the given year is a leap
year or not
Output:

??????
89
SELECTION & DECISION
MAKING
❑ Nested If-Else Statements
When a series of if. Else statements are occurred in a program, we can write
an entire if..else statement in another if. else statement called nesting. When
an if else included with in if.else is known as a nested if statements.

There is no limit to how many levels can be nested, but if there are more than
three, they can be difficult to read.

90
SELECTION & DECISION
MAKING

Output:

??????

91
SELECTION & DECISION
MAKING
To 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; Output:
printf("Enter a number:");
scanf("%d",&n);
if(n<100)
??????
{
printf("%d is less than 100",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;
} 92
SELECTION & DECISION
MAKING
❑ Write a program to given Number is even or odd and
Negative or zero.

Output:

??????

93
SELECTION & DECISION
MAKING
❑ Multi-way Selection
In addition to two-way selection, most programming languages provide
another selection concept known as multiway selection. Multiway selection
chooses among several alternatives. C has two different ways to implement
multiway selection: the switch statement and else-if construction.

❑ The if…else Ladder


There is another way of putting ifs together when multipath decisions are
involved. A multipath decision is a chain of ifs in which the statement
associated with each else is an if. The conditions are evaluated from top
downwards.
As soon as a true condition is found, the statement associated with it is
executed and the control is transferred to the statement x.
When all the conditions become false, then the final else containing the94
default statement will be executed.
SELECTION & DECISION
MAKING

95
SELECTION & DECISION MAKING

❑ /* Program that reads marks in 3 subjects, calculate


average marks and assigns grade as per following
specifications */

Marks Grade
>=90 A
75-89 B
60-74 C
50-59 D
< 50 F

96
SELECTION & DECISION MAKING

Output:

??????

97
SELECTION & DECISION MAKING

#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int day; int day;
printf("Enter day number: "); printf("Enter day number: ");
scanf("%d", &day); scanf("%d", &day);
if(day==1) if(day==1)
{ {
printf("SUNDAY."); printf("SUNDAY.");
} }
else if(day==2) else if(day==2)
{ {
printf("MONDAY."); printf("MONDAY.");
} }
else if(day==3) else if(day==3)
{ {
printf("TUESDAY."); printf("TUESDAY.");
} }
else if(day==4) else if(day==4)
{ {
printf("WEDNESDAY."); printf("WEDNESDAY.");
} }

98
SELECTION & DECISION
MAKING
❑ The Switch Statement
The switch statement is used to pick up or executes a particular group of
statements from several available groups of statements. It allows us to
make a decision from the number of choices. It is a multi-way decision
statement, it tests the value of the variable or expression against a list of
case values and when a match is found, a block of statements associated
with that case is executed.

99
SELECTION & DECISION
MAKING

100
SELECTION & DECISION
MAKING
#include <stdio.h>
int main()
{
char gender; Output:
printf("Enter Gender Enter Gender
code:(M/F)"); code:(M/F)F
scanf("%c",&gender); Female
switch(gender)
{
case 'M':printf("Male");
break;
case 'F':printf("Female");
break;
default:printf("Wrong 101
SELECTION & DECISION
MAKING
1. Program to print Today's
name of the Day by using
switch case statement.

Output:
Enter a Number : 1
Today is Monday

102
SELECTION & DECISION
MAKING
1. Write a program in C
which is menu driven
program to compute
the area of the various
geometrical shape

Output:
1.Area of circle
2.Area of rectangle
3.Area of triangle
4.Area of Square
Enter your choice : 4

Enter the Length of Side : 4


The area is : 16.000000
103
ITERATION

❑ Loops
The loop is defined as a block of statements which are repeatedly executed for a
certain number of times. There are two types of loop statements available: Those
loops which checks the test condition at the entry level itself, and the other checks
test condition at the exit level. The loop in a program consists of two parts, one is
the body of the loop and another is the control statement. The control statement is
used to test the condition and then directs the repeated execution of the
statements in the body of the loop.

104
ITERATION
❑ PRETEST AND POST-TEST
LOOPS
In a pretest loop, the condition is checked before we start and at the
beginning of each iteration. If the condition is true, we execute the code, if
the condition is false, we terminate the loop.
In the post-test loop, we always execute the action at least once. The loop
control expression is then tested. If the expression is true, the loop
repeats, if the expression is false, the loop terminates.

105
ITERATION

❑ Any looping statement would include.


1. Initialization of a condition variable.
2. Test the control statement.
3. Executing the body of the loop depending on the condition.
4. Updating the variable.

❑ There available loop structures available in ‘C’ is –

106
ITERATION

❑ The While Loop


The while loop is an entry controlled loop statement, means the condition is
evaluated first and if it is true, then the body of the loop is executed. After
executing the body of the loop, the condition is once again evaluated and if it is
true, the body is executed once again, the process of repeated execution of the
body of the loop continues until the condition finally becomes false and the control
is transferred out of the loop.

107
ITERATION
Example 1 :
#include <stdio.h>
int main ()
{ Output:
/* local variable definition */ value of a: 10
int a = 10; // Initialization or a is value of a: 11
called as counter variable value of a: 12
/* while loop execution */ value of a: 13
while( a < 20 ) // condition or loop value of a: 14
value of a: 15
{
value of a: 16
printf("value of a: %d\n", a); //body value of a: 17
of the loop value of a: 18
a++; value of a: 19
}
return 0; 108
}
ITERATION

❑ Write a C program to check whether a given number is an armstrong number


or not.

Armstrong number is a number that is equal to the sum of cubes of its


digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong
numbers.
Let's try to understand why 153 is an Armstrong number.

153 = (1*1*1)+(5*5*5)+(3*3*3)
where:
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So:
1+125+27=153 109
ITERATION
#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf("enter the number ="); Output:
scanf("%d",&n);
temp=n;
while(n>0)
{
?????
r=n%10;
sum=sum+(r*r*r);
n=n/10;
?
}
if(temp==sum)
printf("%d is armstrong number ",temp);
else
printf("%d is not armstrong number",temp);
return 0;
} 110
ITERATION
❑ Write a C program to check whether a given number is
palindrome number or not.
A palindrome number is a number that is same after reverse. For example
121, 34543, 343, 131, 48984 are the palindrome numbers.

111
ITERATION
#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf("enter the number="); Output:
scanf("%d",&n);

?????
temp=n;
while(n>0)
{
r=n%10;

}
sum=(sum*10)+r;
n=n/10; ?
if(temp==sum)
printf("%d is a palindrome number ",temp);
else
printf("%d is not palindrome",temp);
return 0;
}

112
ITERATION

❑ do...while loop
The do-while loop is similar to the while loop with one
important difference. The body of do-while loop is executed at
least once. Only then, the test expression is evaluated.
do
{
// the body of the loop
}
while (testExpression);

113
ITERATION

❑ Program to print table for the given number using do while


loop
#include<stdio.h>
int main()
{ Output:
int i=1,number=0; Enter a number: 5
printf("Enter a number: "); 5
scanf("%d",&number); 10
do 15
{ 20
printf("%d \n",(number*i)); 25
i++; 30
} 35
while(i<=10); 40
return 0; 45
} 50
114
ITERATION

❑ For Loop
The for loop is another repetitive control structure, and is used to execute
a set of instructions repeatedly until the condition becomes false. The
assignment, incrimination or decrementation and condition checking is
done in for statement only, where as other control structures are not
offered all these features in one statement.
For loop has three parts:
1. Initialize counter.
2. Test condition is used to initialize counter variable.
3. Increment/decrement is used to increment or decrement counter
variable.

115
ITERATION

❑ For Loop

116
ITERATION
❑ Write a program in C to display n terms of natural number and their
sum.
#include <stdio.h>
void main()
{
Output:
int i,n,sum=0;
Input Value of terms : 5
printf("Input Value of terms : ");
scanf("%d",&n);
The first 5 natural
printf("\nThe first %d natural numbers
numbers are:
are:\n",n);
12345
for(i=1;i<=n;i++)
The Sum of natural
{ numbers upto 5 terms : 15
printf("%d ",i);
sum+=i;
}
printf("\nThe Sum of natural numbers upto %d
terms : %d \n",n,sum);
117
ITERATION
1. Write a C program to calculate the factorial of a given
number.
Factorial of a positive integer (number) is the sum of multiplication of all the
integers smaller than that positive integer. For example, factorial of 5 is 5 * 4 * 3 *
2 * 1 which equals to 120.
#include <stdio.h>
void main()
{
int i,f=1,num;
printf("Enter the number : "); Output:
scanf("%d",&num); Enter the number : 5
for(i=1;i<=num;i++) The Factorial of 5 is: 120
{
f=f*i;
}
printf("The Factorial of %d is: %d\n",num,f);
}
118
ITERATION
1. Write a program in C to display the pattern like right angle triangle
with a<stdio.h>
#include number.
void main()
{
int i,j,rows;
printf("Enter number of rows : Output:
"); Enter number of rows : 5
scanf("%d",&rows); 1
for(i=1;i<=rows;i++) 12
{ 123
for(j=1;j<=i;j++) 1234
{ 12345
printf("%d",j);
}
printf("\n");
}
119
}
ITERATION
The Fibonacci sequence is a sequence where the next term is the sum of the
previous two terms. The first two terms of the Fibonacci sequence are 0
followed by 1.
#include<stdio.h>
int main()
{
int n1=0,n2=1,n3,i,number;
printf("Enter the number of elements:"); Output:
scanf("%d",&number); Enter the number
printf("\n%d %d",n1,n2); //printing 0 and 1 of elements:5
for(i=2;i<number;i++) //loop starts from 2 because 0 and 1 are
already printed 01123
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
return 0;
}
120
ITERATION

❑Jump statements are used to interrupt the normal flow of


program.

❑ While executing any loop, it becomes necessary to skip a part


of the loop or to leave the loop as soon as certain condition
becomes true, that is called jumping out of loop.

❑ C language allows jumping from one statement to another


within a loop as well as jumping out of the loop.

The Break
The Continue
Statement
Statement 121
ITERATION

❑ THE BREAK
STATEMENT
❑ The break statement is used to terminate the loop.

❑ The break statement is used inside loop or switch


statement.

❑ When the keyword break is used inside any C loop,


control automatically transferred to the first statement
after the loop.

❑ When compiler finds the break statement inside a loop,


compiler will abortSyntax : break;
the loop and continue to execute
statements followed by loop. 122
ITERATION

❑ FLOW DIAGRAM OF BREAK


STATEMENT

123
ITERATION

124
ITERATION

#include<stdio.h>
int main()
{
int a=0; OUTPUT
while(a<10) Statement 1
{
a++; Statement 2
if(a==5) Statement 3
break;
Statement 4
printf("\nStatement End of Program.
%d",a);
}
printf("\nEnd of Program.");
}
125
ITERATION

❑ THE CONTINUE
STATEMENT
❑The continue statement skips the current iteration of the
loop & continue with the next iteration.

❑ When a continue statement is encountered inside a loop,


control jumps to the beginning of the loop for next
iteration, skipping the execution of statements inside the
body of loop for the current iteration.

Syntax : continue;

126
ITERATION

❑ FLOW DIAGRAM OF CONTINUE


STATEMENT

127
ITERATION

128
ITERATION

#include<stdio.h> OUTPUT
int main()
Statement 1
{
int a=0;
Statement 2
while(a<10) Statement 3
{ Statement 4
a++; Statement 6
if(a==5) Statement 7
continue; Statement 8
printf("\nStatement %d",a); Statement 9
}
Statement 10
printf("\nEnd of Program.");
} End of Program.
129
ITERATION

❑ THE GOTO STATEMENT

❑ C provides the goto statement to transfer control


unconditionally from one place to another place in the
program.
❑ A goto statement can cause program control almost in the
program unconditionally.
❑ When a goto statement is encountered in a c program, the
control jumps directly to the label mentioned in the goto
statement.
❑ The goto statement requires a label to identify the place to
move the execution.
❑ A label is a valid
Syntax : goto
variable namegotolabel:
and must be ended with a
colon(:). 130
ITERATION

❑ FLOW DIAGRAM OF GOTO


STATEMENT

131
ITERATION
#include <stdio.h>
int main()
{
int i,sum=0;
for(i = 1; i<=10; i++)
{
sum = sum+i;
if(i==7) OUTPUT
{ Sum = 28
goto addition;
}
}
addition:
printf("Sum = %d", sum);
return 0;
}
132
ITERATION

Counter-Controlled Loops Event-Controlled Loops


Generally with for loops Generally with while, do-while
Can generally infer number of loops
repetitions from code Can’t infer number of repetitions
from program

Loops execution depends upon Loops execution depends upon the


count variable values. condition.
Examples: Examples:
read 5 numbers read until input ends
print 7 items read until a number encountered
sort n items search through data until item
A sentinel-controlled loop is the indefinitefound
repetition loop as the number of
repetitions is not known before the loop begins executing. An example is
do..while. 133
ITERATION

134
ITERATION

int count;
for( count=1; count<=100; count++)
printf("%d",count);

int reverseNumber=0; int


number=12345; while(number>0)
{
reverseNumber=
(reverseNumber*10)+ number%10;
number/=10;
} printf("Reverse Number is:
%d\n", reverseNumber);
135
136

You might also like