Pic Unit 2 One Shot
Pic Unit 2 One Shot
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 ?
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:
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
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
#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
#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;
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 :
if (marks>= 90){
printf("Grade A");}
The Correct else if (marks >= 80){
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
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++;
}
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 use of goto makes tracing the flow of the program very difficult.
=> 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 ?
or
Array
Declaration data_type array_name
[size1] [size2]...[sizeN];
Array Initialization
With Declaration
data_type array_name [size] = {value1, value2, ... valueN};
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
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
Output
Call By Reference
Output
Call By Value VS Call By Reference
scanf("%[^\n]s", str);
Function Name Description
strcmp(str1, str2)
Copies the contents of string s2 to string s1.
<String.h>
strings are the same it returns 0.
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: 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
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.
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';
Output
Using pointers with Functions
Output
Structures and Unions
Structures
Syntax
struct structure_name {
data_type member_name1;
data_type member_name2;
....
....
};
Structure Decleration
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
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.
File
Open for writing in binary mode.
does not exist, it will be created.
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 If the file exists, its contents are overwritten. If the file
wb+ binary mode. does not exist, it will be created.
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)
Reading
to a file
Function Description
File handling
fputs()
the end.
File handling
fputs() fputs(str, fp);
char string[MAX];
fgets()
fgets(string, MAX, fptr);
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 .
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
Functions in
character is alphabetic.
<ctype.h> 4
int isdigit(int c)This function checks whether the passed
character is decimal digit.
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