[go: up one dir, main page]

0% found this document useful (0 votes)
19 views115 pages

Unit-1 Part2, Unit-2 Upto Loops

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

Unit-1 Part2, Unit-2 Upto Loops

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

C

Introduction

 C is a structured programming language.


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

 In the year of 1968, research was started


by Dennis Ritchie on programming
languages like BCPL, CPL.
 The main aim of his research was to
develop a new language to create an OS
called UNIX.
 After four years of research, a new
programming language was created with
solutions for drawbacks in languages like
BCPL & CPL. In the year of 1972, the
new language was introduced with the
name “Traditional C”.

The name 'c' was selected from the sequence


of previous language ‘B’ (BCPL) because
most of the features of 'c' were derived from
BCPL (B language).

The first outcome of the c language was the


UNIX operating system. The initial UNIX OS
was completely developed using 'c'
programming language.

The founder of the ‘C’ language, Dennis


Ritchie is known as “Father of C” and
also “Father of UNIX”.
The c programming language is very popular
because it is reliable, simple and easy to use
and it is the base for almost all the other
programming languages.

The following are the language before ‘c’ &


various versions of ‘c’.
1. CPL (Common Programming Language)
The CPL was invented by Martin Richards at
the University of Cambridge in the early of
1960s.
2. BCPL (Basic Combined Programming
Language)
The BCPL was invented by Martin
Richards at the University of Cambridge in
the year of 1966. It was a popular
programming language at that time. BCPL
allows the user, direct access to the computer
memory. BCPL is the extension of CPL.
3. B Language
B language is derived from BCPL. It was
introduced in the year of 1969 by Ken
Thompson and Dennis Ritchie at Bell
Laboratory, USA. The B language is similar to
BCPL.
4. C Language
C language is derived from the B language. It
was introduced in the year of 1972 by Dennis
Ritchie at Bell Laboratory, USA. The C
language was mainly developed to create an
operating system called UNIX. The name C is
given based on the previous language B and
BCPL. Ninety percent of the UNIX operating
system code is written in C language. During
the 1970s, the C language became a very
popular programming language. Many
universities and organizations began creating
their version of C language for their respective
projects. So, C language has got many variants
at that time. Later it was standardized.
5. ANSI C (C89)
In the year of 1983, the ANSI (American
National Standards Institute) formed a
committee to frame standard specifications for
the C language. In the year of 1989, this
committee introduced a standard version of C
with the name "ANSI C" with standard library
files. The ANSI C is also called as C89 in
short form.
6. C90
In the year of 1990, the ANSI C was got ISO
(International Organization for
Standardization) standardization with the
inclusion of a few new features like new
library files, new processor commands. And it
was also added with keywords const, volatile
and signed, etc... ISO standardized ANSI C as
ISO/IEC 9899:1990. This version is called as
C90 in short form.
7. C99
In the year of 1995, many new features were
added to the C90 to create a new version of it.
This new version of C was got ISO
standardization in the year of 1999 with the
name ISO/IEC 9899:1999. In the short form, it
is called as C99. Later C99 became the official
standard version of C.

General rules for any C program


1. Every executable statement must end
with a semicolon symbol (;).
2. Every C program must contain exactly
one main method (Starting point of the
program execution).
3. All the system-defined words
(keywords) must be used in lowercase
letters.
4. Keywords can not be used as user-
defined names(identifiers).
5. For every open brace ({), there must be
respective closing brace (}).
6. Every variable must be declared before
it is used.
Structure of a C Program
C is a structured programming language.
Every c program and its statements must be in
a particular structure. Every c program has the
following general structure...

Line 1: Comments - They are ignored by


