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

Introduction to Computer

Uploaded by

Vinu B
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

Introduction to Computer

Uploaded by

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

EM2101 – Coding Techniques -1

• Problem Solving Fundamentals


• C- Programming Fundamentals
• Arrays & Pointers
• Collective Data Types and File Handling
• Advanced Concepts & Application Development
Objectives:

To enable the student to


 Develop algorithms by analyzing the problem
 Develop simple C Programs using basic programming
constructs
 Develop simple C programs to work on arrays and pointers
 Develop simple applications in C using collective data types
 Develop simple applications in C using advanced concepts
Introduction to
Computer
A computer is a digital electronic machine that can be programmed to
carry out sequences of arithmetic or logical operations (computation)
automatically.

Charles Babbage
Component of a Computer
Input Devices/Units: used to provide data and
control signals to an information processing system
(CPU)
Memory units: The Data storage is the
recording of information/data in a storage device
The purpose of the CPU is to process data get it
from input device and send result to output device

• Arithmetic and Logical Units: to perform any kinds of operations/tasks


• Control Units: it coordinates all units and act as central nervous
Output Devices/Units: that is used to receive data
and commands from an information processing
system
 Clearly get requirements from customer. By asking doubts and
Review Meetings
 Computational Power required to solve the problem (Processor &
Memory Specification)
 Exact Solution: 100% satisfy the customer needs
 Approximation Solution for undecidable Problems
 Algorithm Design Techniques
1. Brue Force: Straight Forward Solution
2. Exhaustive Search: List all feasible Solutions and pick optimal solution
3. Divide and Conquer: Complex Problem is sub divided and solve the
sub problems leads to final solution
4. Dynamic Programming: Overlapping of sub problem results tends to
final solution.
5. Iterative Programming: Start with initial Solution and keep on check
any improvement, then no such change improves the value of the
objective function, the algorithm returns the last feasible solution as
optimal and stops
Design an Algorithm: Algorithm + Data Structure = Program
in-term of time and space complexity  Methods of Specifying an Algorithm
 Algorithm: Step by Step Procedure to solve the problem
 Flow chart: pictorial representation to solve the problem
choose any one program language and implement the  Pseudo Code: is a mixture of a natural language and
solution
programming language like construct
 Prove Correctness: to prove that the algorithm yields a required
Finally do the verification and Validation Testing
result for every legitimate input in a finite amount of time
Algorithm: step by step procedure to solve the problem
• An algorithm is a sequence of unambiguous instructions for solving a
problem, i.e., for obtaining a required output for any legitimate input
in a finite amount of time
Properties of an Algorithm:
 Finiteness: must terminate in a finite number of steps

 Definiteness: Each step of the algorithm must be precisely

and unambiguously stated


 Input/output: Each algorithm must take zero, one or more

quantities as input data and produce one or more output


values

 Effectiveness: sufficiently basic and simple steps


 Generality: it can solve all the problems of the same type

for which it is being designed.


Flow chart: pictorial representation to solve the problem

 A flowchart helps to clarify how things are currently working and showed in pictorial manner for better understanding
 Benefits of the flowchart: Makes Logic Clear, Communication, Effective Analysis, Useful in Coding, Proper Testing and Debugging
 Limitations of the flowchart : Complex, Difficult to Modify, No Update.
Pseudo code: is a mixture of a natural
language and programming language
• Initialize: SET,INIT
• Input: READ,GET,OBTAIN
• Process: COMPUTE, CALCULATE, DETERMINE
• Decision: IF, IF…ELSE,IF…ELSEIF…ELSE,SWITCH
• Looping: FOR, WHILE,UNTIL ,REPEAT
• Output: PRINT, DISPLAY, SHOW,WRITE
Program
s
 A program consists of a series of instructions that a computer process​
to perform the required operation.

 Software is a set of instructions, data, or programs used to operate a

computer and execute specific tasks.

 The process of software development is called programming and


the person who develops the computer program are called
programmer
Characteristics of a
Programs
 Portability:- Application/Program/software to run smoothly on a different platform,
Readability:- The programmer should be written in with a more user-friendly approach and
follow the logic of the program by others without much effort. If the programmer is written
structurally, then the process of fixing program errors and debugging made simple
 Efficiency:- Program instructions are needed less amount of memory and processing time to
get the desire result.

 Flexibility: it allows to add new features without changing the existing module

 Generality: It obtains the result by applying valid set of inputs.

 Documentation: It helps the user to fully utilize the functionality of the application
