mid-2 c programme

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Unit-III

1. 1D Array Declaration, initialization and accessing with an example program?


Collection of homogeneous elements stored in a contiguous memory location and
referred through a same name.
Key Points:
• Fixed Size: Size must be specified during declaration.
• Homogeneous Elements: All elements must be of the same type.
• Efficient Access: Direct access using indices.
• Memory Contiguity: Elements are stored sequentially in memory.

Declaration:
Syntax:
Datatype arr_name[size];
Ex:
int arr[10]; //It allocated 40 bytes of memory and allows to store
10 integer elements.

Initialization can be done in two ways


1) Compile time initialization: Assigning the values into an array at the time of
declaration is called compile time initialization.
Syntax:
Datatype arrName[size]={value1,value2,…..valueN};
Ex: int marks[6]={56,78,89,90,76,67};

2) Runtime initialization: Assigning the values into an array during the program
execution is called runtime initialization.
Ex:
int marks[6],i;
for(i=0;i<6;i++)
Scanf(“%d”,&marks[i]);

Accessing of elements of an array:


int marks[6]={56,78,89,90,76,67};
for(i=0;i<6;i++)
printf(“%d “,marks[i]);

1D Array Programs
a) Binary Search
Binary search is a more efficient searching technique but works only on sorted arrays. It
repeatedly divides the search interval in half.
Steps:
1) Set the low and high pointers to the beginning and end of the array.
2) Find the middle index using (low+high)/2.
3) Compare the middle element with the target:
a) If it matches, return the index.
b) If the target is smaller, adjust the high pointer to mid−1.
c) If the target is larger, adjust the low pointer to mid+1.
4) Repeat until the element is found or the pointers cross.
#include <stdio.h>
int binarySearch(int[],int,int); //function prototype

int binarySearch(int arr[], int n, int target) //function definition


{
int low = 0, high = n - 1;

while (low <= high)


{
int mid = (low + high) / 2;

if (arr[mid] == target)
{
return mid; // Element found.
}
if (arr[mid] < target)
{
low = mid + 1; // Search in the right half.
}
else
{
high = mid - 1; // Search in the left half.
}
}
return -1; // Element not found.
}
int main()
{
int i,key,n;
printf("Enter the Size of the Array\n");
scanf("%d",&n);
int arr[n];

//Read the Array Elements in a sorted order only


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

printf("Enter the Key Element to search in the given array\n");


scanf("%d",&key);

int index=binarySearch(arr,n,key);

if(index==-1)
printf("%d is not found in the given array",key);
else
printf("%d is found at %d index in the given array",key,index);

return 0;
}
b) Linear Search
Linear search is the simplest searching technique. It traverses the array sequentially and
compares each element with the target element until a match is found or the array ends.
Steps:
1) Start from the first element.
2) Compare the current element with the target.
3) If a match is found, return the index.
4) If no match is found after traversing the entire array, return -1 or a failure message.
Advantages:
Simple and easy to implement.
Does not require the array to be sorted.
Disadvantages:
Inefficient for large datasets.
#include <stdio.h>

int linearSearch(int arr[], int n, int target)


{
for (int i = 0; i < n; i++)
{
if (arr[i] == target)
{
return i; // Return the index of the found element.
}
}
return -1; // Element not found.
}

int main()
{
int i,key,n;
printf("Enter the Size of the Array\n");
scanf("%d",&n);
int arr[n];

//Read the Array Elements


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

printf("Enter the Key Element to search in the given array\n");


scanf("%d",&key);

int index=linearSearch(arr,n,key);

if(index==-1)
printf("%d is not found in the given array",key);
else
printf("%d is found at %d index in the given array",key,index);
return 0;
}
c) Bubble sort
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares
adjacent elements, and swaps them if they are in the wrong order. This process is
repeated until the list is sorted.
Steps:
1) Start with the first element and compare it with the next element.
2) If the first element is greater than the second, swap them.
3) Move to the next pair and repeat until the last element of the array.
4) Repeat the entire process for n−1 passes, where n is the number of elements.
5) After each pass, the largest unsorted element "bubbles up" to its correct position.
#include <stdio.h>