the compiler
This section is used to provide a small
description of the program. The comment lines
are simply ignored by the compiler, that means
they are not executed. In C, there are two
types of comments.
1. Single Line Comments: Single line
comment begins with // symbol. We can
write any number of single line comments.
2. Multiple Lines Comments: Multiple
lines comment begins with /* symbol and
ends with */. We can write any number of
multiple lines comments in a program.
In a C program, the comment lines are
optional. Based on the requirement, we write
comments. All the comment lines in a C
program just provide the guidelines to
understand the program and its code.
Line 2: Preprocessing Commands
Preprocessing commands are used to include
header files and to define constants. We use
the #include statement to include the header
file into our program. We use
a #define statement to define a constant. The
preprocessing statements are used according to
the requirements. If we don't need any header
file, then no need to write #include statement.
If we don't need any constant, then no need to
write a #define statement.
Line 3: Global Declaration
The global declaration is used to define the
global variables, which are common for all the
functions after its declaration. We also use the
global declaration to declare functions. This
global declaration is used based on the
requirement.
Line 4: int main()
Every C program must write this statement.
This statement (main) specifies the starting
point of the C program execution. Here, main
is a user-defined method which tells the
compiler that this is the starting point of the
program execution. Here, int is a data type of
a value that is going to return to the Operating
System after completing the main method
execution. If we don't want to return any
value, we can use it as void.
Line 5: Open Brace ( { )
The open brace indicates the beginning of the
block which belongs to the main method. In C
program, every block begins with a '{' symbol.
Line 6: Local Declaration
In this section, we declare the variables and
functions that are local to the function or block
in which they are declared. The variables
which are declared in this section are valid
only within the function or block in which
they are declared.
Line 7: Executable statements
In this section, we write the statements which
perform tasks like reading data, displaying the
result, calculations, etc., All the statements in
this section are written according to the
requirements.
Line 9: Closing Brace ( } )
The close brace indicates the end of the block
which belongs to the main method. In C
program every block ends with a '}' symbol.
Line 10, 11, 12, ...: User-defined function()
This is the place where we implement the
user-defined functions. The user-defined
function implementation can also be
performed before the main method. In this
case, the user-defined function need not be
declared. Directly it can be implemented, but
it must be before the main method. In a
program, we can define as many user-defined
functions as we want. Every user-defined
function needs a function call to execute its
statements.
C Constants
In C programming language, a constant is
similar to the variable but the constant hold
only one value during the program execution.
That means, once a value is assigned to the
constant, that value can't be changed during
the program execution. Once the value is
assigned to the constant, it is fixed throughout
the program. A constant can be defined as
follows...
A constant is a named memory location
which holds only one value throughout the
program execution.
In C programming language, a constant can
be of any data type like integer, floating-
point, character, string and double, etc.,
Integer constants
An integer constant can be a decimal
integer or octal integer or hexadecimal
integer. A decimal integer value is specified
as direct integer value whereas octal integer
value is prefixed with 'o' and hexadecimal
value is prefixed with 'OX'.
An integer constant can also be unsigned
type of integer constant or long type of
integer constant. Unsigned integer constant
value is suffixed with 'u' and long integer
constant value is suffixed with 'l' whereas
unsigned long integer constant value is
suffixed with 'ul'.
Example
125 -----> Decimal Integer Constant
O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer
Constant
50u -----> Unsigned Integer Constant
30l -----> Long Integer Constant
100ul -----> Unsigned Long Integer
Constant
Floating Point constants
A floating-point constant must contain both
integer and decimal parts. Some times it
may also contain the exponent part. When a
floating-point constant is represented in
exponent form, the value must be suffixed
with 'e' or 'E'.
Example
The floating-point value 3.14 is represented
as 3E-14 in exponent form.
Character Constants
A character constant is a symbol enclosed in
single quotation. A character constant has a
maximum length of one character.
Example
'A'
'2'
'+'
In the C programming language, there are
some predefined character constants called
escape sequences. Every escape sequence
has its own special functionality and every
escape sequence is prefixed with '\' symbol.
These escape sequences are used in output
function called 'printf()'.

C Identifiers
In C programming language, programmers can
specify their name to a variable, array, pointer,
function, etc... An identifier is a collection of
characters which acts as the name of variable,
function, array, pointer, structure, etc... In
other words, an identifier can be defined as the
user-defined name to identify an entity
uniquely in the c programming language that
name may be of the variable name, function
name, array name, pointer name, structure
name or a label.
The identifier is a user-defined name of an
entity to identify it uniquely during the
program execution
Example
int marks;
char studentName[30];

Here, marks and studentName are identifiers.


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

C Tokens
In a C program, a collection of all the
keywords, identifiers, operators, special
symbols, constants, strings, and data values
are called tokens.
Tokens are used to construct c programs and
they are said to the basic building blocks of a c
program.
In a c program tokens may contain the
following...
1. Keywords
2. Identifiers
3. Operators
4. Special Symbols
5. Constants
6. Strings
7. Data values
8. C Keywords

As every language has words to construct


statements, C programming also has words
with a specific meaning which are used to
construct c program instructions. In the C
programming language, keywords are special
words with predefined meaning. Keywords are
also known as reserved words in C
programming language.

In the C programming language, there are 32


keywords. All the 32 keywords have their
meaning which is already known to the
compiler.
Keywords are the reserved words with
predefined meaning which already known
to the compiler
Properties of Keywords
1. All the keywords in C programming
language are defined as lowercase letters
so they must be used only in lowercase
letters
2. Every keyword has a specific meaning,
users can not change that meaning.
3. Keywords can not be used as user-
defined names like variable, functions,
arrays, pointers, etc...
4. Every keyword in C programming
language represents something or specifies
some kind of action to be performed by the
compiler.
The following table specifies all the 32
keywords with their meaning...
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.
Primarydatatypes
The primary data types in the C programming
language are the basic data types. All the
primary data types are already defined in the
system. Primary data types are also called as
Built-In data types. The following are the
primary data types in c programming
language...
1. Integer data type
2. Floating Point data type
3. Double data type
4. Character data type
Integer Data type
The integer data type is a set of whole
numbers. Every integer value does not have
the decimal value. We use the keyword "int"
to represent integer data type in c. We use the
keyword int to declare the variables and to
specify the return type of a function. The
integer data type is used with different type
modifiers like short, long, signed and
unsigned. The following table provides
complete details about the integer data type.

Floating Point data types


Floating-point data types are a set of numbers
with the decimal value. Every floating-point
value must contain the decimal value. The
floating-point data type has two variants...
 float
 double
We use the keyword "float" to represent
floating-point data type and "double" to
represent double data type in c. Both float and
double are similar but they differ in the
number of decimal places. The float value
contains 6 decimal places whereas double
value contains 15 or 19 decimal places. The
following table provides complete details
about floating-point data types.

Character data type


The character data type is a set of characters
enclosed in single quotations. The following
table provides complete details about the
character data type.

C Output Functions
printf() function
The printf() function is used to print string or
data values or a combination of string and data
values
on the output screen (User screen). The
printf() function is built-in function defined in
a header file called "stdio.h". When we want
to use printf() function in our program we
need to include the respective header file
(stdio.h) using the #include statement.
Example:
printf("message to be display!!!");
Example Program
#include<stdio.h>
#include<conio.h>
void main(){

printf("Hello! Welcome to my class!!!");


}

