0% found this document useful (0 votes)
47 views201 pages

Pic Unit 2 One Shot

Uploaded by

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

Pic Unit 2 One Shot

Uploaded by

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

PROGRAMMING IN C

Complete One-Shot
PROGRAMMING IN C
Unit 1
Unit-1 Syllabus
=> Introduction to Programming: Computer system, components of a
computer system, computing environments, computer languages, creating
and running programs, Preprocessor, Compilation process, role of linker, idea
of invocation and execution of a programme. Algorithms: Representation
using flowcharts, pseudocode. Introduction to C language: History of C,
basic structure of C programs, process of compiling and running a C
program, C tokens, keywords, identifiers, constants, strings, special symbols,
variables, data types, I/O statements. Interconversion of variables. Operators
and expressions: Operators, arithmetic, relational and logical, assignment
operators, increment and decrement operators, bitwise and conditional
operators, special operators, operator precedence and associativity,
evaluation of expressions, type conversions in expressions.
What is a Programming Language ?

A programming language is a set of rules that provides a


way of telling a computer what operations are to be
perform.
Any programming language consist of two parts :-
Syntax : Grammer rules to write statements .
Semantics : Set of pre-defined words .
Levels to Sabke Niklenge
Computer Languages

 High Level :
 The high-level language is very similar to human languages and
has a set of grammar rules that are used to make instructions more
easily.
 Example ; C,C++,Python,Java etc.
 Middle Level (Assembly Language) :
 Middle-level language is a computer language in which the
instructions are created using symbols such as letters, digits and
special characters.
 Low Level (Machine Language) :
 Low-Level language is the only language which can be
understood by the computer.
 The machine language contains only two symbols 1 & 0.
Translators
 These are set of programs that converts code/data from one language to
another.
1. Compilor :
▪ It converts high level language to machine language.
▪ It converts the whole code in a single go and gives all the eroors at the end .
▪ Used in Languages : C , C++,Java etc .
2. Interpreter :
▪ It also converts high level language to machine language bit runs the code line by line and
stops as it spots an error.
▪ Used in Languages : Python , Perl , Matlab etc .
3. Assembler :
▪ It converts assembly language to machine language .
Types of Computing Environments
 Personal Computing Environment : In personal computing environment there is a stand-alone machine.
Complete program resides on computer and executed there. Different stand-alone machines that constitute
a personal computing environment are laptops, mobiles, printers, computer systems, scanners etc. That we
use at our homes and offices.
 Time-Sharing Computing Environment : In Time Sharing Computing Environment multiple users share system
simultaneously. Different users (different processes) are allotted different time slice and processor switches
rapidly among users according to it. For example, student listening to music while coding something in an IDE.
Windows 95 and later versions, Unix, IOS, Linux operating systems are the examples of this time sharing
computing environment.
 Client Server Computing Environment : In client server computing environment two machines are involved i.e.,
client machine and server machine, sometime same machine also serve as client and server. In this
computing environment client requests resource/service and server provides that respective resource/service.
A server can provide service to multiple clients at a time and here mainly communication happens through
computer network.
 Distributed Computing Environment : In a distributed computing environment multiple nodes are connected
together using network but physically they are separated. A single task is performed by different functional
units of different nodes of distributed unit. Here different programs of an application run simultaneously on
different nodes, and communication happens in between different nodes of this system over network to solve
task.
Types of Computing Environments
 Grid Computing Environment : In grid computing environment, multiple computers from different locations
works on single problem. In this system set of computer nodes running in cluster jointly perform a given task by
applying resources of multiple computers/nodes. It is network of computing environment where several
scattered resources provide running environment for single task.
 Cloud Computing Environment : In cloud computing environment on demand availability of computer system
resources like processing and storage are availed. Here computing is not done in individual technology or
computer rather it is computed in cloud of computers where all required resources are provided by cloud
vendor. This environment primarily comprised of three services i.e software-as-a-service (SaaS), infrastructure-
as-a-service (IaaS), and platform-as-a-service (PaaS).
 Cluster Computing Environment : In cluster computing environment cluster performs task where cluster is a set
of loosely or tightly connected computers that work together. It is viewed as single system and performs task
parallelly that’s why also it is similar to parallel computing environment. Cluster aware applications are
especially used in cluster computing environment.
Algorithms
Algorithm to Add Two
Numbers in C
1. Start.
 These are the set of well defined instructions or 2. Declare variables num1,
steps in sequences to solve a problem. num2, and res.
3. Read values for num1 and
 In this input and output must be defined. num2.
4. Add the values of num1
 It should be independent of any programming and num2 and assigned
language means, it should be in general English the result to a res variable.
5. Display res.
not include any syntax or semantics. 6. Stop.
Pseudo Code
Pseudo Code
 It is an informal way of programming
Example:
description that does not require any strict
programming language syntax or underline
if "1"
technical consideration .
print response
 It is used to create and outline rough draft of "I am case 1"