Problem Definition: Sum of two numbers
Flowchart
Algorithm
Step 1 : START
Step 2 : Declare the variables a & b
Step 3: Read the value of variables a & b
Step 4 : Calculate the sum of a & b and Store it into C
Program
Step 5: Print the value of C #include<stdio.h>
Step 6 : STOP int main ()
{
int a, b, c;
Pseudo Code: printf ("\n Enter the First Number a : ");
scanf ("%d",&a);
READ a,b printf ("\n Enter the Second Number b : ");
DETERMINE c=a+b scanf ("%d",&b);
c=a+b;
PRINT c printf (" Sum is %d“,c);
return 0;
}
Exchange of two variables
2. Algorithm Description
1. Algorithm Development
1. Read a and b
2. Assign t=a, a=b and b=t
3. print a and b

3. Design Consideration
• The use of an intermediate temporary
variable allows the exchange of two
variables to proceed correctly.

4. Applications
• Currency Exchange
• Sorting Problem
Insertion Sort

Merge Sort
Count the students – getting pass
mark
Counting problem (count the pass marks if mark > =50 )
1. Read N
2. Assign i=1, counter=0
3. while i <= N do
3.1 Read the mark
3.2 if mark > = 50 then counter=counter+1
3.3 increment i by 1 i.e i=i+1
Done
4. print counter

Design Consideration: Count based on Selection Criteria

Application:
Counting Problems

• Design an algorithm that reads a list of numbers and makes a count of


the number of negatives and the number of non-negative members in
the set.
• Kevin wants to buy a new Honda car. The car is available in 4
different models, and every model has 5 different colors. Find the
total number of choices for Kevin.
• A locker is locked with a four-digit password. The password only
contains numbers from 0−9. How many different password options
will you have if the order of numbers does that matter?
Problem Solving
Counting problem (count the pass marks if mark > =50 )
Exchange of two variables 1. Read N
1. Read a and b 2. Assign i=1, counter=0
2. Assign t=a, a=b and b=t 3. while i <= N do
3. print a and b 3.1 Read the mark
3.2 if mark > = 50 then counter=counter+1
3.3 increment i by 1 i.e i=i+1
Done
4. print counter
Sum of N numbers
1. Read N Reverse the Number
Factorial of given number
2. set sum=0 and i=1 1. Read N
1. Read N
2. set reverse=0
3. Repeat 2. set fact=1, i=1
3. while N > 0 do
3.1 Read Number 3.1 rem=N%10 3. while i <= N do
3.2reverse=reverse*10+rem 3.1 fact=fact*i
3.2 sum=sum+Number
3.3 N=N/10 3.2 increment i by 1
3.3 increment i by 1 Done Done
Until i <= N 4. print reverse 4. print fact
4. print sum
Fibonacci Series Base conversion Sine Series
1. Read N 1. Read angle(x) and N
1. Read N
2. set octal=0, place=1 2. Convert angle into radian. i.e y=x*3.14/100
2. Assign a=0,b=1 and i=3 3. Assign tsin=y,term=y,sign=-1 and i=3
3. while N > 0 do
3. print a and b 3. while i <= N do
3.1 rem=N%8
4. while i <= N do 3.2 octal=octal+ rem*place 3.1 term= term * y * y / ( i * (i-1))
4.1 c=a+b 3.3 N=N/8 3.2 tsin = tsin+ term * sign
3.4 place=place*10 3.3 sign = sign * -1
4.2 Assign a=b, b=c
Done 3.4 increment i by 2 i.e i=i+2
4.3 print c Done
4. print octal
4.4 increment i by 1 4. print tsin
Done
Developed by Dennis Ritchie for the Unix operating system at
Bell Labs in 1972.
It was first implemented on the Digital Equipment Corporation
PDP-11 computer.
Tokens are the basic building blocks in C Language. The program is
constructed using a combination of these tokens.
Keywords are reversed in programming language. It is used to constructed the program
A data type specifies the type of data that a variable can store
such as integer, floating, character, etc.

Example: Literals
int number=90;
int x=071;
int z=Ox1AB;
float=89.7;
char ch=‘y’;
char c[]=“raj”
Variable: The value of the variable is changed during
Identifiers Rules the program execution.
• Identifier has to begin with a Syntax: Data type variable_name = value;
letter or underscore _ Example: int age=20;
age=20; //modified
followed by alphanumeric
Constant: The value of the variable can not be changed
characters i.e fixed
• Cannot use a keyword as Syntax: const datatype constant_name=value;
identifiers. Example: const float PI=3.14;
• It should not contain white Symbolic Constant: using pre-processor directives
space and special characters. Syntax: #define CONSTANT_NAME=value
• case sensitive Example: #define PI=3.14
Enumeration:
• Identifier names are unique. An enumeration type (also called enum) is a data type that
• Identifiers should be written consists of integral constants. (Attaching name to number)
Syntax: enum enumname{const1, const2=value, const3, ... };
in such a way that it is default const1 has the value of 0
meaningful, short, and easy const2 has assigned value
const3 has the value is const2+1 (next value of const2)
to read. Example: enum week{sun,mon,tue,wed,thu,fri,sat}
Input and Output Statement in C : Input-Output simply means to give some
data or information to the computer so that it can perform various types of
actions and produces the desired result, and this result is termed as output
Operators are used to perform operations on variables and values.
#include<stdio.h> #include<stdio.h>
void main() void main() {
{ const volatile int local = 10;
int a,b; printf("Local = %i", local);
printf(“enter the a & b”); int *ptr=(int *)&local;
scanf(“%d%d”,&a,&b); *ptr=100;
printf(“%d”,a+b); printf(" Modified = %i", local);
} }
Note: X=6, and Y=12 binary value respectively X=0110 ,
Y=1100

Operators Meaning Examples


& Bitwise AND X & Y = 0000 1000
| Bitwise OR X | Y = 0000 1110
^ Bitwise exclusive OR X ^ Y = 0000 1010
~ complement ~X = 1111 1001
<< Shift left X << 2 = 0001 1000
>> Shift right Y >> 1 = 0000 0110
Branching statements allow the flow of execution to jump to a different part
of the program. i.e program execution flow is altered based on the condition.
#include<stdio.h>
#include<stdio.h> #include<stdio.h>
void main()
void main() void main()
{
{ {
float salary,hike=20;
int n; int a,b,c;
printf("enter the salary");
printf("Read N"); printf("Read a,b,c");
scanf("%f",&salary);
scanf("%d",&n); scanf("%d%d%d",&a,&b,&c);
if(salary > = 40000){
if(n%2==0) if(a>b && a>c)
float bonus=salary*hike/100.0;
printf("%d is Even",n); printf("A is Big %d",a);
salary=salary+bonus;
else else if(b>c)
}
printf("%d is Odd",n); printf("B is Big %d",b);
printf("%f",salary);
} else
}
printf("C is Big %d",c);
}
#include <stdio.h>
#include<stdio.h> int main() {
void main() int day; case 6:
{ printf("Read day Number"); printf("Saturday");
char cs[10]; scanf("%d",&day); break;
int age; switch (day) { case 7:
printf("Read Citizenship"); case 1: printf("Sunday");
scanf("%s",&cs); printf("Monday"); break;
printf("Read age"); break; default:
scanf("%d",&age); case 2: printf("invalid");
if(cs=="indian"){ printf("Tuesday"); }
if(age>=18) break; }
printf("Eligible for vote"); case 3:
else printf("Wednesday");
printf("Not Eligible"); break;
} case 4:
else printf("Thursday");
printf("Citizenship not matched"); break;
} case 5:
printf("Friday");
break;
Iteration (Looping) is used to execute the block of code several
times according to the condition given in the loop.