C Input Functions
scanf() function
The scanf() function is used to read multiple
data values of different data types from the
keyboard. The scanf() function is built-in
function defined in a header file called
"stdio.h". When we want to use scanf()
function in our program, we need to include
the respective header file (stdio.h)
using #include statement.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i;
printf("\nEnter any integer value: ");
scanf("%d",&i);
printf("\nYou have entered %d number",i);
}
C Operators
An operator is a symbol used to perform
arithmetic and logical operations in a program.
That means an operator is a special symbol
that tells the compiler to perform
mathematical or logical operations. C
programming language supports a rich set of
operators that are classified as follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
1.Arithmetic Operators (+, -, *, /, %)

The arithmetic operators are the symbols that


are used to perform basic mathematical
operations like addition, subtraction,
multiplication, division and percentage
modulo. The following table provides
information about arithmetic operators.
Operator Meaning Exa

+ Addition 10

- Subtraction 10

* Multiplication 10

/ Division 10
Operator Meaning Exa

% Remainder of the Division 5%


⇒ The addition operator can be used with
numerical data types and character data type.
When it is used with numerical values, it
performs mathematical addition and when it is
used with character data type values, it
performs concatenation (appending).

⇒ The remainder of the division operator is


used with integer data type only.
2.Relational Operators (<, >, <=, >=, ==, !=)

The relational operators are the symbols that


are used to compare two values. That means
the relational operators are used to check the
relationship between two values. Every
relational operator has two results TRUE or
FALSE. In simple words, the relational
operators are used to define conditions in a
program. The following table provides
information about relational operators.
Operato
r Meaning E

< Returns TRUE if the first value is 1


smaller than second value otherwise F
returns FALSE

> Returns TRUE if the first value is larger 1


than second value otherwise returns T
FALSE

<= Returns TRUE if the first value is 1


smaller than or equal to second value F
otherwise returns FALSE

>= Returns TRUE if the first value is larger 1


than or equal to second value otherwise T
returns FALSE

== Returns TRUE if both values are equal 1


otherwise returns FALSE F
Operato
r Meaning E

!= Returns TRUE if both values are not 1


equal otherwise returns FALSE T
3.Logical Operators (&&, ||, !)

The logical operators are the symbols that are


used to combine multiple conditions into one
condition. The following table provides
information about logical operators.
Operato
r Meaning Exam

&& Logical AND - Returns TRUE if all 10 <


conditions are TRUE otherwise 10 is
returns FALSE

|| Logical OR - Returns FALSE if all 10 <


conditions are FALSE otherwise is TR
returns TRUE

! Logical NOT - Returns TRUE if !(10


Operato
r Meaning Exam

condition is FLASE and returns > 10


FALSE if it is TRUE
⇒ Logical AND - Returns TRUE only if all
conditions
are TRUE, if any of the conditions is FALSE

⇒ Logical OR - Returns FALSE only if all


then complete condition becomes FALSE.

conditions are FALSE, if any of the conditions


is TRUE then complete condition becomes
TRUE.
4.Increment & Decrement Operators (++ &
--)

The increment and decrement operators are


called unary operators because both need only
one operand. The increment operators adds
one to the existing value of the operand and
the decrement operator subtracts one from the
existing value of the operand. The following
table provides information about increment
and decrement operators.
Operato
r Meaning

++ Increment - Adds one to existing value

-- Decrement - Subtracts one from existing


value
The increment and decrement operators are
used in front of the operand (++a) or after the
operand (a++). If it is used in front of the
operand, we call it as pre-increment or pre-
decrement and if it is used after the operand,
we call it as post-increment or post-
decrement.
Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the
variable is increased by one before the
expression evaluation. In the case of pre-
decrement, the value of the variable is
decreased by one before the expression
evaluation. That means, when we use pre-
increment or pre-decrement, first the value of
the variable is incremented or decremented by
one, then the modified value is used in the
expression evaluation.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5,j;
j = ++i; // Pre-Increment
printf("i = %d, j = %d",i,j);
}
Output:
Post-Increment or Post-Decrement
In the case of post-increment, the value of the
variable is increased by one after the
expression evaluation. In the case of post-
decrement, the value of the variable is
decreased by one after the expression
evaluation. That means, when we use post-
increment or post-decrement, first the
expression is evaluated with existing value,
then the value of the variable is incremented
or decremented by one.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5,j;

j = i++; // Post-Increment

printf("i = %d, j = %d",i,j);

}
Output:

5.Assignment Operators (=, +=, -=, *=, /=,


%=)

The assignment operators are used to assign


right-hand side value (Rvalue) to the left-hand
side variable (Lvalue). The assignment
operator is used in different variants along
with arithmetic operators. The following table
describes all the assignment operators in the C
programming language.
Operato
r Meaning

= Assign the right-hand side value to left-


hand side variable

+= Add both left and right-hand side values


and store the result into left-hand side
variable

-= Subtract right-hand side value from left-


hand side variable value and store the
result
into left-hand side variable
Operato
r Meaning

*= Multiply right-hand side value with left-


hand side variable value and store the
result
into left-hand side variable

/= Divide left-hand side variable value with


right-hand side variable value and store the
result
into the left-hand side variable

%= Divide left-hand side variable value with


right-hand side variable value and store the
remainder
into the left-hand side variable
6.Bitwise Operators (&, |, ^, ~, >>, <<)

The bitwise operators are used to perform bit-


level operations in the c programming
language. When we use the bitwise operators,
the operations are performed based on the
binary values. The following table describes
all the bitwise operators in the C programming
language.
Let us consider two variables A and B as A =
25 (11001) and B = 20 (10100).
Operato
r Meaning