the program . if "2"
 It shows basic flow of program without getting print response
into details . "I am case 2"
Symbol Name Symbol Representation

Terminal/Terminator
Flow Chart
Process  A flowchart is a type
of diagram that
represents a
workflow or process.
Decision
A flowchart can
also be defined as a
diagrammatic
Input/Output representation of an
algorithm, a step-
by-step approach
to solving a task.
Flow Arrow
if the user wants to
add 1 to an even
number and
subtract 1 if the
number is odd, the
flowchart would
be:

Modulus Operator (%)

Returns the remainder after


diving the left operand with the
right operand.
C Programming Overview

Developed by Dennis Ritchie.


Structures programming language.
Supports functions.
Provides easy readability.
Powerful language.
C Tokens
 A token in C can be defined as the smallest individual element of the C
programming language that is meaningful to the compiler.
 It is the basic component of a C program.
 Types of Tokens in C :
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
Keywords

These are the reserve words or pre-defined words who


have a fixed meaning and cannot be changed .
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifiers

 These are the name of variables, functions and arrays .


 Rules for Identifiers :
➢ The first letter of an identifier should be either alphabet or underscore.
➢ Can only contain character, digit, underscore.
➢ Keywords can not be named as an identifier.
➢ Commas and blank space are invalid while naming an identifier.
➢ Maximum length of the identifier is 31 characters.
Special Symbols

➢ Braces { } : It marks the start and end of a block of a code.


➢ Paranthesis ( ) : It indicates function call and it parameters .
➢ Brcakets [ ] : It is used for array element references .
Comments in C

 These are the statements that are not executed by the compiler or an interpreter.
 C Comments are a way to make a code more readable by providing more descriptions.
 Types of comments in C
➢ Single-line Comment in C :
// This is a single line comment .
➢ Multi-line Comment in C :
/*Comment starts
continues
continues
.
Comment ends*/
Preprocessor :-
A Basic C
#include
Program Preprocessors are programs that
process the source code before
compilation

Header File :-
<stdio.h>
It allows us to conduct input and output
operations in C. printf() and scanf()

Main Function :-
The main function serves as the starting
point for program execution.
Operators
in C
Precedence Category Operator Associativity

1 Postfix () [] -> . ++ - - Left to right

2 Unary ! ++ - - (type) sizeof Right to left

3 Multiplicative */% Left to right

4 Additive +- Left to right

Precedence 5

6
Relational

Equality
< <= > >=

== !=
Left to right

Left to right

of Operators 7

8
Bitwise AND

Bitwise XOR
&

^
Left to right

Left to right

9 Bitwise OR | Left to right

10 Logical AND && Left to right

11 Logical OR || Left to right

12 Conditional ?: Right to left

13 Assignment = += -= *= /= %= Right to left


Type Conversion in C

1. Implicit type conversion :


❑ The compiler provides implicit type conversions when operands are of
different data types.
❑ It is automatically done by the compiler by converting smaller data type into
a larger data type.