#include<stdio.h>
#include<stdio.h>
#include<stdio.h> void main()
void main()
void main() {
{
{ int N; int i=1,N;
int i=1,N;
printf(“enter the N ”); printf(“enter the N ”);
printf(“enter the N ”);
scanf(“%d”,&N); scanf(“%d”,&N);
scanf(“%d”,&N);
for(int i=1;i<=N;i++) while(i<=N){
do{
{ printf(“%d”,i);
printf(“%d”,i);
printf(“%d”,i); i++;
i++;
} }
}while(i<=N);
} }
}
Break Statement: Leave the current block that is breaks/terminates the current
Loop. Also used to leave case statement in switch
Continue Statement: It terminates the current iteration and transfer the control to
the next iteration in loop.
Goto Statement: goto statement is used for altering the normal
sequence of program execution by transferring control to some other
part of the program.(Forward/Backward Jump)

#include <stdio.h>
#include <stdio.h>
void main() {
void main()
int sum=0,n;
{
printf("Sum of First N/2 Numbers?");
int num,i=1;
scanf("%d",&n);
printf("Which table to be Print?");
for(int i = 1; i <= n/2 ; i++){
scanf("%d",&num);
sum = sum+i;
table:
if(i == 5) //stop calculation
printf("%d x %d = %d\n",num,i,num*i);
goto addition;
i++;
}
if(i<=10)
addition:
goto table;
printf("%d", sum);
}
}
Storage Class in C: A storage class defines the scope (visibility) and life-time of
variables and/or functions within a C Program.
Global Scope (extern): Can be accessed anywhere in a program
Block Scope / Local Scope: A Block is a set of statements enclosed within left and right braces
({ and } respectively)
• The auto storage class is the default storage class for all local variables
• The static storage class instructs the compiler to keep a local variable in existence during
the life-time of the program instead of creating and destroying it each time it comes into and
goes out of scope.
• The register storage class is used to define local variables that should be stored in a register
instead of RAM
example:
auto int mark=75;

extern int interest=100;

static int test;

register int i=0;


CODE DECLARE DEFINE INITIALIZ
#include<stdio.h> #include<stdio.h> E

void main() void main() extern int a; Yes No No


{ {
int N; int a; Yes Yes No
auto int a=10,b=a;
printf(“%d”,a+b) printf(“enter the N ”); int a = 1; Yes Yes Yes
} scanf(“%d”,&N); File1.h
for(register int i=1;i<=N;i++) file1.h #include<stdio.h>
{ extern int opengenus; extern int x;
printf(“%d”,i); extern void print()
} og.c {
#include<stdio.h>
} #include "file1.h" printf("\n x = %d", x);
int inc();
void main() int opengenus = 1; }
#include <stdio.h> Main.c
{
extern int x = 32; Main.c #include<stdio.h>
printf(“%d”,inc());
int b = 8; #include "file1.h" #include “File1.h”
printf(“%d”,inc());
void main() { #include <stdio.h> int x;
printf(“%d”,inc());
auto int a = 28; void main(void) extern void print(void);
}
extern int b; { void main()
int inc()
printf("%d", a); printf("%d", opengenus); {
{
printf("x and b : %d,%d",x,b); } x = 10;
static int i=0;
x = 15; print();
return ++i;
printf(" x : %d",x); Compile: gcc Main.c og.c }
}
}
A function is a block of statements that performs a specific task. Break up
complex problem into sub problems. Functions are used to modularize the
program. It provides the reusability
Functions are broadly classified into two types which are as follows −
1. Predefined or Library or Built-in functions
2. User Defined functions

•Predefined or Library functions are already defined in the system libraries. Programmer can
reuse it and helpful to write error free code
#include<stdio.h>
#include<math.h>
void main (){
int x,y;
printf ("enter a number");
scanf ("%d", &x)
y = pow(x,3);
printf("cube = %d", y);
}
•User Defined Functions: These functions must be defined by the
programmer or user.
Function and its Types:
1. Functions with no arguments and no return values.
2. Function with no arguments and return values
3. Functions with arguments and no return values.
4. Functions with arguments and return values

#include<stdio.h>
#include<stdio.h> #include<stdio.h> #include<stdio.h>
int add(int a,int b);
void add(); int add(); void add(int,int);
void main()
void main() void main() void main()
{
{ { {
int a,b;
add(); int r=add(); int a,b;
printf(“enter the a & b”);
} printf(“%d”,r); printf(“enter the a & b”);
scanf(“%d%d”,&a,&b);
void add() } scanf(“%d%d”,&a,&b);
int r=add(a,b);
{ int add() add(a,b);
printf(“%d”,r);
int a,b; { }
}
printf(“enter the a & b”); int a,b;
scanf(“%d%d”,&a,&b); printf(“enter the a & b”); void add(int a, int b)
int add(int a, int b)
printf(“%d”,a+b); scanf(“%d%d”,&a,&b); {
{
} return a+b; printf(“%d”,a+b);
return a+b;
} }
}
In an inline function, a function call is
replaced by the actual program code. Most #include<stdio.h>
of the Inline functions are used for small inline int add(int a,int b){
computations. return a+b;
}
void main()
inline returntype functionname(int a, int {
b) //inline function int a,b;
{ printf(“enter the a & b”);
… scanf(“%d%d”,&a,&b);
return statments; int r=add(a,b);
printf(“%d”,r);
} }
Finding Factorial a Number Using Recursion
Recursive Function:
A Function call itself again
and again to solve the
problem.
ARRAY
An array is a collection of similar(Homogeneous) data elements. The elements of the array are
stored in consecutive memory locations and are referenced by an index

Syntax:
type name[size][][] …={values};
One Dimensional Array
Declaration: type array_name[size];
initialization: array_name={values};

Declaration & Initialization: type array_name[size]={values}; //values are