& the result of Bitwise AND is 1 if all the


bits are 1 otherwise it is 0

| the result of Bitwise OR is 0 if all the bits


are 0 otherwise it is 1

^ the result of Bitwise XOR is 0 if all the


bits are same otherwise it is 1

~ the result of Bitwise once complement is


negation of the bit (Flipping)
Operato
r Meaning

<< the Bitwise left shift operator shifts all the


bits to the left by the specified number of
positions

>> the Bitwise right shift operator shifts all


the bits to the right by the specified
number of positions

Bitwise AND 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.
In C Programming, the bitwise AND
operator is denoted by &.
Let us suppose the bitwise AND operation
of two integers 12 and 25.
Operato
r Meaning

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
&00011001
________
00001000 = 8 (In decimal)
Example 1: Bitwise AND
#include <stdio.h>

int main() {
int a = 12, b = 25;
printf("Output = %d", a & b);
return 0;
}
Operato
r Meaning

Output
Output = 8
Bitwise OR Operator |
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 |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)
Example 2: Bitwise OR
Operato
r Meaning

#include <stdio.h>

int main() {

int a = 12, b = 25;


printf("Output = %d", a | b);
return 0;
}
Output
Output = 29
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)
Operato
r Meaning

25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
^ 00011001
________
00010101 = 21 (In decimal)
Example 3: Bitwise XOR
#include <stdio.h>

int main() {

int a = 12, b = 25;


printf("Output = %d", a ^ b);
return 0;
}
Operato
r Meaning

Output
Output = 21
Bitwise Complement Operator ~
Bitwise complement operator is a unary
operator (works on only one operand). It
changes 1 to 0 and 0 to 1. It is denoted
by ~.
35 = 00100011 (In Binary)

Bitwise complement Operation of 35


~ 00100011
________
11011100 = 220 (In decimal)
Example 4: Bitwise complement
#include <stdio.h>
Operato
r Meaning

int main() {

printf("Output = %d\n", ~35);


printf("Output = %d\n", ~-12);
return 0;
}

Output
Output = -36
Output = 11
Shift Operators in C programming
There are two shift operators in C
programming:
 Right shift operator
 Left shift operator.
Right Shift Operator
Operato
r Meaning

Right shift operator shifts all bits towards


right by certain number of specified bits.
It is denoted by >>.
212 = 11010100 (In binary)
212 >> 2 = 00110101 (In binary) [Right
shift by two bits]
212 >> 7 = 00000001 (In binary)
212 >> 8 = 00000000
212 >> 0 = 11010100 (No Shift)

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 <<.
212 = 11010100 (In binary)
212<<1 = 110101000 (In binary) [Left
Operato
r Meaning

shift by one bit]


212<<0 = 11010100 (Shift by 0)
212<<4 = 110101000000 (In binary)
=3392(In decimal)

Example #5: Shift Operators


#include <stdio.h>