#include<stdio.h>
void main(){
int i=40;
Output Implicit value:40.000000
float a;
a=i;
printf(“Implicit value:%f",a);
}
Type Conversion in C

2. Explicit type conversion :


❑ Explicit type conversion is done by the user by using (type) operator.
❑ Before the conversion is performed, a runtime check is done to see if the
destination type can hold the source value.

#include<stdio.h>
void main(){
float i=40.000000;
Output explicit value:40
int a;
a=(int)i;
printf("explicit value:%d",a);
}
PROGRAMMING IN C
Unit 2
Unit-2 Syllabus
 Control structures: Decision statements; if and switch statement; Loop
control statements: while, for and do while loops, jump statements,
break, continue, goto statements.
 Arrays: Concepts, One dimensional array, declaration and initialization
of one dimensional arrays, two dimensional arrays, initialization and
accessing, multi dimensional arrays.
 Functions: User defined and built-in Functions, storage classes,
Parameter passing in functions, call by value, Passing arrays to functions:
idea of call by reference, Recursion.
 Strings: Arrays of characters, variable length character strings, inputting
character strings, character library functions, string handling functions.
Decession Control Statements

If statement
If – else statement
Switch statement
If statement
Example:- Syntax:-
#include <stdio.h>
 if(condition)
int main()
 {
{

int age= 9;
 // Statements to execute if condition is true
if (age > 18) {
printf("You are an adult");  }
}
if (age < 18) {
printf("You are not an adult");
}
return 0;
}
Flowchart
of
If statement
#include <stdio.h>
void main(){

int scount = 0;

Program for a if (scount == 0){


printf("Mass Bunk Successful");
mass bunk }
if (scount != 0){
printf("Mass Bunk not succesful");
}
}
#include <stdio.h>
void main(){

int scount = 0;
Program for a
mass bunk if (scount == 0){
printf("Mass Bunk Successful");
(More Correct }
One) else{
printf("Mass Bunk not succesful");
}
}
If- else statement
Example:- Syntax:-
 if(condition)
#include <stdio.h>
int main()
 {
{ 
int age= 9;  // Statements to execute if condition
is true
if (age > 18) {
printf("You are an adult");  }
} else {
else { // Statements to execute if condition
printf("You are not an adult"); is false
} }
return 0;
}
Flowchart of
If- else
statement
Lets consider you are a teacher and you have
to give grades to students

Conditions :

 Marks >= 90 => Grade A


 Marks >= 80 => Grade B
Marks >= 70 => Grade C
Marks >= 60 => Grade D
Marks < 60 => Fail
#include <stdio.h>
void main(){

int marks= 50;


if (marks>= 90){
printf("Grade A");}
if (marks >= 80){
1st thought printf("Grade B");}
if (marks >= 70){
printf("Grade C");
if (marks >= 60){
printf("Grade D");}
else {
printf("Fail);}
}
#include <stdio.h>
void main(){

int marks= 50;

if (marks>= 90){
printf("Grade A");}
The Correct else if (marks >= 80){

Solution printf("Grade B");}


else if (marks >= 70){
printf("Grade C");
else if (marks >= 60){
printf("Grade D");}
else {
printf("Fail);}
}
Else-if statement
#include <stdio.h> Example: Syntax:-
int main(){  if(condition) {
int age= 9;  // Execute if condition is true
if (age > 60) {  }
printf("You are Old");
} else if (condition) {
else if (age > 18) {
// Execute if condition is true
printf("You are an adult");
}
} else {
else {
// Execute if all above conditions
printf("You are child");
} are false
}
return 0;
}
Flowchart of
If- else
statement
Switch Statement
The replacement for if-else-if ladder.
Switch statement
#include <stdio.h> Example: Syntax:-
int main(){  switch(expression)
{
{
int num = 2;
case value1: statement_1;
switch (num) {
break;
case 1:
case value2: statement_2;
printf("Value is 1 is \n"); break;
break; .
case 2: case value_n: statement_n;
printf("Value is 2 is \n");
break; break;
default :
printf("Value is niether 1 nor 2\n");
break; default: default_statement;
}
return 0;
Break;
} }
Flowchart of
switch statement
Switch V/S If else if

Switch if else if
 It executes the different cases  It executes the different blocks
on the basis of the value of the based on the condition
switch variable. specified.
 It can only evaluate the int or  It can evaluate any type of
char type expressions. expression.
 Faster and easier to read for  It can get messy when there
the large number of conditions. are lots of conditions.
The one line for
Ternary Operator if-else
Syntax expression 1 ? expression 2 : expression 3

“if expression 1 is true (that is, if its value


is non-zero), then the value returned will
be expression 2, otherwise the value
returned will be expression 3
Ternary
Operator
Example
Now lets write a program to
print numbers from 1 to 5 .
What if you have to print till
100?
Now comes the concept of
Loops
Loops Classification
For Loop
Syntax:-
Example:
 for(initialization; check/test expression;
#include <stdio.h> updation)
 {
 // body consisting of multiple statements
int main()
{  }

for (int i = 1; i<= 5; i++)


{
printf("%d\n", i);
}

return 0;
}
Write a program
to print all even
numbers between
1 to 100 using for
loop
Flowchart of
for loop
While Loop
Example: Syntax:-
#include <stdio.h>  while (test expression)

int main()  {
 // body consisting of multiple statements
{ int i = 1;
 }
while (i<= 5)
{
printf("%d\n", i);
i++;
}

return 0;
}
Write a program
to print all even
numbers between
1 to 100 using
while loop
Flowchart of
while loop
Do-while Loop
Example:
Syntax:-
#include <stdio.h>  do {

int main()

 // body of do-while loop
{ int i = 1;

do {  } while (condition);
printf("%d\n", i);
i++;
}

while (i<= 5);

return 0;
}
Flowchart of
do-while loop
While Loop V/S Do-while Loop

While Do-while
 The test condition is  The test condition is checked after
checked before the loop body executing the body.
is executed.
 The body of the do…while loop is
 When the condition is false, executed at least once even
the body is not executed not when the condition is false.
even once.
 It is a type of post-tested or exit-
 It is a type of pre-tested or controlled loop.
entry-controlled loop.
 Semicolon is required at the end.
 Semicolon is not required.
Jump Statements

Continue statement
Break statement
Goto statement
Continue Statement

The continue statement is use to :-

 Skip the current iteration.


 Control moves to the next iteration.
 Statements after the continue statement
in the loop are not executed.
Write a program
to print all even
numbers between
1 to 10 except
one number enter
by user.
Break Statement

The break statement :-

 It is use to break out of the loop.


 It can be used inside loops or switch statements to bring the control
out of the block.
 It can only break out of a single loop at a time.
The Goto Statement

The C goto statement is a jump statement


which is sometimes also referred to as
an unconditional jump statement. The goto
statement can be used to jump from
anywhere to anywhere within a function.
Write a program
to print all even
numbers between
1 to 10 except
one number enter
by user.
Disadvantages of Goto Statement

 The use of the goto statement is highly discouraged as it makes the


program logic very complex.

 The use of goto makes tracing the flow of the program very difficult.

 The use of goto can be simply avoided by


using break and continue statements.
Write a program
to print the
prime numbers
between 1 to 50
1. Make a calculator using switch
statement which can perform:-

=> Addition
=> Subtraction
Self Practice => Multiplication
=> Division
Solution of self
Practice 1
2. Write a program to print
Self Practice all the numbers divisible by
7 using do-while loop.
Solution of self
Practice 2
ARRAYS
Lets write a program to print
marks of 5 students
Types of
data types
in C
What is an Array ?

Derived data type .


Fixed-size .
Collection of similar data items .
Stored in contiguous memory locations .
data_type array_name [size];

or
Array
Declaration data_type array_name
[size1] [size2]...[sizeN];
Array Initialization
With Declaration
data_type array_name [size] = {value1, value2, ... valueN};

With Declaration without size


data_type array_name[] = {1,2,3,4,5};

Using loops
for (int i = 0; i < N; i++) {
array_name[i] = valuei;
}
Accessing
Elements
of Array

array_name [index];
WAP in which you take marks
of 5 subjects from the user and
print the maximum marks.
Program for
maximum
mark
Types of Arrays

1-D Array
2-D Array
Multi-Dimensional Array
 A Two-Dimensional array or 2D array
in C is an array that has exactly two
dimensions. They can be visualized in
2-D Array in C the form of rows and columns
organized in a two-dimensional
plane.
2-D Array

array_name[rows] [columns];
3-D Array

array_name [size1] [size2] [size3];


Write a program to get the
Transpose of a matrix
Transpose
of a matrix
1. WAP in which you

=> Take number of subjects


from user

Self Practice => Take marks in each


subject

=> Print the AVERAGE marks


Solution of
Self Practice 1
2. Write a Program in
which you take two
matrix from user and
Self Practice return the addition of
these two matrix
Solution of Self Practice 2
FUNCTIONS
Functions

Derived Data type


Enclosed with {}
Perform Specific Task
Provides Code reusibility
Understanding Function in C

Declaration
Defination
Calling
Declaration
of Function

return_type
name_of_the_function
(parameter_1,
parameter_2);
Defining a
Function
 return_type function_name
(para1_type para1_name,
para2_type para2_name)
{
 // body of the function
}
Calling a
Function
Write a program to give sum
of two numbers using
function
Built-in Vs User Defined Functions

Built-in Function User-Defined Function


 Also known as Library Function
 Already existed in the compiler  Created by the user
package
 Any name can be given by the user
 Has a fixed pre-defined name
 Must be declared and defined
 Directly useable without being before being used
defined
 E.g) pow(), sqrt(), strcmp(), strcpy()
etc.
Actual and
Formal
Parameters
Call By Value

Output
Call By Reference

Output
Call By Value VS Call By Reference

Call By Value Call By Reference


 There are two copies of  Both the actual and formal
parameters stored in different parameters refer to the same
memory locations.One is the locations.
original copy and the other is  Any changes made inside the
the function copy.
function are actually reflected
 Any changes made inside in the actual parameters of the
functions are not reflected in caller.
the actual parameters of the
caller.
Passing
Arrays to
Function
Write a program to get the
sum of all the elements of
an array using function
Sum of all
elements of
an Array
Write a program to
get the maximum
Self Practice number from the
array using Function
Self Practice
STRINGS
String

It is an array of characters


Terminated with a null character i.e ' \0'
The difference between a character array and a
C string is that the string in C is terminated with a
unique character ‘\0’.
String Declaration in C

Declaring a string in C is as simple as declaring a


one-dimensional array.

char str[] = "Shivang";


String Initialisation
It is also similar as initalising an array
char str[8] = { 'S','h','I','v','a','n','g','\0'};
char str[] = { 'S','h','I','v','a','n','g','\0'};

Also it can be initalise as:-


char str[] = "Shivang";
char str[30] = "Shivang";
Write a Program
in which you take
user name input and
greet him
Gets and Puts

Scanf() is not capable of receiving multi-word strings , So


this problem is solved by using function gets().
Gets() is use with its counterpart puts
Puts() work as a replaemment for printf in case of strings.

Note :- Scanf() can also receive multi-word string using scanset

scanf("%[^\n]s", str);
Function Name Description

strlen(string_name) Returns the length of string name.

C Library strcpy(s1, s2)

strcmp(str1, str2)
Copies the contents of string s2 to string s1.

Compares the first string with the second string. If

<String.h>
strings are the same it returns 0.

Concat s1 string with s2 string and the result is stored


strcat(s1, s2)
in the first string.

strlwr() Converts string to lowercase.

strupr() Converts string to uppercase.

strstr(s1, s2) Find the first occurrence of s2 in s1.


More Library
Functions
STORAGE CLASSES
Storage Classes

Automatic storage class


Register storage class
Static storage class
External storage class
Automatic Storage Class

Storage: Memory.
Default value: An unpredictable value, often called a
garbage value.
Scope: Local to the block in which the variable is
defined.
Life: Till the control remains within the block in which the
variable is defined.
Register Storage Class

Storage: CPU registers.


Default value: Garbage value.
Scope: Local to the block in which the variable is
defined.
Life: Till the control remains within the block in which the
variable is defined.
Static Storage Class

Storage: Memory.
Default value: Zero.
Scope: Local to the block in which the variable is
defined.
Life: Value of the variable persists between different
function calls.
How Static
presisits
between
different
Functions
External Storage Class

Storage: Memory.
Default value: Zero.
Scope: Global.
Life: As long as the program’s execution doesn’t come to
an end.
RECURSION
Recursion

When a function calls itself from within its body it is


known as a recursive function.
such kind of function calls are called recursive
calls.
Lets write a program to get the
sum of numbers from 0 to N
in which N is given by the user
Program to
get sum till
number N
Write a program to get
factorial of a number using
recursion
Factorial Of
a number
PROGRAMMING IN C
Unit 3
Unit-3 Syllabus

 Pointers: Pointer basics, pointer arithmetic, pointers to pointers, generic


pointers, array of pointers, functions returning pointers, Dynamic memory
allocation. Pointers to functions.
 Structures and unions: Structure definition, initialization, accessing
structures, nested structures, arrays of structures, structures and
functions, self referential structures, unions, typedef, enumerations.
 File handling: command line arguments, File modes, basic file
operations read, write and append. Scope and life of variables, multi-
file programming..
Pointers Defination

It is a derived data type.


It is created with the * operator.
It is used to store the address of other C variables or a
memory location.
A pointer variable points to a data type (like int) of the
same type .
Pointers real
meaning
Here;
 i is variable
 3 is value
 And 65524 is its address

So when we want to change or use


the data through memory location
we use pointers

So pointers access the value by


storing its memory location address
Pointers

Syntax:-

datatype * ptr;

Where;
=> ptr is the name of the pointer.
=> datatype is the type of data it is pointing to.
Example:-
 The size of the pointers in C is
equal for every pointer type.
 It does not depend on the
type it is pointing to.

Note :- Size of • 8 bytes for a 64-bit System


• 4 bytes for a 32-bit System
a pointer in C
 pointers store the memory
addresses
 As the space required to store
the addresses of the different
memory locations is the same
Pointer Arithmetics in C

1.Increment/Decrement of a Pointer
2.Addition / Subtraction of integer to a pointer
3.Subtracting two pointers of the same type
Increment/Decrement of a Pointer

When a pointer is
incremented/decremented,
it actually
increments/decrements by
the number equal to the
size of the data type for
which it is a pointer.
Addition / Subtraction of
integer to a pointer

When a pointer is
added/subtracted with an
integer value, the value is
first multiplied by the size
of the data type and then
added/subtracted to the
pointer.
Subtracting two pointers of the same type

 The subtraction of two pointers is possible only when they have the same data
type
 The result is generated by calculating the difference between the addresses of
the two pointers and calculating how many bits of data it is according to the
pointer data type.

Example:-
ptr1 = 2715594428,(pointer of an integer)
ptr2 = 2715594424, ,(pointer of an integer)
ptr1 – ptr2
Subtraction of ptr1 & ptr2 is =1
Pointer to Pointer (Double Pointer)
 Definition:
The pointer to a pointer in C is used when we want to store the address of another
pointer.
 Declaration:
data_type_of_pointer **name_of_variable = & normal_pointer_variable;
 Initialization:
int val = 5;
int *ptr = &val; // storing address of val to pointer ptr.
int **d_ptr = &ptr; // pointer to a pointer declared
// which is pointing to an integer.
Understanding Double pointers
The pointer to a pointer (double pointer) in C is used when we want to
store the address of another pointer.
Generic pointer / Void Pointer
Example:-
It is a pointer #include <stdio.h>
that has no int main()
associated {
data type with int a = 10;
it. char b = 'x';

 It hold an void* p = &a; // void pointer holds address of int 'a'


address of any p = &b; // void pointer holds address of char 'b'
type .
}
Using pointers with arrays

Output
Using pointers with Functions

Output
Structures and Unions
Structures

It is a user-defined data type.


It can be used to group items of possibly different
types into a single type.
Struct keyword is used to define the structure in
the C.
The C dot (.) operator is used to access structure
variables .
Structures

Syntax
struct structure_name {
data_type member_name1;
data_type member_name2;
....
....
};
Structure Decleration

 Structure Variable Declaration with Structure Template :


struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;
 Structure Variable Declaration after Structure Template :
struct structure_name variable1, variable2, .......;
Initialize Structure Members

 Initialization using Assignment Operator :


struct structure_name str;
str.member1 = value1;
str.member2 = value2;
str.member3 = value3;
.
 Initialization using Initializer List :
struct structure_name str = { value1, value2, value3 };
 Initialization using Designated Initializer List :
struct structure_name str = { .member1 = value1, .member2 = value2, .member3 = value3 };
EXAMPLE

Output
Nested Structures
 Embedded Structure Nesting :  Separate Structure Nesting :
struct parent { struct parent {
int member1; struct mem a;
struct member_str member2 { };
int member_str1;
char member_str2; struct mem {
...
int var;
}
Accessing Nested };
...
Members :
}

str_parent.str_child.member;
Example

OUTPUT
Suppose you have to make
2 structures of same type
what will you do ?
We will
do it OUTPUT

like this
Now if you have to make
100 , Then?
Arrays of Structures

An array whose elements are of type structure is called


array of structure. It is generally useful when we need
multiple structure variables in our program.
 Declaration of Array of Structures :
struct structure_name array_name [number_of_elements];
Self Referential
Structures
Self Referential
structures are those
structures that have
one or more pointers
which point to the
same type of
structure, as their
member.
Self
Referential
Structures
Unions

The Union is a user-defined data type in C language that


can contain elements of the different data types just like
structure.
But unlike structures, all the members in the C union are
stored in the same memory location.
Due to this, only one member can store data at the given
instance.
Size of
union
Difference Between Structure and Union
Enumeration
(or enum) in C
Enumeration (or enum)
is a user defined data
type in C. It is mainly
used to assign names to
integral constants, the
names make a program
easy to read and
maintain.
EXAMPLE
Typedef

The typedef is a keyword that is used to provide existing


data types with a new name.
C typedef Syntax :
typedef existing_name alias_name;
File Handling
File handling in C

 File handing in C is the process in which we create, open, read, write,


and close operations on a file.
 Few features of using files are :
 Reusability: The data stored in the file can be accessed, updated, and deleted
anywhere and anytime providing high reusability.
 Portability: Without losing any data, files can be transferred to another in the
computer system.
 Storage Capacity: Files allow you to store a large amount of data without having to
worry about storing everything simultaneously in a program.
C File Operations

Creating a new file – fopen() with attributes as “a” or


“a+” or “w” or “w+”
Opening an existing file – fopen()
Reading from file – fscanf() or fgets()
Writing to a file – fprintf() or fputs()
Moving to a specific location in a file – fseek(), rewind()
Closing a file – fclose()
File Poniter in C

A file pointer is a reference to a particular position


in the opened file.
It is used in file handling to perform all file operations
such as read, write, close, etc.
We use the FILE macro to declare the file pointer
variable.
The FILE macro is defined inside <stdio.h> header
file.
File Poniter

Syntax of File Pointer : Note:-


FILE* pointer_name; File to be
open(file_name) must
Syntax to open a file: be present in the same
directory of the program
File_ptr fopen ( file_name , file_mode ); file you are opening it in

Syntax to close a file: Otherwise you should


use complete file path in
fclose(file_pointer); place of file_name
Opening Modes Description

Searches file. I f the file is opened successfully fopen( ) loads it into memory and sets up
r a pointer that points to the first character in it. I f the file cannot be opened fopen( )
returns NULL.

rb Open for reading in binary mode. I f the file does not exist, fopen( ) returns NULL.

Open for writing in text mode. I f the file exists, its contents are ov erwritten. If the file
w
doesn’t exist, a new file is created. Returns NULL, if unable to open the file.

Open for writing in binary mode. I f the file exists, its contents are ov erwritten. I f the file
wb

File
does not exist, it will be created.

Searches file. I f the file is opened successfully fopen( ) loads it into memory and sets up
a a pointer that points to the last character in it. I t opens only in the append mode. I f the
file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.

Open for append in binary mode. Data is added to the end of the file. I f the file does
ab

Modes
not exist, it w ill be created.

Searches file. I t is opened successfully fopen( ) loads it into memory and sets up a
r+
pointer that points to the first character in it. Returns NULL, if unable to open the file.

Open for both reading and writing in binary mode. I f the file does not exist, fopen( )
rb+ returns NULL.

Searches file. I f the file exists, its contents are overwritten. If the file doesn’t exist a new
w+
file is created. Returns NULL, if unable to open the file.

Open for both reading and writing in binary mode. I f the file exists, its contents are
wb+ ov erwritten. If the file does not exist, it w ill be created.

Searches file. I f the file is opened successfully fopen( ) loads it into memory and sets up
a pointer that points to the last character in it. I t opens the file in both reading and
a+
append mode. I f the file doesn’t exist, a new file is created. Returns NULL, if unable to
open the file.

Open for both reading and appending in binary mode. I f the file does not exist, it will
ab+ be created.
Mode Meaning of Mode During Inexistence of file

r Open for reading. If the file does not exist, fopen( ) returns NULL.

rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.

If the file exists, its contents are overwritten. If the file


w Open for writing.
does not exist, it will be created.

If the file exists, its contents are overwritten. If the file


wb

File
Open for writing in binary mode.
does not exist, it will be created.

Data is added to the end of the file. If the file does


a Open for append.
not exist, it will be created.

Data is added to the end of the file. If the file does


ab

Modes
Open for append in binary mode.
not exist, it will be created.

r+ Open for both reading and writing. If the file does not exist, fopen( ) returns NULL.

Open for both reading and writing in


rb+ binary mode.
If the file does not exist, fopen( ) returns NULL.

If the file exists, its contents are overwritten. If the file


w+ Open for both reading and writing.
does not exist, it will be created.

Open for both reading and writing in If the file exists, its contents are overwritten. If the file
wb+ binary mode. does not exist, it will be created.

Open for both reading and


a+ appending.
If the file does not exist, it will be created.

Open for both reading and


ab+ appending in binary mode.
If the file does not exist, it will be created.
fprintf(para1,para2)

 use to add(write)
data to file
 para1 is file_ptr of
the file in which we
have to write
 para2 is data we
want to write in the
file

Writing
to a file
Appending
to a file
fgets(para1,para2,para3)

 use to read data to file


 para1specifies where to
store the file content
 para2 specifies the
maximum size of data to
read
 para3 is a file pointer that Output
is used to read the file

Reading
to a file
Function Description

Similar to printf(), this function use formatted


fprintf() string and varible arguments list to print output to
the file.

Prints the whole line in the file and a newline at

File handling
fputs()
the end.

Functions fputc() Prints a single character into the file.

Use formatted string and variable arguments list


fscanf()
to take input from a file.

fgets() Input the whole line from the file.

fgetc() Reads a single character from the file.


Function Example

fprintf() fprintf (fptr, "%s %s %s %d", "We", "are", "in", 2012);

File handling
fputs() fputs(str, fp);

Functions fputc() fputc ("a", fptr);

fscanf() fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);

char string[MAX];
fgets()
fgets(string, MAX, fptr);

fgetc() char c = fgetc(fp);


Scope of variable
Local Scope
Global Scope
The variables declared in the The variables declared within the
global scope are called global local scope are called local variables.
variables. Local variables are visible in the block
Global variables are visible in they are declared in and other blocks
every part of the program. nested inside that block.
Global is also called File Scope Local scope is also called Block
as the scope of an identifier scope.
starts at the beginning of the file
and ends at the end of the file.
Global V/S Local Scope

Global Scope Local Scope


Count chars,
spaces, tabs
and newlines
in a file
Dynamic Memory Allocation

 Dynamic Memory Allocation can be defined as a procedure in which


the size of a data structure (like Array) is changed during the runtime.
 There are 4 library functions provided by C defined under <stdlib.h>
header file to facilitate dynamic memory allocation in C programming.
They are:
 malloc()
 calloc()
 free()
 realloc()
Malloc()

 The “malloc” or “memory allocation” method in C is used to


dynamically allocate a single large block of memory with the
specified size.
 Syntax of malloc():
ptr = (cast-type*) malloc(byte-size)
 “Calloc” or “contiguous allocation” method
in C is used to dynamically allocate the
specified number of blocks of memory of
the specified type.
 it is very much similar to malloc() but has two
Calloc() different points and these are:
 It initializes each block with a default value ‘0’.
 It has two parameters or arguments as compare
to malloc().
 Syntax of calloc():
Free()

 “Free” method in C is used to dynamically de-allocate the memory.


 The memory allocated using functions malloc() and calloc() is de-
allocated by free() method.
 It helps to reduce wastage of memory by freeing it.
 Syntax of free():

free(ptr);
Realloc()
 “Realloc” or “Re-allocation” method in C is used to dynamically
change the memory allocation of memory previously allocated
with the help of malloc or calloc.  Syntax of realloc():
ptr = realloc(ptr, newSize);
where ptr is reallocated with new
size 'newSize'.
 There are many functions like :-
 exit()

Note :  malloc()
 calloc()
 realloc()
<stlib.h> … etc which can only be used after
including standard library fumctions header
Standard Library file in program .

functions So to be safe always write #include<stlib.h>


At the beginning of every file handling c
header file program .
PROGRAMMING IN C
Unit 4
Unit-4 Syllabus
 C99 extensions. ‘C’ Standard Libraries: stdio.h, stdlib.h,
assert.h, math.h, time.h, ctype.h, setjmp.h, string.h, stdarg.h,
unistd.h
Basic Algorithms: Finding Factorial, Fibonacci series,
Linear and Binary Searching,
Basic Sorting Algorithms: Bubble sort, Insertion sort and
Selection sort.
Find the square root of a number, array order reversal,
reversal of a string
‘C’ Standard Libraries

The Standard Function Library in C is a huge library of sub-


libraries, each of which contains the code for several
functions.
The definitions of these functions are present in their
respective header files.
In order to use these functions, we have to include the
header file in the program.
S No. Header Files Description
It checks the v alue of an expression that we expect to be
true under normal circumstances.
1 <assert.h>
If the expression is a nonzero v alue, the assert macro does
nothing.
2 <complex.h> A set of functions for manipulating complex numbers.
Defines macro constants specifying the implementation-
3 <float.h> specific properties of the

Header files
floating-point library.
These limits specify that a v ariable cannot store any v alue
beyond these limits, for example-
4 <limits.h>

with
An unsigned character can store up to a maximum v alue
of 255.
The math.h header defines v arious mathematical functions

descriptions 5 <math.h>
and one macro. All the Functions
in this library take double as an argument and return
double as the result.
The stdio.h header defines three v ariable types, sev eral
6 <stdio.h> macros, and v arious
function for performing input and output.
7 <time.h> Defines date and time handling functions.
Strings are defined as an array of characters. The
difference between a character array
8 <string.h>
and a string is that a string is terminated with a special
character ‘\0’.
Sr.No. Function & Description

int isalnum(int c)This function checks whether the passed


1
character is alphanumeric.

int isalpha(int c)This function checks whether the passed


2

Functions in
character is alphabetic.

int iscntrl(int c)This function checks whether the passed


3
character is control character.

<ctype.h> 4
int isdigit(int c)This function checks whether the passed
character is decimal digit.

int isgraph(int c)This function checks whether the passed


5
character has graphical representation using locale.

int islower(int c)This function checks whether the passed


6
character is lowercase letter.
Macro Value Description

Defines the minimum v alue for a


SHRT_MIN -32768
short int.

Defines the maximum v alue for a


SHRT_MAX +32767
short int.

Defines the maximum v alue for an


USHRT_MAX 65535
unsigned short int.

INT_MIN -2147483648 Defines the minimum v alue for an int.

Macros in INT_MAX +2147483647


Defines the maximum v alue for an
int.

<limits.h> UINT_MAX 4294967295


Defines the maximum v alue for an
unsigned int.

Defines the minimum v alue for a long


LONG_MIN -9223372036854775808
int.

Defines the maximum v alue for a


LONG_MAX +9223372036854775807
long int.

Defines the maximum v alue for an


ULONG_MAX 18446744073709551615
unsigned long int.
<math.h>
<time.h>
 The math.h header defines various C
The time.h header mathematical functions .
file contains  These functions are :
definitions of
functions to get and ➢ sqrt()
manipulate date ➢ pow()
and time
➢ sin()
information.
➢ cos()
➢ tan()
Linear Search
 When an array has itmes in random order and we have to find
a target item .
 We start comparing from 1st to last position until there is a
match .
 If target matches returns the index of the position .
 If we reaches the last position and there is no match then we
return -1 .
 This is called the Linear search or Sequential search.
Linerar
Search
Program
Linear Search Algorithm:

Algorithm:(Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n, then jump to step 7
Step 3: if A[i] = x then jump to step 6
Step 4: Set i to i + 1
Step 5: Go to step 2
Step 6: Print element x found at index i and jump to step 8
Step 7: Print element not found
Step 8: Exit
Binary Search
 When an array has elements in sorted order and we have to find a target element .
 We compare the target with the middle element .
 If they match we return its index and stop.
 If it didn’t match then we reuce our array to half accordingle , mens:
 If target > middle , Then new array = (middle+1) to last i.e [middle+1, . , .. , … , …., ….. , last] .
 If target < middle , Then new array = first to (middle-1) i.e [first, . , .. , … , …. , ….. , ….. , middle-1]
And then we repeat the process from start .
 And at last, if only one element left in array and that too didn’t match we return -1.
 This is called Binary Search.
Binary
Search
Program
Binary Search Algorithm:

 Algorithm:(Array A, Value x)
 Step 1: n=len(A)
 Step 2: first = 0
 Step 3: last = n-1
 Step 4: result = -1
 Step 5: While (first <= last)
 Step 6: mid=(first +last)/2
 Step 7: if(A[mid]== x) , Then result = mid and move to Step 10
 Step 8: if (A[mid]< x) , Then first = mid + 1 and repeat from step 5
 Step 9: else , last = mid – 1 and repeat from step 5
 Step 10: Display Result and exit.
Bubble Sort Algorithm

traverse from left and compare adjacent elements and


the higher one is placed at right side.
In this way, the largest element is moved to the rightmost
end at first.
This process is then continued to find the second largest
and place it and so on until the data is sorted.

You might also like