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

Cs3353 Unit I

Uploaded by

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

Cs3353 Unit I

Uploaded by

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

CS3353

C PROGRAMMING AND DATA


STRUCTURES

UNIT I
C PROGRAMMING FUNDAMENTALS
What is C Programming Language?
 C is a general-purpose programming language that is
extremely popular, simple, and flexible to use.
 It is a structured programming language that is machine-
independent and extensively used to write various
applications, Operating Systems like Windows, and
many other complex programs like Oracle database, Git,
Python interpreter, and more.
 It is said that ‘C’ is a god’s programming language. One
can say, C is a base for the programming. If you know
‘C,’ you can easily grasp the knowledge of the other
programming languages that uses the concept of ‘C’
C Basic Commands
C Basic commands Explanation
This command includes standard input output header
#include <stdio.h> file(stdio.h) from the C library before compiling a C
program
It is the main function from where C program execution
int main()
begins.
{ Indicates the beginning of the main function.
Whatever written inside this command “/* */” inside a C
/*_some_comments_*/ program, it will not be considered for compilation and
execution.
printf(“Hello_World! “); This command prints the output on the screen.
This command is used for any character input from
getch();
keyboard.
This command is used to terminate a C program (main
return 0;
function) and it returns 0.
} It is used to indicate the end of the main function.
How C Programming Language Works?

C is a compiled language. A compiler is a special tool that


compiles the program and converts it into the object file which is
machine readable. After the compilation process, the linker will
combine different object files and creates a single executable file
to run the program
STRUCTURE OF C PROGRAM
 A C program basically consists of the following parts −
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
COMPONENTS OF C PROGRAM
 Header Files: The first and foremost component is the inclusion of
the Header files in a C program.
 A header file is a file with extension .h
 Which contains C function declarations and macro definitions to be
shared between several source files.
 Example of Header files:
stddef.h – Defines several useful types and macros.
stdint.h – Defines exact width integer types.
stdio.h – Defines core input and output functions
stdlib.h – Defines numeric conversion functions, pseudo-
random network generator, memory allocation
string.h – Defines string handling functions
math.h – Defines common mathematical functions
 Main Method: The next part of a C program is to declare the
main() function.
e.g. main()
{}
 Variable Declaration: The next part of any C program is the
variable declaration.
 In the C program, no variable can be used without being declared.
 Also in a C program, the variables are to be declared before any