void bubbleSort(int arr[], int n)


{
for (int i = 0; i < n - 1; i++)
{
int swapped = 0; // Optimization to stop early if no swaps occur.
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// Swap arr[j] and arr[j+1].
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1;
}
}
if (!swapped)
break; // Break if no swaps occurred in this pass.
}
}

void printArray(int arr[], int n)


{
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}

int main()
{
int i,n;
printf("Enter the Size of the Array\n");
scanf("%d",&n);
int arr[n];
//Read the Array Elements
for(i=0;i<n;i++)
scanf("%d",&arr[i]);

bubbleSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);

return 0;
}

d) Selection sort
Selection Sort divides the array into a sorted and an unsorted region. It repeatedly selects
the smallest (or largest) element from the unsorted region and moves it to the sorted
region.
Steps:
1) Start with the first element and find the smallest element in the unsorted region.
2) Swap the smallest element with the first element of the unsorted region.
3) Move the boundary between the sorted and unsorted regions by one element.
4) Repeat until the entire array is sorted.

Advantages:
1) Performs well on small datasets.
2) Simpler to implement than other algorithms.

Disadvantages:
1) Not suitable for large datasets due to its quadratic time complexity.

Main Logic:
void selectionSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int minIndex = i;

// Find the index of the smallest element.


for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
// Swap the smallest element with the first element of the unsorted region.
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
e) Sum of array elements
Main Logic:
int marks[6]={56,78,89,90,76,67};
int sum=0;
for(i-0;i<6;i++)
{
sum=sum+marks[i];
}
printf(“Total Marks: %d”,sum);

f) Maximum and minimum elements of an array

g) Reversing Array elements


Main Logic:
int marks[6]={56,78,89,90,76,67};

for(i=0;i<n/2;i++)
{
int temp=marks[i];
marks[i]=marks[n-i-1];
marks[n-i-1]=temp;
}
2. 2D Array Declaration, initialization and accessing with an example program?
2D array is nothing elements are stored in the form rows and columns.
Declaration:
Syntax: data_type array_name[rows][columns];
rows – Number of rows.
columns – Number of columns
Initialization:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Accessing of 2D array elements:
int value = matrix[1][2]; // Accesses element at 2nd row, 3rd column (6)

Ex:
#include <stdio.h>
int main()
{
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Display the 2D array
printf("2D Array Elements:\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}

return 0;
}

3. 2D Array Programs
a) Matrix Multiplication
b) Matrix Addition
c) Trace of a matrix
Refer the Material or Lab Record to refer these programs.

4. String handling functions


C provides a set of standard library functions to handle strings, declared in the <string.h>
header file. Strings in C are arrays of characters ending with a null character \0.
Some of the String handling functions are
Unit-IV
1. types of functions
Function is a block of code that can be used to perform a specific task.
In C programming a function includes the following
Function prototype
Function definition
Function call
Types of functions
Functions are classified into two types.
1) Built in functions: Built-in functions in C are pre-defined functions provided by
C's standard library.
printf(), scanf(), pow(),sqrt(), gets(), puts()……
2) User defined functions: function defined by the user as per their business
requirements.
void wish() //function definition
{
printf(“Good Morning”);
}
int main()
{
wish(); //function call
return 0;
}

2. factorial using Recursion and without Recursion


Recursion: a function is calling itself is called recursion.
By using Loop:
#include <stdio.h>
int main()
{
int num, factorial = 1;

// Input from user


printf("Enter a number: ");
scanf("%d", &num);

// Calculate factorial
for (int i = 1; i <= num; i++)
{
factorial *= i;
}

// Display result
printf("Factorial of %d is %d\n", num, factorial);

return 0;
}
Recursion:
#include <stdio.h>
// Recursive function to calculate factorial
long long factorial(int n)
{
if (n == 0 || n == 1)
{
return 1; // Base case
}
else
{
return n * factorial(n - 1); // Recursive call
}
}

