Psc-Unit 3
Psc-Unit 3
Array is a data structure that is used to store variables that are of similar data types
at contiguous locations. The main advantage of the array is random access and cache
friendliness. There are mainly three types of the array:
It allows random access and all the elements can be accessed with the help of their
index.
EXAMPLE:
#include <stdio.h>
int main()
{
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
10 8 6
Matrix Multiplication:
Input:
mat1[][] = {{1, 2},{3, 4}}
mat2[][] = {{5, 6},{7, 8}}
Multiplication of two matrices:
Output
Difference Table:
One Dimension
Basis Two Dimension Array
Array
The declaration
varies for different The declaration varies for
programming different programming
language: language:
1. For C++, 1. For C++,
datatype datatype
Declaration variable_name[ro variable_name[row][column
w] ]
int arr[5]; //an array with int arr[2][5]; //an array with two rows and
one row and five columns five columns will be created.
Example will be created. a b c d e
{a , b , c , d , e} f g h i j
3.2.1 Static Array: In this type of array, memory is allocated at compile time having a fixed
size of it. We cannot alter or update the size of this array.
Example:
Let us take an example, int a[5] creates an array of size 5 which means that we can insert only
5 elements; we will not be able to add 6th element because the size of the array is fixed
above.
In static memory
allocation, once the In dynamic memory allocation,
6 memory is allocated, the when memory is allocated the
memory size can not memory size can be changed.
change.
Example:
// C program to create dynamic array using malloc() function
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Memory allocated
printf("Memory successfully allocated using malloc.\n");
return 0;
}
Output:
Enter size of elements:5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
r is the maximum number of string values that can be stored in a string array.
m is the maximum number of character values that can be stored in each string array.
Example:
// C Program to print Array
// of strings
#include <stdio.h>
// Driver code
int main()
{
char arr[3][10] = {"GURU",
"JEEVITH", "GURUJEEVI"};
printf("String array Elements are:\n");
Ex:
#include <stdio.h>
int main()
{
int array[100], search, c, n;
Ex:
#include <stdio.h>
int main() {
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, position, swap;
for (i = 0; i < (n - 1); i++) {
position = i;
for (j = i + 1; j < n; j++) {
if (arr[position] > arr[j])
position = j;
}
if (position != i) {
swap = arr[i];
arr[i] = arr[position];
arr[position] = swap;
}
}
for (i = 0; i < n; i++)
printf("%d\t", arr[i]);
return 0;
}
Output:
0 2 6 11 12 18 34 45 55 99
Syntax of a function
In a function declaration, we must provide the function name, its return type, and the number
and type of its parameters. A function declaration tells the compiler that there is a function
with the given name defined somewhere else in the program.
Syntax
return_type name_of_the_function (parameter_1, parameter_2);
The parameter name is not mandatory while declaring functions. We can also declare the
function without using the name of the data variables.
Example
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names
Function Declaration
Note: A function in C must always be declared globally before calling it.
3.7.2 Function Definition
The function definition consists of actual statements which are executed when the function is
called (i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the function definition
always starts with the function declaration so we do not need to declare it explicitly. The
below example serves as both a function definition and a declaration.
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b) {
return a+b; }
Output:
Enter two numbers 10 25
The sum is 35
Type 4: Function with argument and no return value
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b) {
printf("\nThe sum is %d",a+b); }
Remember that global variables have external linkage by default, but you can restrict access to
the current file by marking them as static. Local variables have internal linkage within their
block or function.
Call by reference is the method in C where we call the function with the passing address as
arguments. We pass the address of the memory blocks which can be further stored in a
pointer variable that can be used in the function. Now, changes performed in the values inside
the function can be directly reflected in the main memory.
Ex:
// C Program to implement
// Call by reference
#include <stdio.h>
// Call by reference
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
// Driver Code
int main()
{
// Declaring Integer
int x = 1, y = 5;
printf("Before Swapping: x:%d , y:%d\n", x, y);
// Calling the function
swap(&x, &y);
printf("After Swapping: x:%d , y:%d\n", x, y);
return 0;
}
Output:
Before Swapping: x:1 , y:5
After Swapping: x:5 , y:1
Example:
#include <stdio.h>
void func(int arr[8]) {
// Size information is lost; arr behaves like a pointer
printf("Size of arr[] in func(): %d bytes\n", sizeof(arr));
}
int main() {
int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8};
printf("Size of arr[] in main(): %d bytes\n", sizeof(arr));
func(arr);
return 0;
}
Output:
Size of arr[] in main(): 32 bytes
Size of arr[] in func(): 8 bytes
Remember that passing an array to a function results in array decay, where the array loses
information about its size. One way to handle this is by passing the size of the array as an
additional parameter to the function.
Strings handling functions are defined under "string.h" header file. #include<string.h>
Few Predefined String Function and its Purpose:
• strlen() String length computes string's length strcpy() String Copy copies a string to
another
• strcat() String Concatenation concatenates(joins) two strings strcmp() String
Comparison compares two strings
• strlwr() String Lower converts string to lowercase strupr() String Upper converts string
to uppercase strrev() String Reverse reverses the given string
• strncat(), strncmp(), strncpy() n -> denotes number of strings
Syntax:
char var_name[size]=“String”;
Example program for Handling of Character Strings:
#include<stdio.h>
#include<conio.h>
{ char a[6]=“Cse”;
clrscr();
printf(“Enter a string : “);
scanf(“%s”,a);
printf(“Your String is : %s”,a);
getch();
}
Output:
Your String is : cse
Example 2:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[]=“Cse";
char b[]="Dept";
clrscr();
strcpy(a,b);
printf("\nThe string is %s",a);
getch();
}
Output:
The string is Dept
3.10.4 strcat( ) Function :
• It concatenates two strings and returns the concatenated string.
Syntax:
strcat(string1,string2);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[]=“Cse";
char b[]="Dept";
clrscr();
strcat(a,b);
printf("\nThe string is %s",a);
getch();
}
Output:
The string is CseDept
3.10.5 strcmp( ) Function :
• It compares the two strings and returns an integer value.
• If both the strings are same (equal) then this function would return 0 otherwise it may
return a negative or positive value based on the comparison.
• If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value.
• If string1 > string2 then it would return positive value.
• If string1 == string2 then you would get 0(zero) when you use this function for compare
strings.
Syntax: int strcmp(const char *str1, const char *str2);
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = “ProblemSolving";
char s2[20] = “ProblemSolvingusingC";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}
else {
printf("string 1 and 2 are different");
}
return 0;
}
Output:
string 1 and 2 are different
Example 2:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[10]=“csedept";
char b[10]=“cse";
int i;
clrscr();
i=strcmp(a,b);
if(i==0)
printf(“Strings are equal”);
else
printf("Strings are not equal”);
getch();
}
Output:
Strings are not equal
3.10.6 strrev()
It used to reverse a string.
syntax: strrev(string);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[]="Dept";
clrscr();
printf("\nThe reversed string is %s",strrev(a));
getch();
}
Output:
The string is tpeD
In C programming, recursion is a powerful concept where a function calls itself repeatedly until
a certain condition is met. Let’s explore the basics of recursion, recursive functions, and how
they differ from iteration.
Definition:
A function that calls itself is called a recursive function. Recursive functions can contain
multiple recursive calls. So Recursion is the process of a function calling itself directly or
indirectly. They are used to solve complex problems by breaking them down into simpler sub-
problems.
Basic Structure of Recursive Functions:
type function_name(args) {
// Base condition
// Recursion case (recursive call)
}
#include <stdio.h>
int nSum(int n) {
// Base condition to terminate recursion when N = 0
if (n == 0) {
return 0;
}
// Recursive case (recursive call)
int res = n + nSum(n - 1);
return res;
}
int main() {
int n = 5;
int sum = nSum(n);
printf("Sum of First %d Natural Numbers: %d", n, sum);
return 0;
}
Output:
Sum of First 5 Natural Numbers: 15
In this example, the nSum function calculates the sum of the first N natural numbers. It
demonstrates the fundamental concepts of recursion: the base condition (when to stop) and
the recursion case (how to break down the problem).