operation in the function.
 Ex. main()
{
int a;
Body of program: Body of a function in C program, refers to the
operations that are performed in the functions.
Example:
int main()
{
int x;
printf("%d", x);
Return Statement: The last part in any C program is the return statement.
-The return statement refers to the returning of the values from a function.
-This return statement and return value depend upon the return type of the
function.
For example: if the return type is void, then there will be no return
statement.
int main()
{
int a;
printf("%d", a);
return 0;
}
C - Basic Syntax

A C program consists of various tokens and a token is either a


keyword, an identifier, a constant, a string literal, or a symbol
printf("Hello, World! \n");
In this C statement consists of five tokens − 1.printf, 2. ( , 3."Hello,
orld! \n“, 4. ), 5.;
Semicolons:
The semicolon is a statement terminator
Comments:
Comments are like helping text in your C program and they are
ignored by the compiler. They start with /* and terminate with the
characters */
Keywords
 The following list shows the reserved words in C. These reserved
words may not be used as constants or variables or any other
identifier names.
auto else long switch contin goto sizeof
ue
break enum register typedef default if static

case extern return union do int struct

char float short unsigne volatile while _Packe


d d

const for signed void double


DATA TYPES
 A data type specifies the type of data that a variable can store
such as integer, floating, character, etc.
Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type They are again arithmetic types and they
are used to define variables that can only
assign certain discrete integer values
throughout the program.

Void Data Type The type specifier void indicates that no


value is available.
Each data type requires different amounts of memory and has some
specific operations which can be performed over it .
Data Types Memory Size Range
char 1 byte −128 to 127
signed char 1 byte −128 to 127
unsigned char 1 byte 0 to 255
int 2 Or 4 byte −32,768 to 32,767
signed int 2 Or 4 byte −32,768 to 32,767
unsigned int 2 or 4 byte 0 to 65,535
short int 2 byte −32,768 to 32,767
signed short int 2 byte −32,768 to 32,767
unsigned short int 2 byte 0 to 65,535
long int 4 byte -2,147,483,648 to 2,147,483,647
signed long int 4 byte -2,147,483,648 to 2,147,483,647
unsigned long int 4 byte 0 to 4,294,967,295
float 4 byte
double 8 byte
long double 10 byte
Identifiers
 A C identifier is a name used to identify a variable, function, or any
other user-defined item.
Identifiers must be unique.
An identifier starts with a letter A to Z, a to z, or an underscore '_'
followed by zero or more letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within
identifiers.
C is a case-sensitive programming language.
Thus, Manpower and manpower are two different identifiers in C.
Rules for Identifiers
 A valid identifier can have letters (both uppercase and lowercase
letters), digits and underscores.
 The first letter of an identifier should be either a letter or an
underscore.
 You cannot use keywords as identifiers.
 There is no rule on how long an identifier can be. (However, you
may run into problems in some compilers if the identifier is longer
than 31 characters.)
Some examples for identifiers
mohd zara abc move_name a_123 myname50
_temp j a23b9 retVal
 Examples for incorrect identifier
1testprogram (/* starts with a digit */), %arrayex (/* contains
invalid character */), Char (/* reserved word */ ), Structure prg (/*
 Types of identifiers
Internal identifier
External identifier
Internal Identifier
If the identifier is not used in the external linkage,
then it is known as an internal identifier. The internal
identifiers can be local variables.
External Identifier
If the identifier is used in the external linkage, then it
is known as an external identifier. The external identifiers
can be function names, global variables.
Differences between Keyword and Identifier
Keyword Identifier

Keyword is a pre-defined word. The identifier is a user-defined word

It must be written in a lowercase letter. It can be written in both lowercase and


uppercase letters.

Its meaning is pre-defined in the c Its meaning is not defined in the c


compiler. compiler.

It is a combination of alphabetical It is a combination of alphanumeric


characters. characters.

It does not contain the underscore It can contain the underscore


character. character.
Example
int main()
{
int a=10;
int A=20;
printf("Value of a is : %d",a);
printf("\nValue of A is :%d",A);
return 0;
}

Output:
Value of a is : 10
Value of A is :20

The above output shows that the values of both the variables, 'a' and
'A' are different. Therefore, we conclude that the identifiers are case
sensitive.
VARIABLES
 A variable is a name of the memory location. It is
used to store data. Its value can be changed, and it can
be reused many times.
int a;
float b;
char c;
 Here, a, b, c are variables. The int, float, char are the
data types.
Rules for defining variables

 A variable can have alphabets, digits, and underscore.


 A variable name can start with the alphabet, and
underscore only. It can't start with a digit.
 No whitespace is allowed within the variable name.
 A variable name must not be any reserved word or
keyword, e.g. int, float, etc.
 Valid variable names: Invalid variable names:
int a; int 2;
int _ab; int a b;
int a30; int long;
Types of Variables in C
 There are many types of variables in c:
1.Local variable
2.Global variable
3.Static variable
4.Automatic variable
5.External variable
 Local Variable
A variable that is declared inside the function or block is called a local variable.
It must be declared at the start of the block.
Example:
void function1()
{
int x=10;//local variable
}
 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.
It must be declared at the start of the block.
Example:
int value=20;//global variable
void function1()
{
int x=10;//local variable
}
Static Variable
A variable that is declared with the static keyword is called
static variable.
It retains its value between multiple function calls.
Example:
void function1()
{
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
Automatic Variable
All variables in C that are declared inside the block, are
automatic variables by default.
We can explicitly declare an automatic variable using auto
keyword.
EXAMPLE:
void main(){
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
External Variable
We can share a variable in multiple C source files by using
an external variable. To declare an external variable, you need to
use extern keyword.
myfile.h
extern int x=10;//external variable (also global)
OPERATIONS
 C operators are one of the features in C which has
symbols that can be used to perform mathematical,
relational, bitwise, conditional, or logical manipulations.
The C programming language has a lot of built-in operators
to perform various tasks as per the need of the program.
TYPES OF OPERATOR
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment and Decrement Operators
 Conditional Operator
 Bitwise Operators
 Special Operators
Arithmetic Operators
 An arithmetic operator performs mathematical
operations such as addition, subtraction,
multiplication, division etc on numerical values
(constants and variables).
Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

remainder after division


%
(modulo division)
// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;

c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);

return 0;
}
Increment and Decrement
Operators
 Increment and Decrement Operators are useful
operators generally used to minimize the
calculation, i.e. ++x and x++ means x=x+1 or -
x and x−−means x=x-1. But there is a slight
difference between ++ or −− written before or
after the operand. Applying the pre-increment
first add one to the operand and then the result
is assigned to the variable on the left whereas
post-increment first assigns the value to the
variable
Operatoron the Description
left and then increment the
operand. ++ Increment
−− Decrement
// Working of increment and decrement operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

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


printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);

return 0;
}
Output:
++a=11
--b=99
++c=11.50
--d=99.50
Relational operators
 Relational operators are used to comparing two
quantities or values

Operator Description

== Is equal to
!= Is not equal to
> Greater than
< Less than

>= Greater than or equal to

<= Less than or equal to


// Working of relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;

printf("%d == %d is %d \n", a, b, a == b);


printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);

return 0;
}
Logical operators
 C provides three logical operators when we test
more than one condition to make decisions. These
are: && (meaning logical AND), || (meaning logical
OR) and ! (meaning logical NOT)
Operator Description
And operator. It performs logical conjunction
of two expressions. (if both expressions
&& evaluate to True, result is True. If either
expression evaluates to False, the result is
False)
Or operator. It performs a logical disjunction
on two expressions. (if either or both
||
expressions evaluate to True, the result is
True)
Not operator. It performs logical negation on
!
// Working of logical operators

#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b);
printf("!(a != b) is %d \n", result);
result = !(a == b);
printf("!(a == b) is %d \n", result);
return 0;
}
Bitwise Operators
 C provides a special operator for bit operation
between two variables.
Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right


#include <stdio.h>
#include <conio.h>
void main()
{
int m = 10,n = 20,AND,OR,XOR,NOT ;
clrscr();
AND = (m&n);
OR = (m|n);
NOT = (~m);
XOR = (m^n);
printf("AND value = %d\n",AND );
printf("OR value = %d\n",OR );
printf("NOT value = %d\n",NOT );
printf("XOR value = %d\n",XOR );
printf("left shift value = %d\n", m << 1);
printf("right shift value = %d\n", m >> 1);
getch();
}
Output:
AND value =0 OR value = 30 NOT value = -11
XOR value = 30 left shift value = 20 right shift value = 5
Assignment Operators
 Assignment operators applied to assign the
result of an expression to a variable. C has a
collection of shorthand assignment operators.

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
// Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;

c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);

return 0;
}
Special Operators
 C programming language also offers a few other
important operators including sizeof, comma,
pointer(*), and conditional operator (?:).
Operator Example What it does

Returns the size occupied by


sizeof sizeof(a) the data type of the
operand.

Refers to the memory


& &a address where operand is
stored.

* *a A pointer.
a? b:
?: Alternative of if-else.
statement
#include<stdio.h>
int main()
{
int number = 10, *pointer;
int another_number=13;
pointer=&number;
printf("int is: %d bytes\n", sizeof(int));
printf("Example of pointer and reference operator!\n");
printf("Memory address: %d\n",pointer);
printf("Example of condition operator!\n");
(another_number>14)? (printf("It is greater than number 14!")) : (printf("It
is less than number 14!"));
// if you put the value 15 in another_number variable then it will output>>
It is greater than number 14!
return 0;
}

Output:
int is: 4 bytes
Example of pointer and reference operator!
Memory address: 1701039932
Example of condition operator!
It is less than number 14!
Operator Precedence in C
 In between operators, some have higher precedence and some
have lower precedence. For example, Division has a higher
precedence than subtraction operator.
Category Operator Associativity
Postfix () [] -> . ++ – – Left to right
+ – ! ~ ++ – – (type)* &
Unary Right to left
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
<<= &= ^= |=
EXPRESSION AND
C Expressions:
STATEMENTS
An expression is a combination
of constants and variables interconnected by one or more operators. An
expression consists of one or more operands and one or more operators.
Operands are values and operators are symbols that represent
particular actions.
Examples of Expressions:
 num1 + num2 // variables num1 and num2 are operands and + is
the operator used.
 x = y // the assignment operator (=) is used to assign the value
stored in y to x.
 a = b + c // the value of the expression (b + c) is assigned to a.
 x <= y // the lesser-than-equalTo (<=) the relational operator
compares the values of x and y and returns either 1 (true) or 0
(false).
 a++ // the value of variable a is incremented by 1 i.e, this
expression is equivalent to a = a + 1.
TYPES OF EXPRESSION
Arithmetic Expressions
 Addition (+), Subtraction(-), Multiplication(*), Division(/),
Modulus(%), Increment(++) and Decrement(–) operators are
said to “Arithmetic expressions”. This operator works in
between operands. like A+B, A-B, A–, A++ etc.
#include <stdio.h>
int main()
{
int a,b,result;
printf("Enter 2 numbers for Arithmetic operation \n");
scanf("%d\n%d",&a,&b);
result = a+b;
printf("Addition of %d and %d is = %d \n",a,b,result);
result = a-b;
printf("Subtraction of %d and %d is = %d \n",a,b,result);
result = a*b;
printf("Multiplication of %d and %d is = %d \n",a,b,result);
result = a/b;
printf("Division of %d and %d is = %d \n",a,b,result);
result = a%b;
printf("Modulus(Remainder) when %d divided by %d = %d \n",a,b,result);
int c=a;
result = a++;
printf("Post Increment of %d is = %d \n",c,result);
result = ++a;
printf("Pre Increment of %d is = %d \n",c,result);
result=a--;
printf("Post decrement of %d is = %d \n",c,result);
result=--a;
printf("Pre decrement of %d is = %d \n",c,result);
printf("==========================================");
Relational expression
== (equal to), != (not equal to), > (greater than), < (less than),
>= (greater than or equal to), <= (less than or equal to) operators are
said to “Relational expressions”.This operators works in between
operands. Used for comparing purpose. Like A==B, A!=B, A>B, A<B etc.
#include <stdio.h>
Example:
int main()
{
int x=4;
if(x%2==0)
{
printf("The number x is even");
}
else
printf("The number x is not even");
return 0;
}
Logical Expressions
&&(Logical and), ||(Logical or) and !(Logical not) operators are said
to “Logical expressions”. Used to perform a logical operation. This
operator works in between operands. Like A&&B, A||B,A!B etc.
Example:
#include <stdio.h>
int main()
{
int x = 4;
int y = 10;
if ( (x <10) && (y>5))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}
Conditional Expressions
?(Question mark) and :(colon) are said to “Conditional
expressions”. Used to perform a conditional check. It has 3 expressions
first expression is condition. If it is true then execute expression2 and if
it is false then execute expression3. Like (A>B)?”A is Big”:”B is Big”.
Example:
#include<stdio.h>
#include<string.h>
int main()
{
int age = 25;
char status;
status = (age>22) ? 'M': 'U';
if(status == 'M')
printf("Married");
else
printf("Unmarried");
return 0;
C Statements
 A statement is an instruction given to the computer
to perform an action.
 There are three different types of statements in C:
 Expression Statements
 Compound Statements
 Control Statements
 An expression statement or simple
statement consists of an expression followed by a
semicolon (;).
 Examples of expression statements:
a = 100; b = 20; c = a / b;
COMPOUND STATEMENTS

 A compound statement also called a block,


consists of several individual statements
enclosed within a pair of braces { }.
 For example:
{
a = 3;
b = 10;
c = a + b;
}
CONTROL STATEMENTS

 A single statement or a block of statements can be


executed depending upon a condition using control
statements like if, if-else, etc. We shall learn more
about control statements in later sections.
 Example of if control statement:
a = 10;
if ( a > 5)
{
b = a + 10;
}
CONDITIONAL STATEMENTS
 Conditional statements help you to make a decision
based on certain conditions.
 These conditions are specified by a set of conditional
statements having boolean expressions which are
evaluated to a boolean value of true or false.
 There are the following types of conditional
statements in C.
 If statement
 If-Else statement
 Nested If-else statement
 If-Else If ladder
 Switch statement
IF STATEMENT
 The single if statement in C language is used to
execute the code if a condition is true. It is also
called a one-way selection statement.
 Syntax
if(expression)
{
block of statements;
}
 Example program:
#include<stdio.h>
#include<conio.h>
void main()
{
int num=0;
printf("enter the number");
scanf("%d",&num);
if(n%2==0)
{
printf("%d number in even",num);
}
getch();
}
If-else statement
 The if-else statement in C language is used to execute the code if
the condition is true or false. It is also called a two-way selection
statement.
 By using the if statement, only one block of the code executes
after the condition is true but by using the if-else statement,
there are two possible blocks of code where the first block is
used for handling the success part and the other one for the
failure condition.
 Syntax
if(expression)
{
block of statements 1;
}
else
{
block of statements 2;
 if..else Statement Example
#include<stdio.h>
#include<conio.h>
void main()
{
int num=0;
printf("enter the number");
scanf("%d",&num);
if(n%2==0)
{
printf("%d number in even", num);
}
else
{
printf("%d number in odd",num);
}
getch();
}
Nested If-else statement
 The nested if...else statement is used when a program
requires more than one test expression. It is also called a
multi-way selection statement.
 When a series of the decision are involved in a statement,
we use the if-else statement in nested form.
 Syntax
if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{
statement-block 3;
}
Example program for nested if
#include<stdio.h>
}
#include<conio.h>
}
void main( )
{ else
int a,b,c; {
clrscr(); if(b>c)
printf("Please Enter 3 number"); {
scanf("%d%d%d",&a,&b,&c);
printf("b is greatest");
if(a>b)
{ }
if(a>c) else
{ {
printf("a is greatest"); printf("c is greatest");
} }
else
}
{
printf("c is greatest"); getch();
}
If..else If ladder
 The if-else-if statement is used to execute one code
from multiple conditions.
 It is also called a multipath decision statement. It is
a chain of if..else statements in which each if
statement is associated with an else if statement
and the last would be an else statement.
 Syntax
if(condition1)
{
//statements
}
else if(condition2)
{
//statements
}
else if(condition3)
{
//statements
}
else
{
//statements
}
If..else If ladder Example
#include<stdio.h> }
#include<conio.h>
else if(a%5==0)
void main( )
{ {
int a; printf("divisible by 5");
printf("enter a number"); }
scanf("%d",&a);
else
if( a%5==0 && a%8==0)
{ {
printf("divisible by both 5 and 8"); printf("divisible by none");
} }
else if( a%8==0 )
getch();
{
printf("divisible by 8"); }
Switch Statement
 switch statement acts as a substitute for a long if-
else-if ladder that is used to test a list of cases.
 A switch statement contains one or more case
labels that are tested against the switch expression.
 When the expression match to a case then the
associated statements with that case would be
executed.
 Syntax
Switch (expression)
{
case value1:
//Statements break;
case value 2:
//Statements break;
case value 3:
//Statements case value n:
//Statements break;
Default:
//Statements
}
switch statement Example
#include <stdio.h> case 3:
int main() printf("Case1: Value is: %d",
{ num);
int num=2; default:
switch(num+2) printf("Default: Value is: %d",
{ num);
case 1: }
printf("Case1: Value is: return 0;
%d", num); }
case 2:
printf("Case1: Value is:
%d", num);
For loop
 For loop is used to evaluate the initialization part
first, checking the condition for true or false. If the
condition is true, it executes the statements of for
loop.
Syntax:
for (initial value; condition; incrementation or
decrementation )
{
statements;
}
Example program
Program to find the factorial of a
number
#include <stdio.h>
#include <conio.h>
void main()
{
int i, a ,f = 1;
printf("Enter a number:\n");
scanf("%d", &a);
for (i = 1; i <= a; i++)
f=f*i;
printf("Factorial of %d is %d\n", a, f);
getch();
}
While Loop
 The condition is evaluated before processing the
loop’s body. Only the loop’s body is executed if the
condition is true.
 Then the control goes back to the beginning after
completing the loop once. The statements in the
loop will be executed again, and if the condition is
true and checked, this process goes on until the
condition becomes false.
 The control will go out of the loop if the condition
is false. After completion of the loop, the control
will go to the statement immediately after the
loop, and the body can contain more than one
statement
 Syntax:

while (condition)
{
statements;
}
Print numbers from 1 to 5

#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
Output:
1
2
3
4
5
Do-While
 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.
The syntax:
do
{
// Statement block
}
while (Condition);
Example program:
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
Do
{
printf("value of a: %d\n", a);
a = a + 1;
}
while( a < 20 );
return 0;
}
FUNCTIONS
 A function is a block of code that performs a
specific task.
 There are two types of functions in C programming:

Library Functions: are the functions which are declared in the C


header files such as scanf(), printf(), gets(), puts(), ceil(), floor()
etc.
User-defined functions: are the functions which are created by
the C programmer
Defining a Function
 The general form of a function definition in
C
return_type function_name( parameter list )
{
body of the function
}
 A function definition in C programming
language consists of a function header and
a function body.
Example
/* function returning the m ax between two num
bers * /
int max(int num 1, int num 2)
{
/* local variable declaration * /
int result;
if (num 1 > num 2)
result = num 1;
else
result = num 2;
return result;
}
Function Declarations
 A function declaration tells the compiler about a
function name and how to call the function. The
actual body of the function can be defined separately.
return_type function_nam e( param eter list );
Example: int m ax(int num 1, int num 2);
Parameter names are not important in function
declaration only their type is required
int m ax(int, int);
 Function declaration is required when you define a
function in one source file and you call that function
in another file.
 In such case you should declare the function at the
top of the file calling the function
Calling a Function
 While creating a C function, you give a
definition of what the function has to do. To use
a function,you will have to call that function to
perform the defined task.
 When a program calls a function, program
control is transferred to the called function.
 A called function performs defined task and
when its return statement is executed or when
its function ending closing brace is reached, it
returns program control back to the main
program.
Example
#include <stdio.h> }
/* function declaration * / /* function returning the max
int m ax(int num 1, int num 2); between two num bers * /
int m ain ()
int m ax(int num 1, int num 2)
{
/* local variable definition * / {
int a = 100; /* local variable declaration * /
int b = 200; int result;
int ret; if (num 1 > num 2)
/* calling a function to get m ax
result = num 1;
value * /
ret = m ax(a, b); else
printf( "Max value is : %d\n", ret ); result = num 2;
return 0; return result;
Different aspects of function
calling
A function, depending upon the presence of arguments
and return type, can be classified under following
categories
 function without arguments and without return value
 function without arguments and with return value
 function with arguments and without return value
 function with arguments and with return value
function without arguments and without return value
 When a function has no arguments, it does not
receive any data from the calling function similarly,
when it does no return a value, the calling function
does not receive any data from the calling function.
Example program
#include<stdio.h>
main ()
{
void sum ();
clrscr ();
sum ();
getch ();
}
void sum ()
{
int a,b,c;
printf("enter 2 numbers:\n"); output
scanf ("%d%d", &a, &b); Enter 2 numbers:
c = a+b; 3
printf("sum = %d",c); 5
} Sum=8
Functions with arguments and without return
values

 In this function the data are transferred from calling


function to called function.
 The called function receives some data from the
calling function and does not send back any values
to the calling function
Example program
#include<stdio.h>
main ()
{
void sum (int, int );
int a,b;
printf("enter 2 numbers");
scanf("%d%d", &a,&b);
sum (a,b);
getch ();
}
void sum ( int a, int b)
{
int c;
c= a+b;
printf (“sum=%d”, c);
}
Functions without arguments and with return
values
Example
#include<stdio.h>
main ()
{
int sum ();
int c;
c= sum ();
printf(“sum = %d”,c);
getch ();
}
Int
sum ()
{
int a,b,c;
printf(“enter 2 numbers”); s
canf (“%d%d”, &a, &b);
c = a+b;
return c;
}
Functions with arguments and with
return values
Example
#include<stdio.h>
main ()
{
int sum ( int,int);
int a,b,c;
printf("enter 2 numbers");
scanf("%d%d", &a,&b);
c= sum (a,b);
printf ("sum=%d", c);
getch ();
}
int sum ( int a, int b )
{
int c;
c= a+b;
return c;
}
Function Arguments
 An Argument is a data passed from a main program to the
function. In this function we can pass a variable by following two
ways
Call by value / pass by value
Call by reference/pass by reference
Function call by value
 In the call by value method the actual arguments are
copied to the formal arguments, hence any operation
performed by function on arguments doesn’t affect
actual parameters.
Actual parameters: The parameters that appear in
function calls.
Formal parameters: The parameters that appear in
function declarations.
Example:
#include <stdio.h>
int increment(int var)
{
var = var+1;
return var;
}
int main()
{
int num1=20;
int num2 = increment(num1);
printf("num1 value is: %d", num1);
printf("\nnum2 value is: %d", num2);
return 0;
}
Function call by reference

 The address of the variable is passed


 In the function, the address of the argument is
copied into memory location instead of the value
#include<stdio.h> printf("Before swapping:");
printf("\nnum1 value is %d",
void swapnum ( int *var1, int
*var2 ) num1);
{ printf("\nnum2 value is %d",
int tempnum ; num2);
tempnum = *var1 ; /*calling swap function*/
*var1 = *var2 ; Swapnum( &num1, &num2 );
*var2 = tempnum ; printf("\nAfter swapping:");
} printf("\nnum1 value is %d",
num1);
int main( )
{ printf("\nnum2 value is %d",
num2);
int num1 = 35, num2 = 45 ;
return 0;
Difference between call by value and call by
reference
No. Call by value Call by reference
1 A copy of the value is passed into the An address of value is passed into the
function function

2 Changes made inside the function is limited Changes made inside the function
to the function only. The values of the actual validate outside of the function also.
parameters do not change by changing the The values of the actual parameters do
formal parameters. change by changing the formal
parameters.

3 Actual and formal arguments are created at Actual and formal arguments are
the different memory location created at the same memory location
C Library Functions
SN Header file Description
1 stdio.h This is a standard input/output header file. It contains all the library
functions regarding standard input/output.
2 conio.h This is a console input/output header file.
3 string.h It contains all string related library functions like gets(), puts(),etc.

4 stdlib.h This header file contains all the general library functions like
malloc(), calloc(), exit(), etc.
5 math.h This header file contains all the math operations related functions
like sqrt(), pow(), etc.
6 time.h This header file contains all the time-related functions.
7 ctype.h This header file contains all character handling functions.
8 stdarg.h Variable argument functions are defined in this header file.
9 signal.h All the signal handling functions are defined in this header file.
10 setjmp.h This file contains all the jump functions.
11 locale.h This file contains locale functions.
12 errno.h This file contains error handling functions.
13 assert.h This file contains diagnostics functions.
Benefits of functions
a)To improve the readability of code.
b) Improves the reusability of the code, same function
can be used in any program rather than writing the same
code from scratch.
c) Debugging of the code would be easier if you use
functions, as errors are easy to be traced.
d) Reduces the size of the code, duplicate set of
statements are replaced by function calls.
Recursive Function
 Recursion is the process of repeating items in a self-