int main() {

int num=212, i;

for (i = 0; i <= 2; ++i) {


printf("Right shift by %d: %d\n", i,
num >> i);
Operato
r Meaning

}
printf("\n");

for (i = 0; i <= 2; ++i) {


printf("Left shift by %d: %d\n", i,
num << i);

return 0;
}
Run Code
Right Shift by 0: 212
Right Shift by 1: 106
Right Shift by 2: 53
Operato
r Meaning

Left Shift by 0: 212


Left Shift by 1: 424
Left Shift by 2: 848

7.Conditional Operator (?:)

The conditional operator is also called


a ternary operator because it requires three
operands. This operator is used for decision
making. In this o
perator, first we verify a condition, then we
perform one operation out of the two
operations based on the condition result. If the
condition is TRUE the first option is
performed, if the condition is FALSE the
second option is performed. The conditional
operator is used with the following syntax.
Condition ? TRUE Part : FALSE Part;
Example
A = (10<15)?100:200; ⇒ A value is 100
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input
for age variable
(age>=18)? (printf("eligible for
voting")) : (printf("not eligible for
voting")); // conditional operator
return 0;
}
8.Special Operators (sizeof, pointer, comma,
dot, etc.)

The following are the special operators in c


programming language.
sizeof operator
This operator is used to find the size of the
memory (in bytes) allocated for a variable.
This operator is used with the following
syntax.
sizeof(variableName);
Example
sizeof(A); ⇒ the result is 2 if A is an integer
#include<stdio.h>
void main()
{
int a;
float b ;
double c;
char d;
printf("%lu\n", sizeof(a));
printf("%lu\n", sizeof(b));
printf("%lu\n", sizeof(c));
printf("%lu\n", sizeof(d));
}
4
4
8
1
Note : The size of an int in C is either 2 or 4
bytes. However, the language standard
allows the size of int to be implementation-
specific, so portable code shouldn't depend
on it.

Here are the sizes of some other basic data


types in C:
float: 4 bytes
double: 8 bytes
char: 1 byte
That we use the %lu format specifier to
print the result, instead of %d. It is because
the compiler expects the sizeof operator to
return a long unsigned int (%lu), instead
of int (%d). On some computers it might
work with %d, but it is safer to use %lu.

Pointer operator (*)


This operator is used to define pointer
variables in c programming language.
Comma operator (,)
This operator is used to separate variables
while they are declaring, separate the
expressions in function calls, etc.
Dot operator (.)
This operator is used to access members of
structure or union.
 Expression Evaluation:
Expressions are evaluated using an assignment
statement of the form:
In the above syntax, variable is any valid C
variable name. When the statement like the
above form is encountered, the expression is
evaluated first and then the value is assigned
to the variable on the left hand side.
All variables used in the expression must be
declared and assigned values before evaluation
is attempted. Examples of expressions are:

Expressions are evaluated based on operator


precedence and associativity rules when an
expression contains more than one operator.

C Operator Precedence and Associativity


What is Operator Precedence?
The precedence of operators determines which
operator is executed first if there is more than
one operator in an expression.
Let us consider an example:
int x = 5 - 17* 6;
In C, the precedence of * is higher
than - and =. Hence, 17 * 6 is evaluated first.
Then the expression involving - is evaluated as
the precedence of - is higher than that of =.
Example1:
#include <stdio.h>
int main() {
int a = 5, b = 10, c = 15,result;

// Example of operator precedence


result = a + b * c; // Multiplication (*) has
higher precedence than addition (+)
printf("Result of a + b * c = %d\n", result);
// Using parentheses to change
precedence
result = (a + b) * c; // Parentheses change
the order of evaluation
printf("Result of (a + b) * c = %d\n", result);
return 0;
}
O/P:
155
225
In this program:
 The expression a + b * c evaluates b *
c first because multiplication has higher
precedence than addition.
 By using parentheses (a + b) * c, we
change the order of evaluation, so a + b is
evaluated first.
Example-2
// C Program to illustrate operator precedence
#include <stdio.h>
int main()
{
// printing the value of same expression
printf("10 + 20 * 30 = %d", 10 + 20 * 30);
return 0;
}
OUTPUT:610

What is Operator Associativity?


The associativity of operators determines the
direction in which an expression is evaluated.
For example,
b = a;
Here, the value of a is assigned to b, and not
the other way around. It's because the
associativity of the = operator is from right to
left.
Also, if two operators of the same precedence
(priority) are present, associativity determines
the direction in which they execute.
Let us consider an example:
1 == 2 != 3
Here, operators == and != have the same
precedence. And, their associativity is from
left to right. Hence, 1 == 2 is executed first.
The expression above is equivalent to:
(1 == 2) != 3
Note: If a statement has multiple operators,
you can use parentheses () to make the code
more readable.

Precedence Operator Operator Meaning A

1 () function call L
[] array reference
-> structure member access
. structure member access

2 ! negation R
~ 1's complement
+ Unary plus
- Unary minus
++ increment operator
-- decrement operator
Precedence Operator Operator Meaning A

& address of operator


* pointer
sizeof returns size of a variable
(type) type conversion

3 * multiplication L
/ division
% remainder

4 + addition L
- subtraction

5 << left shift L


>> right shift

6 < less than L


<= less than or equal to
> greater than
>= greater than or equal to

7 == equal to L
!= not equal to
Precedence Operator Operator Meaning A

8 & bitwise AND L

9 ^ bitwise EXCLUSIVE OR L

10 | bitwise OR L

11 && logical AND L

12 || logical OR L

13 ?: conditional operator L

14 = assignment R
*= assign multiplication
/= assign division
%= assign remainder
+= assign addition
-= assign subtraction
&= assign bitwise AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift
Precedence Operator Operator Meaning A

15 , separator L

#include <stdio.h>
int main() {
int a = 5, b = 10, c = 15;
int result;
// Left to right associativity example
result = a - b - c;
printf("Result of a - b - c: %d\n", result);
// Right to left associativity example
result = a = b = c;
printf("Result of a = b = c: %d\n",
result);
printf("Values after assignment: a = %d,
b = %d, c = %d\n", a, b, c);

return 0;
}
1. Left to Right Associativity:
o In the expression a - b - c, the
subtraction operators have left-to-
right associativity. So, it is evaluated
as (a - b) - c.
2. Right to Left Associativity:
o In the expression a = b = c, the
assignment operators have right-to-
left associativity. So,
o it is evaluated as a = (b = c).

 Type Conversion:
Type conversion in C is the process of
converting one data type to another. The type
conversion is only performed to those data
types where conversion is possible. Type
conversion is performed by a compiler.
For example, if you try to divide two
integers, 5 by 2, you would expect the result to
be 2.5. But since we are working with integers
(and not floating-point values), the following
example we just got output 2:
Example
int x = 5;
int y = 2;

int sum = 5 / 2;
printf("%d", sum); // Output 2
To get the right result, you need to know
how type conversion works.
There are two types of conversion in C:
 Implicit Conversion (automatically)
 Explicit Conversion (manually)
#include <stdio.h> As you can see, the
compiler automatically converts the int
value 9 to a float value of 9.000000.
This can be risky, as you might lose control
over specific values in certain situations.
Especially if it was the other way around - the
following example automatically converts the
float value 9.99 to an int value of 9:
#include <stdio.h>
int main() {
// Automatic conversion: int to float
float a = 9;
printf("%f", a);
return 0;
}
#include <stdio.h>
int main() {
// Automatic conversion: float to int
int a = 9.99;
printf("%d", a);
return 0;
}
O/P: 9
What happened to .99?
As another example, if you divide two
integers: 5 by 2, you know that the sum is 2.5.
And as you know from the beginning of this
page, if you store the sum as an integer, the
result will only display the number 2.
Therefore, it would be better to store the sum
as a float or a double,.

#include <stdio.h>
int main() {
float sum = 5 / 2;
printf("%f", sum); // 2.000000
return 0;
}
O/P:
2.000000
Why is the result 2.00000 and not 2.5? Well, it
is because 5 and 2 are still integers in the
division. In this case, you need to manually
convert the integer values to floating-point
values. That’s why explicit type conversion
has introduced.
Explicit Conversion
Explicit conversion is done manually by
placing the type in parentheses () in front of
the value.
Considering our problem from the example
above, we can now get the right result:
#include <stdio.h>

int main() {
// Manual conversion: int to float
float sum = (float) 5 / 2;
printf("%f", sum);
return 0;
}
O/P:
2.500000
You can also place the type in front of a
variable:
#include <stdio.h>
int main() {
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;
printf("%f", sum);
return 0;
}
O/P:
2.500000

Decision Making Statement:


Def: Decision-making statements are the
statements that are used to verify a given
condition and decide whether a block of
statements gets executed or not based on
the condition result.
In the C programming language, the program
execution flow is line by line from top to
bottom. That means the c program is executed
line by line from the main method. But this
type of execution flow may not be suitable for
all the program solutions. Sometimes, we
make some decisions or we may skip the
execution of one or more lines of code.
Consider a situation, where we write a
program to check whether a student has passed
or failed in a particular subject. Here, we need
to check whether the marks are greater than
the pass marks or not. If marks are greater,
then we decide that the student has passed
otherwise failed. To solve such kind of
problems in c we use the statements called
decision making statements.

In the c programming language, there are two


decision-making statements they are as
follows.
1. if statement
2. switch statement
if statement in c
In c, if statement is used to make decisions
based on a condition. The if statement verifies
the given condition and decides whether a
block of statements are executed or not based
on the condition result. In c, if statement is
classified into four types as follows...
1. Simple if statement
2. if-else statement
3. Nested if statement
4. if-else-if statement (if-else ladder)

Test whether given number is divisible by


5.
#include<stdio.h>
void main(){
int n ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
printf("Given number is divisible by 5\
n") ;
}
if-else statement
The if-else statement is used to verify the
given condition and executes only one out
of the two blocks of statements based on
the condition result. The if-else statement
evaluates the specified condition. If it is
TRUE, it executes a block of statements
(True block). If the condition is FALSE, it
executes another block of statements
(False block). The general syntax and
execution flow of the if-else statement is
as follows.
Test whether given number is even or
odd.
#include<stdio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVEN\n") ;
else
printf("Given number is ODD\n") ;
}

Magic Number in C using


if-else
In this section, we will discuss magic
numbers in C programming language
along with their various examples. When
the sum of all the given digits of a
number and the reverse of that sum is
multiplied, which is equal to the original
number, and then the number is called a
magic number.
For example, suppose we have a 1729
number and we need to validate whether
the number is a magic number or not. So,
first we need to get the sum of all digits
of the number which is 19 (1 + 7 + 2 + 9
= 19). Reverse the sum of the number is
91, and then get the product of the sum
of original digits with the reverse of that
sum as 19 * 91= 1729. So, it is the magic
number.

#include <stdio.h>
int main ()
{
// declare integer variables
int n, temp, rev = 0, digit, sum_of_digi
ts = 0;
printf (" Enter a Number: \n");
scanf (" %d", &n); // get the number
temp = n; // assign the number to tem
p variable
// use while loop to calculate the sum
of digits
while ( temp > 0)
{
// extract digit one by one and stor
e into the sum_of_digits
sum_of_digits = sum_of_digits + te
mp % 10; /* use modulus symbol to get t
he remainder of each iteration by temp
% 10 */
temp = temp / 10;
}

temp = sum_of_digits; // assign the su


m_of_digits to temp variable
printf (" \n The sum of the digits = %d
", temp);

// get the reverse sum of given digits


while ( temp > 0)
{ rev = rev * 10 + temp % 10;
temp = temp / 10;
}

printf (" \n The reverse of the digits =


%d", rev);
printf (" \n The product of %d * %d =
%d", sum_of_digits, rev, rev * sum_of_di
gits);
// use if else statement to check the magi
c number
if ( rev * sum_of_digits == n)
{
printf (" \n %d is a Magic Number. ",
n);
}
else
{
printf (" \n %d is not a Magic Numb
er. ", n);
}
return 0;

}
Output:
Enter a number
1729
The sum of the digits = 19
The reverse of the digits = 91
The product of 19 * 91 = 1729
1729 is a Magic Number.

In the above program, we take 1729 from


the user and assign the number to the
temp variable. After that, use a while
loop to extract the sum of the original
digits (n) into sum_of_digits one by one
and assign the result to the temp. Use the
loop again to reverse the sum of the
digits and print the reverse number. And
finally compare the original digit (N) with
the multiplication of sum_of_digits and
rev variable that return the same result
to show a magic number.
Nested if statement
Writing a if statement inside another if
statement is called nested if statement.
The general syntax of the nested if
statement is as follows...

Test whether given number is even or odd


if it is below 100.
#include<stdio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 100") ;
}
if-else-if statement (if-else ladder)
Writing a if statement inside else of an if
statement is called if-else-if statement. The
general syntax of the if-else-if statement is as
follows...
Find the largest of three numbers.
#include<stdio.h>
void main(){
int a, b, c ;
printf("Enter any three integer numbers:
") ;
scanf("%d%d%d", &a, &b, &c) ;
if( a>=b && a>=c)
printf("%d is the largest number", a) ;
else if (b>=a && b>=c)
printf("%d is the largest number", b) ;
else
printf("%d is the largest number", c) ;
}

'switch' statement in C
Consider a situation in which we have many
options out of which we need to select only
one option that is to be executed. Such kind of
problems can be solved using nested
if statement. But as the number of options
increases, the complexity of the program also
gets increased. This type of problem can be
solved very easily using a switch statement.
Using the switch statement, one can select
only one option from more number of options
very easily.

Example Program | Display pressed digit


in words.

#include<stdio.h>
void main(){
int n ;
printf("Enter any digit: ") ;
scanf("%d", &n) ;
switch( n )
{
case 0: printf("ZERO") ;
break ;
case 1: printf("ONE") ;
break ;
case 2: printf("TWO") ;
break ;
case 3: printf("THREE") ;
break ;
case 4: printf("FOUR") ;
break ;
case 5: printf("FIVE") ;
break ;
case 6: printf("SIX") ;
break ;
case 7: printf("SEVEN") ;
break ;
case 8: printf("EIGHT") ;
break ;
case 9: printf("NINE") ;
break ;
default: printf("Not a Digit") ;
}
}

For loop:
A for loop in C is used to repeat a block of
code a specific number of times. It consists of
three parts: initialization, condition, and
update.
Syntax
for (initialization; condition; update) {
// code block to be executed
}

Program code to find Reverse of a Number in


C:
#include<stdio.h>
void main()
{
int i,n,r,s=0;
printf("\n Enter The Number:");
scanf("%d",&n);
//LOOP FOR FINDING THE REVERSE
OF A NUMBER
for(i=n;i>0; )
{
r=i%10;
s=s*10+r;
i=i/10;
}
printf("\n The Reverse Number of %d is
%d",n,s);
}
Let us assume a number entered is 4321.
So i=4321 , s=0
1. i>0 (4321>0) for loop condition is
true
r=i%10 (r=4321%10) So r=1
s=s*10+r (s=0*10+1) So s=1
i=i/10 (i=4321/10) So i=432
2. i>0 (432>0) for loop condition is true
r=i%10 (r=432%10) So r=2
s=s*10+r (s=1*10+2) So s=12
i=i/10 (i=432/10) So i=43
3. i>0 (43>0) for loop condition is true
r=i%10 (r=43%10) So r=3
s=s*10+r (s=12*10+3) So s=123
i=i/10 (i=43/10) So i=4
4. i>0 (4>0) for loop condition is true
r=i%10 (r=4%10) So r=4
s=s*10+r (s=123*10+4) So s=1234
i=i/10 (n=4/10) So i=0
5. i>0 (0>0) for loop condition is false
It comes out of the for loop and prints the
reverse number which is stored in variable “s”.
6. Thus the program execution is
completed.
Output:
While loop:
The while Loop is an entry-controlled loop in
C programming language. This loop can be
used to iterate a part of code while the given
condition remains true.This is also called as
pre-test loop.
Syntax
The while loop syntax is as follows:
while (test expression)
{
// body consisting of multiple statements
}
Perfect Number:
A Perfect Number is a number that
is equal the sum of its positive divisors
excluding the given Number.
For example,
6 is a Perfect Number, because 6 is
equal to the sum of its positive divisors .
(ie. 1 + 2 + 3 = 6).
Program code for Perfect Number or Not in C:

#include<stdio.h>
void main()
{
int n, i=1, sum=0;
printf("\n Enter a number: ");
scanf("%d", &n);
/* Loop to calculate the sum of positive
divisors */
while(i<n)
{
if(n%i==0)
{
sum=sum+i;
}
i++;
}

/* if-else condition to print Perfect Number or


Not */
if(sum==n)
printf("\n %d is a Perfect Number.",n);
else
printf("\n %d is Not a Perfect Number.",n);
}
For Perfect Number:
1. Let us assume that a user enters the
positive integer value as 6.
2. It assigns the value of sum=0 and n=6.
3. It assigns the value of i=1 and the loop
continues till the condition of the while
loop is true.
3.1. i<n (1<6) while loop condition is
true
n%i==0 (6%1==0) if condition is true
sum=sum+i (sum=0+1) So, sum=1
i++ (i=1+1) So i=2
3.2. i<n (2<6) while loop condition is true
n%i==0 (6%2==0) if condition is true
sum=sum+i (sum=1+2) So, sum=3
i++ (i=2+1) So i=3
3.3. i<n (3<6) while loop condition is true
n%i==0 (6%3==0) if condition is true
sum=sum+i (sum=3+3) So, sum=6
i++ (i=3+1) So i=4
3.4. i<n (4<6) while loop condition is true
n%i==0 (6%4==0) if condition is false
i++ (i=4+1) So i=5
3.5. i<n (5<6) while loop condition is true
n%i==0 (6%5==0) if condition is false
i++ (i=5+1) So i=6
3.6. i<n (6<6) while loop condition is
false
It comes out of the while loop.
4. sum==n (6==6) if condition is true
So it prints 6 is a Perfect Number.
5. Thus program execution is completed.

Do-while condition:
 At first, the single statement or block of
statements which are defined
in do block are executed.
 After the execution of the do block, the
given condition gets evaluated. If the
condition is evaluated to TRUE, the
single statement or block of statements
of do block are executed again. Once the
execution gets completed again the
condition is evaluated.
 If it is TRUE, again the same
statements are executed.
 The same process is repeated until the
condition is evaluated to FALSE.
Whenever the condition is evaluated to
FALSE, the execution control moves out
of the while block.
It is a form of an exit-controlled or post-
tested loop where the test condition is
checked after executing the body of the loop.
Syntax of do…while Loop in C
do {

// body of do-while loop

} while (condition);
Example1: Program to display even
numbers upto 10.

#include<stdio.h>
void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
do
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}while( n <= 10 ) ;
}

Example 2:
Program code for Armstrong Number or Not
in C:
It calculates the sum of the cubes of its digits.
#include<stdio.h>
void main()
{
int n,num,r,ans=0;
printf("Enter a positive integer: ");
scanf("%d", &num);
n=num;

/* Loop to calculate the sum of the cubes of its


digits */
do
{
r=n%10;
ans=ans+r*r*r;
n=n/10;
}while(n>0);

/* if else condition to print Armstrong or Not */


if(ans==num)
{
printf("%d is an Armstrong number.",num);
}
else
{
printf("%d is not an Armstrong number.",num);
}
}
For Armstrong Number:
1. Let us assume that a user enters the
positive integer value as 153.
2. It assigns the value of ans=0,
num=153.
3. It assigns the value of n=num(ie.
n=153) and the loop continues till the
condition of the do-while loop is true.
3.1. do
r=n%10 (r=153%10) So r=3
ans=ans+r*r*r (ans=0+3*3*3) So
ans=27
n=n/10 (n=153/10) So n=15
n>0 (15>0) do-while loop condition is true
3.2. do
r=n%10 (r=15%10) So r=5
ans=ans+r*r*r (ans=9+5*5*5) So
ans=152
n=n/10 (n=15/10) So n=1
n>0 (1>0) do-while loop condition is true
3.3. do
r=n%10 (r=1%10) So r=1
ans=ans+r*r*r (ans=152+1*1*1) So
ans=153
n=n/10 (n=1/10) So n=0
n>0 (0>0) do-while loop condition is false
3.4. It comes out of the do-while loop and
checks whether the number is Armstrong or
not.
4. ans==num (153==153) if condition
is true
It prints 153 is an Armstrong number.
5. Thus program execution is completed.
Unconditional control statements:
In c, there are control statements that do
not need any condition to control the
program execution flow. These control
statements are called as unconditional
control statements. C programming language
provides the following unconditional control
statements...
 break
 continue
 goto
The above three statements do not need any
condition to control the program execution
flow.
break statement
In C, the break statement is used to perform
the following two things...
1. break statement is used to terminate
the switch case statement
2. break statement is also used to
terminate looping statements like while,
do-while and for.
When a break statement is encountered inside
the switch case statement, the execution
control moves out of the switch statement
directly. For example, consider the following
program.
Example Program to perform all arithmetic
operations using switch statement.
#include<stdio.h>
void main(){
int number1, number2, result ;
char operator;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &number1, &number2) ;
printf("Please enter any arithmetic operator:
");
switch(operator)
{
case '+': result = number1 + number2 ;
printf("Addition = %d", result) ;
break;
case '-': result = number1 - number2 ;
printf("Subtraction = %d", result) ;
break;
case '*': result = number1 * number2 ;
printf("Multiplication = %d", result)
;
break;
case '/': result = number1 / number2 ;
printf("Division = %d", result) ;
break;
case '%': result = number1 % number2 ;
printf("Remainder = %d", result) ;
break;
default: printf("\nWrong selection!!!") ;
}
}

Break :
#include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
printf("%d ", i);
}
return 0;
}
// Output: 0 1 2 3 4
In this example, when i becomes equal to 5,
the break statement is executed, causing an
immediate exit from the loop, and thus
numbers from 0 to 4 are printed

continue statement
The continue statement is used to move the
program execution control to the beginning of
the looping statement. When
the continue statement is encountered in a
looping statement, the execution control skips
the rest of the statements in the looping block
and directly jumps to the beginning of the
loop. The continue statement can be used with
looping statements like while, do-while and
for.
When we use continue statement
with while and do-while statements the
execution control directly jumps to the
condition. When we use continue statement
with for statement the execution control
directly jumps to the modification portion
(increment/decrement/any modification) of the
for loop. The continue statement execution is
as shown in the following figure.
Example Program to illustrate continue
statement.
#include<stdio.h>
void main(){
int number ;
while( 1 )
{
printf("Enter any integer number: ") ;
scanf("%d", &number) ;
if(number%2 == 0)
{
printf("Entered number is EVEN!!! Try
another number!!!\n") ;
continue ;
}
else
{
printf("You have entered ODD
number!!! Bye!!!") ;
break;
}
}

goto statement
The goto statement is used to jump from one
line to another line in the program.
Using goto statement we can jump from top to
bottom or bottom to top. To jump from one
line to another line, the goto statement
requires a label. Label is a name given to the
instruction or line in the program. When we
use a goto statement in the program, the
execution control directly jumps to the line
with the specified label.
Example Program for goto statement.
#include<stdio.h>
void main(){
printf("We are at first printf statement!!!\
n") ;
goto last ;
printf("We are at second printf statement!!!\
n") ;
printf("We are at third printf statement!!!\n")
;
last: printf("We are at last printf
statement!!!\n") ;

Output:
continue statement
The continue statement is used to move the
program execution control to the beginning of
the looping statement. When
the continue statement is encountered in a
looping statement, the execution control skips
the rest of the statements in the looping block
and directly jumps to the beginning of the
loop. The continue statement can be used with
looping statements like while, do-while and
for.
When we use continue statement
with while and do-while statements the
execution control directly jumps to the
condition. When we use continue statement
with for statement the execution control
directly jumps to the modification portion
(increment/decrement/any modification) of the
for loop.
#include<stdio.h>
#include<conio.h>
void main(){
int number ;
while( 1 )
{
printf("Enter any integer number: ") ;
scanf("%d", &number) ;
if(number%2 == 0)
{
printf("Entered number is EVEN!!! Try
another number!!!\n") ;
continue ;
}
else
{
printf("You have entered ODD
number!!! Bye!!!") ;
exit(0) ;
}
}
}

You might also like