int main()
{
int num;

// Input from user


printf("Enter a number: ");
scanf("%d", &num);

// Display result
printf("Factorial of %d is %lld\n", num, factorial(num));

return 0;
}

3. Fibonacci series using Recursion and without Recursion


#include <stdio.h>

// Recursive function for Fibonacci


int fibonacci(int n)
{
if (n <= 1)
{
return n; // Base case
}
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive call
}

int main()
{
int n, i;

// Input from user


printf("Enter number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series (Recursion): ");
for (i = 0; i < n; i++)
{
printf("%d ", fibonacci(i));
}

return 0;
}

Fibonacci Series without Recursion (Iterative Approach)


#include <stdio.h>
int main()
{
int n, i;
int t1 = 0, t2 = 1, nextTerm;

// Input from user


printf("Enter number of terms: ");
scanf("%d", &n);

printf("Fibonacci Series (Iterative): ");


for (i = 0; i < n; i++)
{
printf("%d ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}

return 0;
}
Output:
Enter number of terms: 7
Fibonacci Series (Iterative): 0 1 1 2 3 5 8

4. swapping of two numbers (all three programs using functions)


Call by value
#include<stdio.h>
void swap(int,int);
void swap(int a,int b)
{
int temp=a;
a=b;
b=temp;
}
int main()
{
int x,y;
scanf("%d%d",&x,&y);
printf("Before Swap call\n");
printf("%d %d\n",x,y);
swap(x,y);
printf("After Swap call\n");
printf("%d %d\n",x,y);
return 0;
}
Call by reference:
#include<stdio.h>
void swap(int*,int*);
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int x,y;
scanf("%d%d",&x,&y);
printf("Before Swap call\n");
printf("%d %d\n",x,y);
swap(&x,&y);
printf("After Swap call\n");
printf("%d %d\n",x,y);
return 0;
}

5. storage classes
Storage classes in C define the scope, lifetime, visibility, and default initial value of
variables. The main storage classes in C are:
1) Automatic (auto)
2) Register (register)
3) Static (static)
4) External (extern)

1. Automatic Storage Class (auto)


Scope: Local to the block where it is defined.
Lifetime: Until the block/function ends.
Default Value: Garbage value.
Keyword: auto (optional, as it is the default for local variables).
Example:

#include <stdio.h>
void autoExample()
{
auto int x = 10; // 'auto' is optional
printf("Automatic variable x = %d\n", x);
}
int main()
{
autoExample();
return 0;
}
Output:
Automatic variable x = 10

2. Register Storage Class (register)


Scope: Local to the block where it is defined.
Lifetime: Until the block/function ends.
Default Value: Garbage value.
Keyword: register.
Purpose: Suggests storing the variable in a CPU register for faster access.
Example:
#include <stdio.h>
void registerExample()
{
register int x = 5; // Suggest to store 'x' in a CPU register
printf("Register variable x = %d\n", x);
}

int main()
{
registerExample();
return 0;
}
Output:
Register variable x = 5

3. Static Storage Class (static)


Scope: Local to the block where it is defined (for local variables) or global (for global
variables).
Lifetime: Throughout the program's execution.
Default Value: 0 for numeric types.
Keyword: static.
Purpose: Retains its value between function calls.
Example:
#include <stdio.h>
void staticExample()
{
static int x = 0; // Static variable retains value between calls
x++;
printf("Static variable x = %d\n", x);
}
int main()
{
staticExample();
staticExample();
staticExample();
return 0;
}
Output:
Static variable x = 1
Static variable x = 2
Static variable x = 3