similar way. In programming languages, if a program
allows you to call a function inside the same function,
then it is called a recursive call of the function.
 Pseudocode for writing any recursive function
void recursion()
{
recursion();
/* function calls itself */
}
int main()
{
recursion();
Example of recursion in C
#include <stdio.h> int main()
unsigned long long int {
factorial(unsigned int i) int i = 12;
{ printf("Factorial of %d is
if(i <= 1) %d\n", i, factorial(i));
{ return 0;
return 1; }
} Output:
return i * factorial(i - 1); Factorial of 12 is
} 479001600
Benefits of recursive
function
 Used to create clearer and simply versions of several
algorithms
 Memory occupied when the recursive function is called
is very less compared to an ordinary function
 Recursion is a very useful way of creating and
accessing certain dynamic data structures such as
linked lists, stacks, queues etc…
ARRAYS
 Arrays a kind of data structure that can store a
fixed-size sequential collection of elements of the
same type.
 An array is used to store a collection of data, but it
is often more useful to think of an array as a
collection of variables of the same type.
 A specific element in an array is accessed by an
index.
 All arrays consist of contiguous memory locations.
The lowest address corresponds to the first
element and the highest address to the last
element.
Declaring Arrays
 To declare an array in C, a programmer specifies
the type of the elements and the number of
elements required by an array as follows
type arrayname [ arraysize];
 This is called a single-dimensional array. The
arraySize must be an integer constant greater
than zero and type can be any valid C data type.
 For example, to declare a 10-element array called
balance of type double, use this statement
double balance[10];
Initializing Arrays
 You can initialize an array in C either one by one or
using a single statement as follows
double balance[5]={1000.0,2.0,3.4,7.0,50.0};
 The number of values between braces { } cannot
be larger than the number of elements that we
declare for the array between square brackets [ ].
 If you omit the size of the array, an array just big
enough to hold the initialization is created.
Therefore,
double balance[]={1000.0,2.0,3.4,7.0,50.0};
Accessing Array Elements

 An element is accessed by indexing the array


name. This is done by placing the index of the
element within square brackets after the name of
the array.
double salary=balance[9];
 The above statement will take the 10th element
from the array and assign the value to salary
variable.
Example program: printf("Element[%d] = %d\n", j, n[j] );
#include <stdio.h> }
int main ()
return 0;
{
int n[ 10 ]; }
/* n is an array of 10 integers */ OUTPUT
int i,j; Element[0]=100
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) Element[1]=101
{ Element[2]=102
n[ i ] = i + 100; Element[3]=103
/* set element at location i to i + 100 */
} Element[4]=104
/* output each array element's value */ Element[5]=105
for (j = 0; j < 10; j++ )
Element[6]=106
{
Element[7]=107
Element[8]=108
Advantage of C Array
1)Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can
retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we
need a few lines of code only.
4) Random Access: We can access any element randomly
using the array.
Disadvantage of C Array
Fixed Size: Whatever size, we define at the time
of declaration of the array, we can't exceed the limit.
Two Dimensional Array
 The two-dimensional array can be defined as an