separated by comma
Example: int a[5]={10,20,30,40,50};
Print the values of for(int i =0;i<=10;i++)
Array Elements printf(marks[i]);
#include<stdio.h>
Arrays are used to store multiple void main()
values in a single variable, instead #include<stdio.h> {
of declaring separate variables for void main() int a[5],i,j,t;
each value { printf("Enter five values : \n");
int a[5],i,max; for(i=0;i<5;i++)
printf("Enter five values : \n"); scanf("%d",&a[i]);
for(i=0;i<5;i++) for(i=0;i<5;i++)
{ {
scanf("%d",&a[i]); for(j=i+1;j<5;j++)
} {
max=a[0]; if(a[i]>a[j])
for(i=1;i<5;i++) {
{ t=a[i];
if(max<a[i]) a[i]=a[j];
{ a[j]=t;
max=a[i]; }
} }
} }
printf("Maximum no is %d",max); printf("Ascending order : \n");
} for(i=0;i<5;i++)
printf("%d\t",a[i]);
}
#include<stdio.h>
void main()
{
int a[20],i,search,n;
printf("How many elements?");
scanf("%d",&n);

printf("Enter array elements:n");


for(i=0;i<n;++i)
scanf("%d",&a[i]);

printf("nEnter element to search:");


scanf("%d",&search);

for(i=0;i<n;++i)
if(a[i]==search)
break;
if(i<n)
printf("Element found at index %d",i);
else
printf("Element not found");
}
#include<stdio.h>
2D Array: A two dimensional array is specified void main()
{
using two subscripts where one subscript denotes int a[3][3],b[3][3],c[3][3],i,j;
row and the other denotes column printf("Enter values of Matrix A : \n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("Enter values of Matrix B : \n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<3;i++) {
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
}
printf("Added Matrix\n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
}
#include<stdio.h>
void main() printf("Matrix Multiplication\n");
{ for(i=0;i<3;i++)
int a[3][3],b[3][3],c[3][3],i,j; {
printf("Enter values of Matrix A : \n"); for(j=0;j<3;j++)
for(i=0;i<3;i++) printf("%d\t",c[i][j]);
for(j=0;j<3;j++) printf("\n");
scanf("%d",&a[i][j]); }
}
printf("Enter values of Matrix B : \n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<3;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
3D Array: A three dimensional array is specified #include<stdio.h>
using three subscripts where first subscript denotes void main()
number of 2D arrays, second subscripts denotes row {
int i, j, k;
and the other denotes column int arr[3][3][3];
printf("Enter the Matrix 3D Array Values : \n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
for(k=0;k<3;k++)
scanf("%d",&a[i][j][k]);
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf("%d\t",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
}
STRING #include <stdio.h>
void main()
String is a collection of characters {
int i = 0, count = 0;
Strings are defined as a null-terminated char s[100];
character array.
printf("Input a string\n");
string is terminated with a special NULL gets(s);
character \0.
while (s[i] != NULL) {
if (s[i] == 'a' || s[i] == 'A' || s[i] == 'e' || s[i] == 'E'
|| s[i] == 'i' || s[i] == 'I' || s[i] =='o' || s[i]=='O'
|| s[i] == 'u' || s[i] == 'U')
count++;
i++;
}

printf("Number of vowels in the string: %d", count);


}

• There are two ways to declare a string in c language.


• By char array Ex: char str[]={‘a’, ‘b’, ‘c’, ‘\0’};
• By string literal Ex: char str[]=“abc”;
UNFORMATTED INPUT AND OUTPUT
#include<stdio.h>
void main(){
char name[50];
printf("Enter your name: ");
gets(name);
printf("Your name is: ");
puts(name); //displays string
}

#include<stdio.h>
void main()
{
int c=getchar();
while(c!=EOF)
{
putchar(c);
c=getchar();
}
}
#include <stdio.h> #include <stdio.h>
#include <stdio.h>
#include <string.h> #include <string.h>
#include <string.h>
void main() int main()
int main()
{ {
{
char s1[30] = "Good Luck"; char s1[10] = "Hello";
char s1[20]="Kamaraj";
char s2[30] = "All of You !"; char s2[10] = "World";
char s2[40]="kamaraj";
strcpy(s1,s2); strcat(s1,s2);
if (strcmp(s1, s2) ==0) //-,+,0 value
printf("String s1 is: %s", s1); printf("string concatenation: %s", s1);
printf("s1 and s2 are equal");
int len=strlen(s1); }
else
printf("Length of s1 is: %d", len);
printf("s1 and s2 are different");
}
#include <stdio.h> }
#include <string.h>
void main()
#include<stdio.h> {
#include<string.h> char s1[10],s2[10];
void main() printf("Enter the string: ");
{ gets(s1);
char s[100]; strcpy(s2,s1);
printf("Enter a string: "); strrev(s2);
scanf("%[^\n]",s); if(!strcmp(s1,s2))
printf("In Lower Case:\n"); printf("string is palindrome");
puts(strlwr(s)); else
} printf("string is not palindrome");
}
#include <stdio.h>
int main() {

char a[10],b[10],rev[10];
int i,j;
printf("Enter the String:"); i=0;
gets(a); while(a[i]!='\0')
printf("Copying a string:"); {
for(i=0;a[i]!=NULL;i++) if(a[i]>='A' && a[i]<='Z')
b[i]=a[i];
a[i]=a[i]+32;
b[i]='\0';
puts(b); i++;
printf("length is %d",i); }
j=0; printf("Lower case is");
for(i=i-1;i>=0;i--) puts(a);
rev[j++]=a[i];
return 0;
rev[j]='\0';
printf("\nReversed String "); }
puts(rev);
Arrays of Strings #include <stdio.h>
int main ()
{
char s[5][10];
• Strings of Strings or an Arrays of Strings would store another individual string.
printf ("Enter the string");
for (int i = 0; i < 5; i++)
Syntax: char str_name[row_size][column_size];
scanf ("%s", s[i]);
row_size specifes the total number of strings column_size
printf ("Display String");
specifies length of the individual strings for (int i = 0; i < 5; i++)
printf ("\n%s", s[i]);
return 0;
}
Pointer
A pointer is a variable that stores the memory Pointer to Pointer: stores address of another pointer variable
address of another variable
Syntax: type *ptr=&variablename;
Example
int a=10;
int *p=&a; // stores the address of a
Benefits:
• Enables us to access a variable that is defined
outside the function. #include<stdio.h>
• Can be used to pass information back and void main()
{
forth between a function and its reference int num= 10;
point. int *ptr=&num;
#include<stdio.h>
• More efficient in handling data tables. printf("%d", *ptr);
} void main()
• Reduces the length and complexity of a {
char *ch = "Hello World";
program. printf("%s", ch);
• Sometimes also increases the execution }
speed.
ARRAY AND POINTER
When an array is declared,
#include <stdio.h>
• The compiler allocates a base address and sufficient amount of
int main ()
storage to contain all the elements of the array in contiguous {
memory locations. char *s[4];
• The base address is the location of the first element (index 0) of printf ("Enter the string");
the array. for (int i = 0; i < 4; i++)
• The compiler also defines the array name as a constant pointer to scanf ("%s", s[i]);
the first element.
printf ("Display String");
x  &x[0]  2500 ; for (int i = 0; i < 4; i++)
printf ("\n%s", s[i]);
p = x; and p = &x[0]; are equivalent. return 0;
We can access successive values of x by using p++ }
or p- - to move from one element to another.
Relationship between p and x: *(p+i) x[i] Array of Strings using pointer
p = &x[0] = 2500 char *str[4] = {
p+1 = &x[1] = 2504 "String",
p+2 = &x[2] = 2508 "Topics",
"Pointers",
p+3 = &x[3] = 2512 "World"
p+4 = &x[4] = 2516 };
Pointer Expressions / Arithmetic
Like other variables, pointer variables can be used in expressions. Data Type Scale Factor
If p1 and p2 are two pointers, the following statements are valid: char 1
int 4
sum = *p1 + *p2 ;
float 4
prod = *p1 * *p2 ;
double 8
prod = (*p1) * (*p2) ; If p1 is an integer pointer, then
*p1 = *p1 + 2; p1++
x = *p1 / *p2 + 5 ; will increment the value of p1 by 4.
We have seen that an integer value can be added to or subtracted
from a pointer variable.
int *p1, *p2 ; #include<stdio.h>
void main()
int i, j; {
p1 = p1 + 1 ; int arr[5] = { 1, 2, 3, 4, 5 };
p2 = p1 + j ; int *ptr = arr;
for(int i=0;i<5;i++)
p2++ ; printf("%d",*(ptr+i));
p2 = p2 – (i + j) ; }
In reality, it is not the integer value which is added/subtracted, but
rather the scale factor times the value.
#include<stdio.h> #include<stdio.h>
void swap(int,int); void swap(int *a,int *b);
void main() void main()
{ {
int a,b; int a,b;
printf(“enter the a & b”); printf(“enter the a & b”);
scanf(“%d%d”,&a,&b); scanf(“%d%d”,&a,&b);
printf(“A is %d B is %d”,a,b); printf(“A is %d B is %d”,a,b);
swap(a,b); swap(&a,&b);
printf(“A is %d B is %d”,a,b);
} }
void swap(int a, int b)
{ void swap(int *a, int *b)
int t=a; {
a=b; int t=*a;
b=t; *a=*b;
printf(“A is %d B is %d”,a,b); *b=t;
} }
Function Pointers
1) Unlike normal pointers, a function pointer points to code, #include <stdio.h>
not data. Typically a function pointer stores the start of int add(int,int);
executable code. int main()
{
2) Unlike normal pointers, we do not allocate de-allocate int a,b;
memory using function pointers. int (*ip)(int,int);
3) A function’s name can also be used to get functions’ int result;
printf("Enter the values of a and b : ");
address. For example, in the below program, we have scanf("%d %d",&a,&b);
removed address operator ‘&’ in assignment. We have also ip=add;
changed function call by removing *, the program still works. result=(*ip)(a,b);
printf("Value after addition is : %d",result);
1.Declaration of a function pointer. return 0;
type *fp(type,..); }
float (*fp) (int , int); int add(int a,int b)
{
2. Declaration of function. int c=a+b;
type func(type,..); return c;
float func( int , int ); }

3. Assigning address of func to the fp pointer


fp=func;
#include <stdio.h>
void fun(int a)
{
printf("Value of a is %d\n", a);
}

int main()
{
void (*fun_ptr)(int) = fun; // & removed

fun_ptr(10); // * removed

return 0;
}
int main()
#include <stdio.h> {
void add(int a, int b) // fun_ptr_arr is an array of function pointers
{ void (*fun_ptr_arr[])(int, int) = {add, sub, mul};
printf("Addition is %d\n", a+b); unsigned int ch, a = 15, b = 10;
}
void sub(int a, int b) printf("Enter Choice: 0 for add, 1 for sub & 2 for
{ multiply\n");
printf("Subtraction is %d\n", a-b); scanf("%d", &ch);
}
void mul(int a, int b) if (ch > 2) return 0;
{
printf("Multiplication is %d\n", a*b); (*fun_ptr_arr[ch])(a, b);
}
}
A null pointer which is a special pointer value that is known not to point
anywhere. This means that a NULL pointer does not point to any valid memory
address.
To declare a null pointer you may use the predefined constant NULL,
int *ptr = NULL;

GENERIC POINTER
• A generic pointer is pointer variable that has void as its
data type. #include<stdio.h>
void main()
• The generic pointer, can be pointed at variables of any {
data type. int x=10;
• It is declared by writing char ch = ‘A’;
void *gp;
void *ptr; gp = &x;
• You need to cast a void pointer to another kind of printf("\n integer value = %d", *(int*)gp);
pointer before using it. gp = &ch;
printf("\n the character %c", *(char*)gp);
• Generic pointers are used when a pointer has to point to }
data of different types at different times.
Dynamic Memory Allocation is a process in which allocate or
deallocate a block of memory during the run-time of a program.
#include<stdio.h> #include<stdio.h>
#include<stdlib.h> #include<stdlib.h>
int main() int main()
{ {
int i, n; int i, n;
int *arr; int *arr;
printf("\n Enter the number of elements: "); printf("\n Enter the number of elements: ");
scanf("%d", &n); scanf("%d", &n);
arr = (int*)malloc(n*sizeof(int)); arr = (int*)calloc(n,sizeof(int));
for (i=0; i<n;i++) for (i=0; i<n;i++){
{ printf("\n Enter the value of %d of the array:",i);
printf("\n Enter the value of %d of the array:",i); scanf("%d",&arr[i]);
scanf("%d",&arr[i]); }
} printf("\n The array contains \n");
printf("\n The array contains \n"); for (i=0; i<n;i++)
for (i=0; i<n;i++) printf("%d",arr[i]);
printf("%d",arr[i]); free(arr);
return 0; return 0;
} }
#include <stdio.h>
#include <stdlib.h>
int main() { // rellocating the memory
int *ptr, i , n1, n2; ptr = realloc(ptr, n2 * sizeof(int));
printf("Enter size: "); for (i=0; i<n2;i++)
scanf("%d", &n1); {
ptr = (int*) malloc(n1 * sizeof(int)); printf("\n Enter the value of %d of the
for (i=0; i<n1;i++) array:",i);
{ scanf("%d",&ptr[i]);
printf("\n Enter the value of %d of the }
array:",i); printf("\n The array contains \n");
scanf("%d",&ptr[i]); for (i=0; i<n2;i++)
} printf("%d",ptr[i]);
printf("\n The array contains \n"); free(ptr);
for (i=0; i<n1;i++) return 0;
printf("%d",ptr[i]); }
printf("\nEnter the new size: ");
scanf("%d", &n2);
Structure: A structure is a user defined data type or derived data type
that can be used to group of variables of different types into a single type
• A structure is declared using the keyword
struct followed by a structure name. All the
variables of the structures are declared within
the structure. A structure type is defined by
using the given syntax.
Syntax:
struct struct-name Example struct student
{ {
data_type var-name; int r_no;
data_type var-name; char name[20];
... char course[20];
}; float fees;
};
Methods of Declaring a Structure
Variable 3
1 struct
struct student student
{ int r_no;
{ int r_no; char name[20];
char name[20]; char
char course[20];
course[20]; }; float fees;
float fees; struct student
}student1; student1,student2,student3;
4
2 struct
struct student
{ int r_no;
student
{ int r_no; char name[20];
char name[20]; char
char course[20];
course[20]; } float fees;
float fees;
}student1,student2,student3; struct student
student1={23456,”Priya”,”BCA”,25000.75};
#include<stdio.h> printf(“\n ***STUDENT’S DETAILS ***”);
int main() printf(“\n ROLL No. = %d”, stud1.roll_no);
{ printf(“\n NAME. = %s”, stud1.name);
struct student printf(“\n Fees. = %f”, stud1.fees); printf(“\
{ n DOB. = %s”, stud1.DOB);
int roll_no; }
char
name[80];
float fees;
char DOB[80];
};
Output:
struct student
Enter the roll number: 1234
stud1; Enter the name : Ajay
printf(“\n Enter the roll number : Enter the fees : 34500.78
“); scanf(“%d”, &stud1.roll_no); Enter the DOB :
printf(“\n Enter the name : “); 23.05.1998
scanf(“%s”, stud1.name); ***STUDENT’S DETAILS ***
printf(“\n Enter the fees : “); ROLL No. = 1234
scanf(“%f”, &stud1.fees); NAME. = Ajay
printf(“\n Enter the DOB : ROLL No. = 34500.781250
ROLL No. = 23.05.1998
“); scanf(“%s”, stud1.DOB);
#include<stdio.h
> struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
main()
{ struct student stud1, *ptr_stud1;
Accessing ptr_stud1 = &stud1;
ptr_stud1->r_no = 01;
Structure strcpy(ptr_stud1->name, "Rahul");
strcpy(ptr_stud1->course,
using "BCA"); ptr_stud1->fees = 45000;
Pointer printf("\n DETAILS OF
STUDENT");
printf("\n -");
printf("\n ROLL NUMBER = %d", ptr_stud1->r_no);
printf("\n NAME =%s ", puts(ptr_stud1->name));
printf("\n COURSE = %s", puts(ptr_stud1->course));
} printf("\n FEES = %f", ptr_stud1->fees);
Array of
Structure
emp[0 emp[1
] ]

int id char float int id char float


name[5] salary name[5] salary
struct emloyee
{ int id; sizeof(emp) = 26 bytes
char name[5];
float salary; sizeof(emp[2]) = 4 + 5 + 4 = 13 bytes
}struct employee emp[2];
for(i = 0; i < 2; i++ )
{
printf("\nEnter details of student %d\n\n",
#include<stdio.h> i+1); printf("Enter name: ");
#include<string.h> scanf("%s", arr_student[i].name);
printf("Enter roll no: ");
Array
struct student
scanf("%d", &arr_student[i].roll_no);
{
Structur
char name[20];
printf("Enter marks: ");

e
int roll_no; float }
scanf("%f", &arr_student[i].marks);

Program
marks; printf("\n");
}; printf("Name\tRoll no\tMarks\n");
int main() for(i = 0; i < 2; i++ )
{ {
struct student arr_student[2]; printf("%s\t%d\t%.2f\n", arr_student[i].name,
arr_student[i].roll_no,
int i;
arr_student[i].marks);
}
return 0;
#include<stdio.h> Output:
struct address ******
{ Enter employee information Name/ City/ PIN Code/
char Phone Number?
city[20]; int Kani
pin; Madurai
char 600009
999411
phone[14];
7284
Write a program }; Printing the employee information....
to read and struct employee name: Kani
display { City: Madurai
information of an
char name[20]; Pincode: 600009
employee using
structure within a struct address Phone:
structure add; 9994117284
};
printf("Enter
void main () employee information Name/ City/ PIN Code/ Phone Number?\
{ n"); scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin,
emp.add.phone);
struct employee printf("Printing the employee information....\n");
printf("name:
emp; %s\nCity: %s\nPincode: %d\nPhone:
%s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}
#include<stdio.h>
typedef struct
{
int x;
int
y;
}POINT;
void
Passing display(POI
Structure NT);
void main()
as {
arguments POI
NT
p1 =
{2,
3};
displ
Self Referential Structures: contain
reference to data of
struct Node
its same type
{
int data;
struct Node *next;
};
Dynamic data structures : Structures with pointer members that
refer to the same structure.
• Arrays and other simple variables are allocated at block
entry.
• But dynamic data structures require storage management
routine to explicitly obtain and release memory.
int main()
// A simple C program for traversal of a linked list {
struct Node* head = NULL;
struct Node* second = NULL;
#include <stdio.h> struct Node* third = NULL;
#include <stdlib.h>
// allocate 3 nodes in the heap
struct Node { head = (struct Node*)malloc(sizeof(struct Node));
int data; second = (struct Node*)malloc(sizeof(struct Node));
struct Node* next; third = (struct Node*)malloc(sizeof(struct Node));
};
head->data = 1; // assign data in first node
head->next = second; // Link first node with second
void printList(struct Node* n)
{ second->data = 2; // assign data to second node
while (n != NULL) { second->next = third;
printf(" %d ", n->data);
n = n->next; third->data = 3; // assign data to third node
} third->next = NULL;
}
// Function call
printList(head);
return 0;
}
//Accessing union through pointer:

Union #include <stdio.h>

#include <stdio.h> union point{


#include <stdio.h>
union point{ typedef union int x,y;

int x,y; { }p;


int x,y; void main() {
}p; }POINT;
void main() { union point *ptr=&p;
void main() { printf("Enter the value of x or y:");
printf("Enter the value of x or y:");
POINT p;
scanf("%d",p.x); scanf("%d",&ptr->x);
printf("Enter the value of x or y:");
printf("\nDisplay the point:"); scanf("%d",&p.x); printf("\nDisplay the point:");
printf("\nDisplay the point"); printf("%d %d",ptr->x,ptr->y);
printf("%d %d",p.x,p.y);
printf("%d %d",p.x,p.y);
} } }
Nested derived data types: either structure within union or union with structure or both

struct store { int main ( )


struct store double price; //8 Bytes
{ {
union {
double price; // struct { struct store s;
8 bytes char *title; // char *title; //8 Bytes s.item.book.title = “Programming in C”;
8 bytes char *author; // s.item.book.author= “bmkv”;
char *author; //8 Bytes s.iteam.book.num_pages = 786;
8 bytes int nt num_pages; //4 Bytes
num_pages; // 4 bytes printf(“%s \n ”, s.item.book.title);
} books; printf(“%ld \n ”, sizeof(s));
int color;
struct { return 0;
// 4 bytes
int color; //4 Bytes }
int size;
int size; //4 Bytes
// 4 bytes
char *design;//8 Bytes Output :
char *design;
} shirt; Programming in C
// 8 bytes
}item; 28
};
};
Enumeration:
An enumeration type (also called enum) is a data type that consists of integral constants. (Attaching name to
number) Enum used in looping
Syntax: enum enum_name{const1, const2=value, const3, ... }; for(int i=mon;i<=sun;i++)
printf(“%d”,i);
default const1 has the value of 0
const2 has assigned value Enum used in switch
const3 has the value is const2+1 (next value of const2)
Example: switch(day)
#include<stdio.h> {
case mon:
enum week{mon=1,tue,wed,thu,fri,sat,sun}; case tue:
case wed:
void main() case thu:
case fri:
{ printf(“working day”);
break;
enum week day; case sat:
day = wed; case sun:
printf(“holiday”);
printf("%d",day); Break;
}
}
File handling in C
• A file is a collection of data stored on a secondary storage device like
hard disk.
• A file is basically used in real life applications that involve large
amounts of data input and in such situations the console oriented I/O
operations pose two major problems:
• First, it becomes cumbersome and time consuming to handle huge
amount of data through terminals.
• Second, when doing I/O using terminal, the entire data is lost when
either the program is terminated or computer is turned off. Therefore,
it becomes necessary to store data on a permanent storage (the disks)
and read whenever necessary, without destroying the data
#include <stdio.h>
main()
{ Two kinds of files:
int i; – Textfile :: contains ASCII codes only EOF character can be
fprintf(stdout,"Give value of i \n"); checked
fscanf(stdin,"%d",&i); – Binaryfile :: can contain non-ASCII characters. Ex: Image,
fprintf(stdout,"Value of i=%d \n",i); audio, video, executable, etc.
fprintf(stderr,"No error: message.\n"); To check the end of file here, the file size value (also stored on
} disk) needs to be checked. feof
Function Description
fopen() opens new or existing file

fprintf() write data into the file


fscanf() reads data from the file

fputc() writes a character into the file

fgetc() reads a character from file

fgets() reads a string from file


fputs() writes a string to file
getw() Read integer from the file
putw() Write an integer into the file
fread() Reads data from the file

fwrite() Write data into the file

fseek() sets the file pointer to given


position
ftell() returns current position

rewind() sets the file pointer to the


beginning of the file
fclose() closes the file
Steps in File handling
• Declare the File Pointer: FILE *fp=NULL;
Other file operations:
• Open the file with specified mode: fp=fopen(“filename.txt”, “mode”);
fseek( fp, Position, SEEK_SET );
• Process the file using following functions
ftell(fp)
• fscanf and fprintf
rewind(fp)
Syntax: fscanf(fp, “format specifiers”, &variables);
Example: fscanf(fp, “%s %d”,&name,&rollno);
#include<stdio.h>
Syntax: fprintf(fp, “format specifiers”, variables);
void main()
Example: fprintf(fp, “%s %d”,name,rollno);
{
• fgetc and fputc
FILE*fp=fopen("1.txt",“w");
Syntax: ch=fgetc(fp);
fseek(fp, 5,SEEK_SET);
Syntax:fputc(ch,fp);
fputs(“Soul”);
• fgets and fputs
printf(“Pos is %ld”,ftell(fp));
syntax: fgets(str,number of characters, fp);
rewind(fp);
syntax:fputs(str,fp);
printf(“Pos is %ld”,ftell(fp));
• fread and fwrite
fclose(fp);
Syntax: fread(void *ptr, size_t size, size_t n, FILE *fp);
}
Example:int a[5];
Input:1.txt
fread(a,sizeof(int),2,fp);
Good is make happy
Syntax: fwrite(const void *ptr, size_t size, size_t n, FILE *fp);
Output:1.txt
Example:
Good soul is make happy
int a[]={10,20};
Pos is 9
fwrite(a,sizeof(int),2,fp);
Pos is 0
• Close the file: fclose(fp);
1 2 3
#include<stdio.h> #include<stdio.h> #include<stdio.h>
void main() void main() void main()
{ { {
FILE*fp=fopen("1.txt","r"); FILE*fp1=fopen("1.txt","r"); FILE*fp1=fopen(“in.txt","r");
while(1) FILE*fp2=fopen("2.txt","w"); FILE*fp2=fopen("res.txt","w");
{ char line[100]; int a,b;
char ch=fgetc(fp); while(fgets(line,80,fp1)!=NULL) fscanf(fp1,"%d %d",&a,&b);
if(ch==EOF) { fprintf(fp2,"Result is %d",a+b);
break; fputs(line,fp2); fclose(fp1);
printf("%c",ch); fclose(fp2);
} }
} fclose(fp1); #include<stdio.h>
fclose(fp); fclose(fp2); 4
void main()
} } {
FILE*fp1=fopen("src.txt","r");
FILE*fp2=fopen("dst.txt","w");
1)Input: 2)input: 3) Input 4)input
char a[100];
1.txt 1.txt in.txt src.txt
fread(a,sizeof(char),3,fp1);
Welcome to KCET Welcome to KCET 10 20 God is great
fwrite(a,sizeof(char),3,fp2);
CSE CSE
fclose(fp1);
Output: output: 2.txt output: res.txt output: dst.txt
fclose(fp2);
Welcome to KCET Welcome to KCET Result is 30 God
}
CSE CSE
BIT-FIELD #include <stdio.h>
The idea of bit-field is to use memory
struct date
efficiently when we know that the value of a {
field or group of fields will never exceed a int d : 5; // d range is 0 - 31, so 5 bits are sufficient
limit or is within a small range. int m : 4; // m range is 0 - 15, so 4 bits are sufficient
Bit fields are used when the storage of our int y;
program is limited. };
int main()
Need of bit fields in C programming language: {
• Reduces memory consumption. printf("Size of date is %lu bytes\n", sizeof(struct date));
• To make our program more efficient and flexible. struct date dt = { 15, 07, 2023 };
• Easy to Implement printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
Syntax: }
struct tagname
{ Output:
type member: width_of_bit-field; Size of date is 8 bytes
Date is 15/07/2023
typedef
The typedef is a keyword
used in C programming to
provide some meaningful
names to the already existing
type/variable in the C
Program.

Syntax :
typedef <existing_name> <alias_name> ;
MACRO is defined with the pre-processor directive.
• Macros are pre-processed which means that all the macros would be
processed before your program compiles

Types of Macro
Object Like Macro Function Like Macro

Syntax: #define Macrofunction(args) operations


Example: #define sum(a,b) a+b
Condition Like Macros
Variable length Arguments #include <stdio.h>
#include <stdarg.h>
double average ( int num, ... )
• Creating a Variadic Function {
• Use standard header stdarg.h va_list ap;
• 4 macros (not prototypes) needed from this double sum = 0;
header file va_start ( ap, num ); //initializes, store all values
va_list int x;
va_start for ( x = 0; x < num; x++ )
va_args sum += va_arg ( ap, double );
va_end va_end ( ap );
return sum/num;
}
int main()
{
printf( "%f\n", average ( 3, 12.2, 22.3, 4.5 ));
printf("%f\n", average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ));
return 0;
}
Command Line Arguments are passed to the main() method.
In order to implement command line arguments, generally, two parameters
are passed into the main function:
Number of command line arguments (argc): It refers to “argument count”.
The list of command line arguments (argv): It refers to “argument vector”.
The basic syntax is: #include <stdio.h>
#include <conio.h>
int main( int argc, char *argv[] )
void main(int argc, char *argv[])
{ {
. printf(“No of cmd args are %d”,argc);
for(int i = 0; i < argc; i++)
.
printf("%s\t", argv[i]);
// BODY OF THE MAIN FUNCTION }
.
Input: ./a.out 2 ram raj
.
Output:
} No of cmd args are 4
./a.out 2 ram raj
Modular programming is a software design technique that
How do you solve a big/complex?
emphasizes separating the technique that emphasizes Divide it into small tasks and solve each task.
separating the functionality of a functionality of a program into Then combine these solutions.
Modules can be written and tested separately
independent, interchangeable modules, such that each Modules can be reused
contains everything necessary to execute only one aspect of Large projects can be developed in parallel
Reduces length of program, making it more
the desired functionality.
readable
Promotes the concept of abstraction
Features of Modular Programming  A module hides details of a task
Helps manage complexity  We just need to know what this module
 Smaller blocks of code does
 Easier to read  We don’t need to know how it does it
Encourages re-use of code
 Within a particular program or across different programs
Allows independent development of code
User-defined libraries
User defined libraries are created and maintained by programmers.
They can contain user defined functions to perform specific tasks

To add a user-defined library to your program, you need to perform the following steps:
1. Write the code for the library: This involves writing the functions that will be included
in the library.
2. Compile the code: Compile the code for the library into an object file (usually with
filename.o or .obj extension) using the appropriate compiler.
3. Create the library: create a library file (usually with filename. a extension ) from the
object file. The library file contains the compiled code for the functions in the library.
4. Link the library to your program: To use the library in your program, you need to link
the library file to the program at compile time. This can be done using linker scripts.
5. Include the header file: In order to call the functions in the library, you need to
include the header file for the library in your program
Example of how to add a user-defined library in C: (Using Command Prompt in Windows or linux)
ar stands for "archiver", which is a tool used to manage libraries in C
•r: replace existing files in the library
•c: create the library if it does not exist
•s: write an index to the archive, allowing faster access to its contents
•libmylib.a is the name of the library file that will be created,
•mylib.o is the name of the object file that will be included in the library.

•gcc is the Gnu Compiler Collection, which includes a C compiler


•-L. specifies the directory where the library file is located. The . means the current
directory.
•-lmylib specifies the library to be linked with the program.
•-o main specifies the name of the output file
5. Include mylib.c in the header file
// main.c
#include <stdio.h>
#include "mylib.c"
int main(){ 6. Run the main.c
print_hello(); C:\> ./main
return 0; Output:
} Hello, World!

You might also like