4. External Storage Class (extern)


Scope: Global (accessible across multiple files).
Lifetime: Throughout the program's execution.
Default Value: 0 for numeric types.
Keyword: extern.

Purpose: Declare a global variable or function defined in another file.


Example (with two files):
File1.c:
#include <stdio.h>
int x = 10; // Global variable
void display()
{
printf("Value of x = %d\n", x);
}

File2.c:
#include <stdio.h>
#include "File1.c"
extern int x; // Declare global variable
void display();
int main()
{
printf("Accessing x in another file: %d\n", x);
display();
return 0;
}
Output:
Accessing x in another file: 10
Value of x = 10

6. Categories of functions
According to the arguments and return values, there are four types of user defined
functions.
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions with no arguments and return values.
Unit-V
1. pointer Declaration, initialization and accessing with an example program?
Pointer is also a variable used to store the address of another variable.
Operators used in pointers:
1) & -> Address of operator
2) * -> Dereferce or Value at the address operator
#include<stdio.h>
int main()
{
int x=10,y=20;
int *p,*q;
p=&x;
q=&y;
printf("%d %d \n",x,y);
printf("%d %d\n",*p,*q);
}

2. Call by value and Call by reference

3. File handling functions


File: In C, a file is a container used to store data permanently on storage devices like
hard drives. It allows data to persist even after the program ends, unlike variables that
lose their values once the program exits.
There are two types of files
1) Text files: It stores data in the form of character by character
Ex: .txt, .doc, .csv…..
2) Binary files: It stores the data in the form of 0 and 1’s.
Ex: .jpeg, .png, .mp4, .mp3,…..
Function Description Syntax Example
FILE *fopen(const char
Opens a file in
fopen() *filename, const char fopen("data.txt", "w");
specified mode.
*mode);
fclose() Closes an opened file. int fclose(FILE *stream); fclose(file);
Writes formatted text int fprintf(FILE *stream, fprintf(file, "Hello %s",
fprintf()
to a file. const char *format, ...); "World");
Reads formatted data int fscanf(FILE *stream, fscanf(file, "%d",
fscanf()
from a file. const char *format, ...); &num);
Reads a line from a char *fgets(char *str, int n,
fgets() fgets(buffer, 100, file);
file. FILE *stream);
Writes a string to a int fputs(const char *str,
fputs() fputs("Hello", file);
file. FILE *stream);
Reads a single
fgetc() int fgetc(FILE *stream); char c = fgetc(file);
character from a file.
Writes a single int fputc(int char, FILE
fputc() fputc('A', file);
character to a file. *stream);
Checks if end of file is
feof() int feof(FILE *stream); if (feof(file)) break;
reached.
Moves file pointer to int fseek(FILE *stream, long fseek(file, 0,
fseek()
specific location. offset, int whence); SEEK_END);
Returns current file
ftell() long ftell(FILE *stream); long pos = ftell(file);
pointer position.
Resets file pointer to
rewind() void rewind(FILE *stream); rewind(file);
the start.
Example:
#include<stdio.h>
int main()
{
FILE *fptr;
fptr=fopen("Sample.txt","r");
if(fptr==NULL)
{
printf("Connection failed");
return 1;
}
char ch;
while(1)
{
ch=fgetc(fptr);
if(ch==EOF)
break;
printf("%c ",ch);
}
fclose(fptr);
return 0;
}

4. file copy and file merge programs


Refer the Lab program for this

5. Count number of vowels and consonants, digits and special characters in a text
file.
Refer the Lab program for this

6. Dynamic memory allocation functions

Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *arr;
int n, i;

// Allocate memory using malloc


printf("Enter number of elements: ");
scanf("%d", &n);
arr = (int *)malloc(n * sizeof(int));

// Check if memory allocation is successful


if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Initialize and print values
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Array elements:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

// Free allocated memory


free(arr);
return 0;
}

You might also like