array of arrays. The 2D array is organized as
matrices which can be represented as the collection
of rows and columns.
 However, 2D arrays are created to implement a
relational database lookalike data structure.
 It provides ease of holding the bulk of data at once
which can be passed to any number of functions
wherever required.
Declaration of two dimensional Array in C
data_type array_name[rows][columns];
Example: int twodimen[4][3];
Initialization of 2D Array in C
 In the 1D array, we don't need to specify the
size of the array if the declaration and
initialization are being done simultaneously.
However, this will not work with 2D arrays.
 We will have to define at least the second
dimension of the array. The two-dimensional
array can be declared and defined in the
following way.
<data type> array name_[row size]
[column size];

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},
Two-dimensional array
#include<stdio.h>
arr[0][0] = 1
int main(){
int i=0,j=0;
arr[0][1] = 2
int arr[4][3]={{1,2,3},{2,3,4}, arr[0][2] = 3
{3,4,5},{4,5,6}}; arr[1][0] = 2
//traversing 2D array arr[1][1] = 3
for(i=0;i<4;i++)
{
arr[1][2] = 4
for(j=0;j<3;j++) arr[2][0] = 3
{ arr[2][1] = 4
printf("arr[%d] [%d] = %d \ arr[2][2] = 5
n",i,j,arr[i][j]);
arr[3][0] = 4
}//end of j
}//end of i arr[3][1] = 5
return 0; arr[3][2] = 6
}
Multi-dimensional Arrays in C
 C programming language allows multidimensional
arrays. Here is the general form of a
multidimensional array declaration
type name[size1][size2]...[sizeN];
The following declaration creates a three dimensional
integer array
int threedim[5][10][4];

You might also like