0% found this document useful (0 votes)
25 views55 pages

Unit 03

Uploaded by

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

Unit 03

Uploaded by

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

Programming for Problem Solving

Q.1 What is pointer? Explain various types of pointer.

Answer:

Pointer
A Pointer in C language is a variable which holds the address of another variable of
same data type. Pointers are used to access memory and manipulate the address.
Pointers are one of the most distinct and exciting features of C language. It provides
power and flexibility to the language.
Declaring a pointer

data_type * pointer_variable_name;

Initialize a pointer

pointer = &variable;

int *a;

Key Points to Remember About Pointers in C:


1. Normal variable stores the value whereas pointer variable stores the address
of the variable.
2. The content of the C pointer always be a whole number i.e. address.
3. Always C pointer is initialized to null, i.e. int *p = null.
4. The value of null pointer is 0.
5. & symbol is used to get the address of the variable.
6. *Symbol is used to get the value of the variable that the pointer is pointing to.
7. If a pointer in C is assigned to NULL, it means it is pointing to nothing.
8. Two pointers can be subtracted to know how many elements are available
between these two pointers. But, Pointers addition, multiplication, division
are not allowed.
9. The size of any pointer is 2 byte (for 16 bit compiler) and 4 byte (for 32 bit
compiler).

Prepared by: Shankar Sharan Tripathi Page 1


Programming for Problem Solving

Program for Pointers in C:

#include <stdio.h>
int main()
{
int *ptr, a;
a= 50;
ptr = &a;
printf("The value of a=%d\n", a);
printf("The address of a=%d\n", &a);
printf("The value of a=%d\n", *ptr);
printf("The address of a=%d\n", ptr);
return 0;
}

Output:

The value of a=50


The address of a= -124567
The value of a=50
The address of a= -124567

Prepared by: Shankar Sharan Tripathi Page 2


Programming for Problem Solving

Q.2 Types of Pointers in C Programming


1. NULL Pointer
2. Dangling Pointer
3. Generic Pointers/Void Pointer
4. Wild Pointer
5. Near Pointer
6. Far Pointer
7. Huge Pointers

1. NULL Pointer:
NULL Pointer is a pointer which is pointing to nothing. In case, if we don’t have
address to be assigned to a pointer, then we can simply use NULL.

#include <stdio.h>
int main()
{
int *ptr = NULL;
printf("The value of ptr is %p", ptr);
return 0;
}

Output:
The value of ptr is (nil)

Prepared by: Shankar Sharan Tripathi Page 3


Programming for Problem Solving

2. Dangling Pointer in C
Dangling pointers arise when an object is deleted or de-allocated, without
modifying the value of the pointer, so that the pointer still points to the memory
location of the de-allocated memory. In short pointer pointing to non-existing memory
location is called dangling pointer.

#include <stdlib.h>
#include <stdio.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int));
free(ptr); // After call free function, ptr becomes a dangling
pointer

3. Generic pointer or Void pointer


A void pointer is a special pointer that can point to object of any type.
A void pointer is type less pointer also known as generic pointer. Void pointer is an
approach towards generic functions and generic programming in C. A void pointer can
hold address of any type and can be type casted to any type.

#include<stdlib.h>
int main()
{
int x = 4;

Prepared by: Shankar Sharan Tripathi Page 4


Programming for Problem Solving

float y = 5.5;
void *ptr;
ptr = &x;
printf("Integer variable is = %d", *( (int*) ptr) );
ptr = &y;
printf("\nFloat variable is= %f", *( (float*) ptr) );
return 0;
}

Output:
Integer variable is = 4
Float variable is= 5.500000

4. Wild Pointer:
A pointer which has not been initialized to anything (not even NULL) is known
as wild pointer. The pointer may be initialized to a non-NULL garbage value that may
not be a valid address.
int main()
{
int *p; /* p wild pointer */
int x = 10;
return 0;
}

5. Near Pointer
The pointer which can points only 64KB data segment or segment number 8 is
known as near pointer. That is near pointer cannot access beyond the data segment
like graphics video memory, text video memory, etc. Size of near pointer is two byte.
With the help of keyword near, we can make any pointer as near pointer.

Prepared by: Shankar Sharan Tripathi Page 5


Programming for Problem Solving

#include<stdio.h>
int main()
{
int x=25;
int near* ptr;
ptr=&x;
printf(“%d”,sizeof ptr);
return 0;
}

Output:
2

6. Far Pointer
The pointer which can point or access whole the residence memory of RAM, i.e.,
which can access all 16 segments is known as far pointer. Size of the far pointer is 4
byte or 32 bit.

#include<stdio.h>
int main()
{
int x=10;
int far *ptr;
ptr=&x;
printf("%d",sizeof ptr);
return 0;
}

Output :
4

Prepared by: Shankar Sharan Tripathi Page 6


Programming for Problem Solving

7. Huge Pointer
The pointer which can point or access whole the residence memory of RAM i.e.
which can access all 16 segments is known as a huge pointer. Size of the far pointer is
4 byte or 32 bit.

#include<stdio.h>
int main()
{
har huge * far *p;
printf("size of p=%d \/",sizeof(p));
printf(“size of *p=%d\n",sizeof(*p));
printf("size of **p=%d",sizeof(**p));
return 0;
}

Output :
Size of p=4
Size of *p=4
Size of **p= 1

Prepared by: Shankar Sharan Tripathi Page 7


Programming for Problem Solving

Q.3 Explain Dynamic memory allocation in C.


Answer:
Dynamic memory allocation in C
The concept of dynamic memory allocation in c language enables the C programmer
to allocate memory at runtime. Dynamic memory allocation in c language is possible by
4 functions of stdlib.h header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

Before learning above functions, let's understand the difference between static
memory allocation and dynamic memory allocation.

static memory allocation dynamic memory allocation


Memory is allocated at compile time. Memory is allocated at run time.
Memory can't be increased while Memory can be increased while executing
executing program. program.
Used in array. Used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc() Allocates single block of requested memory.


calloc() Allocates multiple block of requested memory.
realloc() Reallocates the memory occupied by malloc() or calloc() functions.
free() Frees the dynamically allocated memory.

Prepared by: Shankar Sharan Tripathi Page 8


Programming for Problem Solving

1. malloc() function in C

1. The malloc() function allocates single block of requested memory.


2. It doesn't initialize memory at execution time, so it has garbage value
initially.
3. It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size)

For Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And,
the pointer ptr holds the address of the first byte in the allocated memory.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i, sum = 0;
printf("Enter number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL)
{
printf("Memory not allocated.\n");

Prepared by: Shankar Sharan Tripathi Page 9


Programming for Problem Solving

exit(0);
}
else
{
printf("Memory successfully allocated using malloc.\n");
for (i = 0; i < n; ++i)
{
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
{
printf("%d, ", ptr[i]);
}
}
return 0;
}

Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,

2. calloc()function in C
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the
specified number of blocks of memory of the specified type. It initializes each block
with a default value ‘0’.

Syntax:
ptr = (cast-type*)calloc(n, element-size);

For Example:
ptr = (float*) calloc(25, sizeof(float));

Prepared by: Shankar Sharan Tripathi Page 10


Programming for Problem Solving

This statement allocates contiguous space in memory for 25 elements each with the
size of the float.

If space is insufficient, allocation fails and returns a NULL pointer.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i, sum = 0;
printf("Enter number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using calloc.\n");
for (i = 0; i < n; ++i)
{
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i)

Prepared by: Shankar Sharan Tripathi Page 11


Programming for Problem Solving

{
printf("%d, ", ptr[i]);
}
}
return 0;
}

Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,

3. free() function in C
“free” method in C is used to dynamically de-allocate the memory. The memory
allocated using functions malloc() and calloc() is not de-allocated on their own. Hence
the free() method is used, whenever the dynamic memory allocation takes place. It
helps to reduce wastage of memory by freeing it.

Syntax:
free(ptr);

Prepared by: Shankar Sharan Tripathi Page 12


Programming for Problem Solving

#include <stdio.h>
#include <stdlib.h>
int main()
{ int *ptr, *ptr1;
int n, i, sum = 0;
printf("Enter number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
ptr1 = (int*)calloc(n, sizeof(int));
if (ptr == NULL || ptr1 == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using malloc.\n");
free(ptr);
printf("Malloc Memory successfully freed.\n");
printf("\nMemory successfully allocated using calloc.\n");
free(ptr1);
printf("Calloc Memory successfully freed.\n");
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.

Memory successfully allocated using calloc.


Calloc Memory successfully freed.

Prepared by: Shankar Sharan Tripathi Page 13


Programming for Problem Solving

4. realloc() function in C
“realloc” or “re-allocation” method in C is used to dynamically change the memory
allocation of a previously allocated memory. In other words, if the memory previously
allocated with the help of malloc or calloc is insufficient, realloc can be used
to dynamically re-allocate memory.

Syntax:
ptr = realloc(ptr, newSize);

Where ptr is reallocated with new size 'newSize'.

If space is insufficient, allocation fails and returns a NULL pointer.


#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i, sum = 0;
printf("Enter number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));

Prepared by: Shankar Sharan Tripathi Page 14


Programming for Problem Solving

if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using calloc.\n");
for (i = 0; i < n; ++i)
{
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
{
printf("%d, ", ptr[i]);
}
printf("\n\nEnter the new size of the array: %d\n", n);
ptr = realloc(ptr, n * sizeof(int));
printf("Memory successfully re-allocated using realloc.\n");
for (i = 5; i < n; ++i)
{
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
{
printf("%d, ", ptr[i]);
}
free(ptr);
}

return 0;
}

Prepared by: Shankar Sharan Tripathi Page 15


Programming for Problem Solving

Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5

Enter the new size of the array: 10


Memory successfully re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Q.4 Write short notes on:


1. Pointer to Pointer 2. Pointer and Arrays 3. Pointer to Array
4. Array of Pointers 5. Pointers to Structures

Answer:
1. Pointer to Pointer (Double Pointer) in C
If a pointer points to a pointer of same type, we call it as pointer to a pointer. Read the
statement slowly again, if you did not catch my words. Many texts and authors also
refer pointer to pointer as double pointer, since two pointers are involved.

In the above image pointer *ptr points at memory location 0x1230 of integer type.
Pointer **dPtr points at memory location 0x1220 of integer pointer type.

Prepared by: Shankar Sharan Tripathi Page 16


Programming for Problem Solving

#include <stdio.h>
int main()
{
int num; // Integer variable
int *ptr = &num; // Pointer to integer
int **dPtr = &ptr; // Pointer to integer pointer
num = 10;
printf("Value of num = %d \n", num);
printf("Value pointed by ptr = %d \n", *ptr);
printf("Value pointed by dPtr = %d \n\n", **dPtr);
*ptr = 100;
printf("Value of num = %d \n", num);
printf("Value pointed by ptr = %d \n", *ptr);
printf("Value pointed by dPtr = %d \n\n", **dPtr);
**dPtr = 1000;
printf("Value of num = %d \n", num);
printf("Value pointed by ptr = %d \n", *ptr);
printf("Value pointed by dPtr = %d \n\n", **dPtr);
return 0;
}

Output:
Value of num = 10
Value pointed by ptr = 10
Value pointed by dPtr = 10

Value of num = 100


Value pointed by ptr = 100
Value pointed by dPtr = 100

Value of num = 1000


Value pointed by ptr = 1000
Value pointed by dPtr = 1000

Prepared by: Shankar Sharan Tripathi Page 17


Programming for Problem Solving

2. Pointer and Arrays in C


When an array is declared, compiler allocates sufficient amount of memory to contain
all the elements of the array. Base address i.e address of the first element of the array
is also allocated by the compiler.

Suppose we declare an array arr,


int arr[5] = { 1, 2, 3, 4, 5 };

Assuming that the base address of arr is 1000 and each integer requires two bytes, the
five elements will be stored as follows:

Here variable arr will give the base address, which is a constant pointer pointing to the
first element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In
short, arr has two purpose - it is the name of the array and it acts as a pointer pointing
towards the first element in the array.

Arr = &arr[0] by default


We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.

Now we can access every element of the array arr using p++ to move from one
element to another.
NOTE: You cannot decrement a pointer once incremented. p-- won't work.

Prepared by: Shankar Sharan Tripathi Page 18


Programming for Problem Solving

3. Pointer to Array
As studied above, we can use a pointer to point to an array, and then we can use that
pointer to access the array elements. Let’s have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}

In the above program, the pointer *p will print all the values stored in the array one by
one. We can also use the Base address (a in above case) to act as a pointer and print all
the values.

The generalized form for using pointer with an array,


*(a+i) is same as: a[i]

Prepared by: Shankar Sharan Tripathi Page 19


Programming for Problem Solving

4. Array of Pointers
We can also have array of pointers. Pointers are very helpful in handling character
array with rows of varying length.
char *name[3] = { "Adam","chris","Deniel"};

//Now lets see same array without using pointer

char name[3][20] = { "Adam", "chris","Deniel"};

5. Pointers to Structures
You can define pointers to structures in the same way as you define pointer to any
other variable :–

struct Books *struct_pointer;

Now, you can store the address of a structure variable in the above defined pointer
variable. To find the address of a structure variable, place the '&'; operator before the
structure's name as follows :–

struct_pointer = &structure_variable;

Prepared by: Shankar Sharan Tripathi Page 20


Programming for Problem Solving

to access the members of a structure using a pointer to that structure, you must use
the → operator as follows :–

#include <stdio.h>
#include <string.h>
struct Books
{ char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( )
{
struct Books Book1,*book; /* Declare Book1 of type Book */
printf(“ Enter the title of book, author name, subject & book id”);
scanf( "%s", &Book1.title);
scanf( "%s", &Book1.author);
scanf( "%s", &Book1.subject);
scanf( "%d", &Book1.book_id);
book=&Book1;
printf(“\nthe title of book, author name, subject & book id”);
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
return 0;
}
Output:
Enter the title of book, author name, subject & book id
C Programming
Nuha
C
6495407

Prepared by: Shankar Sharan Tripathi Page 21


Programming for Problem Solving

the title of book, author name, subject & book id


Book title : C
Book author : Nuha
Book subject : C
Book book_id : 6495407

Q.5 pointer arithmetic/ Operations on Pointers

Pointer arithmetic depends on the type of data the pointer points to, as the arithmetic
adjusts for the size of the data type.

a. Increment (ptr++)

 Moves the pointer to the next memory location for the type it points to.

 Example:

int arr[3] = {10, 20, 30};

int *ptr = arr; // Points to arr[0]

ptr++; // Now points to arr[1]

b. Decrement (ptr--)

 Moves the pointer to the previous memory location for the type it points to.

 Example:

ptr--; // Moves back to arr[0] if it was at arr[1].

c. Addition (ptr + n)

 Moves the pointer forward by n elements.

 Example:

ptr = arr + 2; // Points to arr[2].

d. Subtraction (ptr - n)

 Moves the pointer backward by n elements.


Prepared by: Shankar Sharan Tripathi Page 22
Programming for Problem Solving

 Example:

ptr = arr + 2; // Points to arr[2].

ptr = ptr - 1; // Now points to arr[1].

2. Difference Between Pointers

The difference between two pointers gives the number of elements between them.

int arr[5] = {10, 20, 30, 40, 50};

int *ptr1 = &arr[1]; // Points to arr[1]

int *ptr2 = &arr[4]; // Points to arr[4]

int diff = ptr2 - ptr1; // Difference in terms of array elements (4 - 1 = 3)

3. Accessing Elements

Pointers can access array elements using offset notation:

int arr[3] = {1, 2, 3};

int *ptr = arr;

printf("%d\n", *(ptr + 1)); // Outputs 2 (arr[1]).

4. Valid Pointer Arithmetic

Pointer arithmetic is valid only for pointers that point to the same memory block.
Accessing memory outside this block causes undefined behavior.

5. Pointers and Arrays

Pointers and arrays are closely related, as the name of an array is a pointer to its first
element:

int arr[3] = {1, 2, 3};

int *ptr = arr;

Prepared by: Shankar Sharan Tripathi Page 23


Programming for Problem Solving

printf("%d\n", *(ptr + 2)); // Equivalent to arr[2], outputs 3.

6. Limitations

Pointer arithmetic is not valid for void* or function pointers, as they do not have a
defined size

Q.6 What is an Array? Write a program to sort an integer array.


Answer:
An array is a data structure that stores a collection of elements, typically of the same
data type, in contiguous memory locations. Arrays allow you to efficiently access and
manipulate elements by their index.

Key Characteristics
1. Fixed Size: The size of the array is determined at the time of creation and
cannot be changed.
2. Homogeneous Elements: All elements in an array are of the same type.
3. Indexed Access: Each element is accessed using an index, starting from 0 (in
most programming languages).
Properties of Array:
 Each element of an array is of same data type and carries the same size.
 Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
 Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size of
the data element.
Declaring an Array
 Like any other variable, arrays must be declared before they are used. General
form of array declaration is,
Data-type variable-name[size];

/* Example of array declaration */


int arr[10];

Prepared by: Shankar Sharan Tripathi Page 24


Programming for Problem Solving

Here int is the data type, arr is the name of the array and 10 is the size of array. It
means array arr can only contain 10 elements of int type.Index of an array starts
from 0 to size-1 i.e first element of arr array will be stored at arr[0] address and the
last element will occupy arr[9].

Advantage of C Array:
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using for loop, we can retrieve the elements of an array
easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array:
Fixed Size: Whatever size, we define at the time of declaration of the array, we
can't exceed the limit. So, it doesn't grow the size dynamically like Linked List
which we will learn later.

TYPES OF C ARRAYS:
There are 2 types of C arrays. They are:
One dimensional array
Multi dimensional array
 Two dimensional array
 Three dimensional array
 Four dimensional array etc…

1. One-dimensional array (1-D arrays):


You can imagine a 1d array as a row, where elements are stored one after another.

Prepared by: Shankar Sharan Tripathi Page 25


Programming for Problem Solving

Syntax
data_type array_name[array_size];
where,
 data_type: is a type of data of each array block.
 array_name: is the name of the array using which we can refer to it.
 array_size: is the number of blocks of memory array going to have.
Example
int nums[5];

2. Two-dimensional (2D) array:


Multidimensional arrays can be considered as an array of arrays or as a matrix
consisting of rows and columns.

Syntax
data_type array_name[sizeof_1st_dimension][sizeof_2nd_dimension];
where,
 data_type: is a type of data of each array block.
 array_name: is the name of the array using which we can refer to it.
 sizeof_dimension: is the number of blocks of memory array going to have in the
corresponding dimension.

Prepared by: Shankar Sharan Tripathi Page 26


Programming for Problem Solving

Example
int nums[5][10];

3. Three-dimensional array:
A 3-D Multidimensional array contains three dimensions, so it can be considered an
array of two-dimensional arrays.

Syntax
data_type array_name[sizeof_1st_Dim.][sizeof_2nd_dimension][sizeof_3rd_dimension];
where,
 data_type: is a type of data of each array block.
 array_name: is the name of the array using which we can refer to it.
 sizeof_dimension: is the number of blocks of memory array going to have in the
corresponding dimension.
Example
int nums[5][10][2];

Prepared by: Shankar Sharan Tripathi Page 27


Programming for Problem Solving

Q.7 Character Arrays and Strings in C

In C programming, a character array is a collection of characters stored in


contiguous memory locations. It is commonly used to represent and manipulate
strings.

1. Character Arrays

A character array is an array of characters, but it does not automatically include a


null terminator (\0). You need to explicitly add one if you want the array to represent
a string.

Syntax:
char arr[] = {'H', 'e', 'l', 'l', 'o'};

Characteristics:

1. Does not necessarily end with a null character (\0).


2. Used for storing characters, not strings directly.

Example:

#include <stdio.h>
int main()
{
char arr[] = {'H', 'e', 'l', 'l', 'o'};
for (int i = 0; i < 5; i++) {
printf("%c", arr[i]); // Output: Hello
}
return 0;
}

2. Strings

A string in C is essentially a null-terminated (\0) character array. The null character


indicates the end of the string.

Syntax:
char str[] = "Hello";

Prepared by: Shankar Sharan Tripathi Page 28


Programming for Problem Solving

Characteristics:

1. Must end with a null character (\0) to signify the string's end.
2. C strings can be manipulated using standard library functions such as strlen(),
strcpy(), strcmp(), etc.

Example:

#include <stdio.h>
#include <string.h>
int main()
{
char str[ ] = "Hello";
printf("String: %s\n", str); // Output: Hello
printf("Length: %lu\n", strlen(str)); // Output: 5
return 0;
}

Differences Between Character Arrays and Strings

Aspect Character Array String


A character array that ends
Definition An array of characters.
with \0.
Null Terminator May or may not include \0. Always ends with \0.
Requires manual implementation for Uses standard string library
Manipulation
operations. functions.
Example
char arr[ ] = {'H', 'e', 'l', 'l', 'o'}; char str[ ] = "Hello";
Declaration

Prepared by: Shankar Sharan Tripathi Page 29


Programming for Problem Solving

Q.8 Write C String function with Example.

Answer:

1. String Length function:


strlen() : The strlen() function returns the length of the given string. It doesn't count
null character '\0'.

Example:

#include<stdio.h>
#include <string.h>
int main()
{ char ch[20]={'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Output:

Length of string is: 7

2. Copy String function:


strcpy() : The strcpy(destination, source) function copies the source string in
destination.
Example:

#include<stdio.h>
#include <string.h>
int main()
{
char ch[20]={'w', 'e', 'l', 'c', 'o', 'm', 'e','\0'};
char ch2[20];
strcpy(ch2,ch);

Prepared by: Shankar Sharan Tripathi Page 30


Programming for Problem Solving

printf("Value of second string is: %s",ch2);


return 0;
}

Output:
Value of second string is: welcome

3. String Concatenation function:


strcat() : The strcat(first_string, second_string) function concatenates two strings and
result is returned to first_string.
Example:

#include<stdio.h>
#include <string.h>
int main()
{
char ch[10]={'w', 'e', 'l', '\0'};
char ch2[10]={'c', 'o', 'm', 'e', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}

Output:
Value of first string is: welcome

4. Compare String function:


strcmp(): The strcmp(first_string, second_string) function compares two string and
returns 0 if both strings are equal.

Here, we are using gets() function which reads string from the console.

Prepared by: Shankar Sharan Tripathi Page 31


Programming for Problem Solving

Example:

#include<stdio.h>
#include <string.h>
int main()
{
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}

Output:

Enter 1st string: hello


Enter 2nd string: hello
Strings are equal

5. Reverse String function:


strrev(): The strrev(string) function returns reverse of the given string. Let's see a
simple example of strrev() function.

Example:

#include<stdio.h>
#include <string.h>
int main()
{ char str[20];
printf("Enter string: ");
Prepared by: Shankar Sharan Tripathi Page 32
Programming for Problem Solving

gets(str);//reads string from console


printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}

Output:
Enter string: nam
String is: nam
Reverse String is: man

6. String Lowercase function:


strlwr():The strlwr(string) function returns string characters in lowercase. Let's see a
simple example of strlwr() function.

Example:

#include<stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}

Output:

Enter string: WELcome


String is: WELcome
Lower String is: welcome

Prepared by: Shankar Sharan Tripathi Page 33


Programming for Problem Solving

7. String Uppercase function:


strupr():The strupr(string) function returns string characters in uppercase. Let's see
a simple example of strupr() function.

Example:

#include<stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}

Output:

Enter string: welcome


String is: welcome
Upper String is: WELCOME

8. C gets() function

The gets() function enables the user to enter some characters followed by the enter
key. All the characters entered by the user get stored in a character array. The null
character is added to the array to make it a string. The gets() allows the user to enter
the space-separated strings. It returns the string entered by the user.

Declaration

char[] gets(char[]);

Prepared by: Shankar Sharan Tripathi Page 34


Programming for Problem Solving

Reading string using gets() function

Example:

#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}

Output

Enter the string?


Welcome
You entered Welcome

9. C puts() function

The puts() function is very much similar to printf() function. The puts() function is
used to print the string on the console which is previously read by using gets() or
scanf() function. The puts() function returns an integer value representing the number
of characters being printed on the console. Since, it prints an additional newline
character with the string, which moves the cursor to the new line on the console, the
integer value returned by puts() will always be equal to the number of characters
present in the string plus 1.

Declaration

int puts(char[])

Prepared by: Shankar Sharan Tripathi Page 35


Programming for Problem Solving

Example:

#include<stdio.h>
#include <string.h>
int main()
{
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}

Output:

Enter your name: Amit Kumar


Your name is: Amit Kumar

10. strchr - Find First Occurrence of Character

 Description: Finds the first occurrence of a character in a string.


 Syntax: char *strchr(const char *str, int ch);

Program:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "Hello, World!";
char *pos = strchr(str, 'W');
if (pos)
printf("Character found at position: %ld\n", pos - str); // Output: 7
else
printf("Character not found.\n");

return 0;
}
Prepared by: Shankar Sharan Tripathi Page 36
Programming for Problem Solving

11. strstr - Find Substring


 Description: Finds the first occurrence of a substring in a string.
 Syntax: char *strstr(const char *haystack, const char *needle);

Program:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "Hello, World!";
char *pos = strstr(str, "World");
if (pos)
printf("Substring found at position: %ld\n", pos - str); // Output: 7
else
printf("Substring not found.\n");

return 0;
}

Q.9 Basic Algorithms of Searching (Linear Search & Binary Search)

Linear Search
Linear Search is a simple search algorithm that sequentially checks each element of an
array until the desired element is found or the end of the array is reached.

Wap to Search an element using Linear Search.


#include <stdio.h>
int main()
{
int key,i, arr[5] = {10, 20, 30, 40, 50};
printf("Enter the number to search: ");
scanf("%d", &key);
for (i = 0; i < n; i++)
{
if (arr[i] == key)
{
Prepared by: Shankar Sharan Tripathi Page 37
Programming for Problem Solving

printf("Number found at position %d\n", i + 1);


break;
}
}
if (i == n)
{
printf("Number not found.\n");
}
return 0;
}
Example Input/Output:
Enter the number to search: 30
Number found at position 3.

Binary Search
Binary Search is an efficient search algorithm that works on sorted arrays. It
repeatedly divides the search interval in half, comparing the target value with the
middle element, until the target is found or the search interval is empty.

Wap to Search an element using Binary Search.


#include <stdio.h>
int main()
{
int arr[] = {10, 20, 30, 40, 50}; // Array must be sorted
int n = 5; // Number of elements in the array
int key, left = 0, right = n - 1, mid;
printf("Enter the number to search: ");
scanf("%d", &key);
while (left <= right)
{
mid = (left + right) / 2;
if (arr[mid] == key)
{
printf("Number found at position %d.\n", mid + 1);

Prepared by: Shankar Sharan Tripathi Page 38


Programming for Problem Solving

return 0;
}
else if (arr[mid] < key)
{
left = mid + 1; // Search in the right half
}
else
{
right = mid - 1; // Search in the left half
}
}
printf("Number not found.\n");
return 0;
}

Output:
Enter the number to search: 40
Number found at position 4.

Comparison of Linear and Binary Search


Aspect Linear Search Binary Search

Array Requirement Unsorted or sorted Must be sorted

Time Complexity O(n) O(log n)

Best Case Key is the first element Key is the middle element

Worst Case Key is the last element or absent Key is absent or at one extreme

Q.10 Basic Algorithms of Sorting (Bubble sort & Selection sort)

Prepared by: Shankar Sharan Tripathi Page 39


Programming for Problem Solving

Bubble Sort
 Definition: Bubble Sort repeatedly compares adjacent elements in the array and
swaps them if they are in the wrong order. This process continues until the
entire array is sorted.

#include <stdio.h>
int main()
{
int arr[100], n, i, j, temp;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
// Bubble Sort
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Sorted Array: ");
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}

Prepared by: Shankar Sharan Tripathi Page 40


Programming for Problem Solving

return 0;
}

Output:
Enter the number of elements: 5
Enter the elements:
52915
Sorted Array: 1 2 5 5 9

Example:
Input: [5, 2, 9, 1, 5]
Pass 1: [2, 5, 1, 5, 9]
Pass 2: [2, 1, 5, 5, 9]
Pass 3: [1, 2, 5, 5, 9]

2. Selection Sort
 Definition: Selection Sort selects the smallest (or largest) element from the
unsorted part of the array and swaps it with the first unsorted element. This
process is repeated until the array is sorted.
#include <stdio.h>
int main( )
{
int arr[100], n, i, j, minIndex, temp;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}

// Selection Sort
for (i = 0; i < n - 1; i++)
Prepared by: Shankar Sharan Tripathi Page 41
Programming for Problem Solving

{
minIndex = i;
for (j = i + 1; j < n; j++)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
printf("Sorted Array: ");
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}

Output:
Enter the number of elements: 5
Enter the elements:
52915
Sorted Array: 1 2 5 5 9
Example:
Input: [5, 2, 9, 1, 5]
Pass 1: [1, 2, 9, 5, 5]
Pass 2: [1, 2, 9, 5, 5]
Pass 3: [1, 2, 5, 9, 5]
Pass 4: [1, 2, 5, 5, 9]
Differences:

Prepared by: Shankar Sharan Tripathi Page 42


Programming for Problem Solving

Aspect Bubble Sort Selection Sort

Compares and swaps adjacent Finds the smallest/largest and


Working
elements swaps

Best Case O(n) (when array is sorted) O(n2)

Worst
O(n2) O(n2)
Case

Stability Stable Unstable

Q.11 Accessing Arrays Using Pointers in C


In C, arrays and pointers are closely related. The name of an array acts as a pointer to
its first element. You can use pointers to traverse and access array elements.

How It Works:
1. Array Name as Pointer:
 The name of the array (e.g., arr) represents the address of the first
element (&arr[0]).
 You can access elements using a pointer by incrementing it (ptr + i).
2. Pointer Arithmetic:
 Incrementing a pointer (ptr + 1) moves the pointer to the next element in
the array.
 De-referencing a pointer (*ptr) gives the value stored at the memory
address.

Example Program:
#include <stdio.h>
int main()
{
int arr[ ] = {10, 20, 30, 40};
int *ptr; // Pointer to an integer

Prepared by: Shankar Sharan Tripathi Page 43


Programming for Problem Solving

int n = sizeof(arr) / sizeof(arr[0]);


ptr = arr; // Point to the first element of the array
printf("Accessing array elements using pointers:\n");
for (int i = 0; i < n; i++)
{
printf("Element %d: %d (using ptr[%d])\n", i + 1, *(ptr + i), i);
}
printf("\nAccessing array elements directly:\n");
for (int i = 0; i < n; i++)
{
printf("Element %d: %d (using arr[%d])\n", i + 1, arr[i], i);
}
return 0;
}

Output:
Accessing array elements using pointers:
Element 1: 10 (using ptr[0])
Element 2: 20 (using ptr[1])
Element 3: 30 (using ptr[2])
Element 4: 40 (using ptr[3])
Accessing array elements directly:
Element 1: 10 (using arr[0])
Element 2: 20 (using arr[1])
Element 3: 30 (using arr[2])
Element 4: 40 (using arr[3])
Explanation:
1. Pointer ptr is assigned to the array arr (ptr = arr;).
2. Accessing Elements:
 Using *(ptr + i): Accesses the value of the element at index i.
 Using arr[i]: Directly accesses the element using array indexing.

Program

Prepared by: Shankar Sharan Tripathi Page 44


Programming for Problem Solving

Write a Program to Print Transpose of a Matrix.


int main()
{
int i,j, A[4][4],TA[4][4];
clrscr();
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("Enter value for arr[%d][%d]=", i,j);
scanf("%d",&A[i][j]);
}
}
for(i=0;i<4;i++)
{
for(j=0; j<4;j++)
{
printf(" %d ",A[i][j]);
}printf("\n");
}
printf("Transpose of A[%d][%d]=\n", i,j);
for(i=0;i<4;i++)
{
for(j=0; j<4;j++)
{ TA[i][j]=A[j][i];
printf(" %d ",TA[i][j]);
}printf("\n");
}
getch();
return 0;
}

Write a Program to Print 4x4 Matrix.

Prepared by: Shankar Sharan Tripathi Page 45


Programming for Problem Solving

#include <stdio.h>
int main()
{
int i,j, arr[4][4];
clrscr();
// input
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("Enter value for arr[%d][%d]=", i,j);
scanf("%d",&arr[i][j]);
}
}
for(i=0;i<4;i++)
{
for(j=0; j<4;j++)
{
printf("%d ",arr[i][j]);
}printf("\n");
}
getch();
return 0;
}

Write a Program to Print Min & Max element of an array.

Prepared by: Shankar Sharan Tripathi Page 46


Programming for Problem Solving

#include<stdio.h>
int main()
{
int i,a[10], min=0,max=0;
clrscr();
printf("Insert 10 elements in an array :\n");
for(i=0;i<10;i++)
scanf("%d", &a[i]);
min=a[0];
max=a[0];
for(i=0;i<10;i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("The Min value of array = %d \n ",min);
printf("The Max value of array = %d \n”,max);
getch();
return 0;
}

Write a Program to Print Addition of Two Matrixes.

Prepared by: Shankar Sharan Tripathi Page 47


Programming for Problem Solving

#include <stdio.h>
int main()
{
int i,j, a[4][4],b[4][4],c[4][4];
clrscr();
printf("Enter The Elements in First Matrix 4x4 =\n");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{

scanf(" %d",&a[i][j]);
}
}
for(i=0;i<4;i++)
{
for(j=0; j<4;j++)
{
printf("\t a[%d][%d]= %d ",i,j,a[i][j]);
}printf("\n");
}
printf("Enter The Elements in Second Matrix of 4x4 =\n");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{

scanf(" %d",&b[i][j]);
}
}
for(i=0;i<4;i++)
{
for(j=0; j<4;j++)
{
printf("b[%d][%d]= %d ",i,j,b[i][j]);
}
printf("\n");
}
printf("\tThe Sum of The Elements of First & Second Matrix of 4x4 =\n");

Prepared by: Shankar Sharan Tripathi Page 48


Programming for Problem Solving

for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{

c[i][j]=a[i][j] + b[i][j];
}
}
for(i=0;i<4;i++)
{
for(j=0; j<4;j++)
{
printf("c[%d][%d]= %d ",i,j,c[i][j]);
}
printf("\n");
}
getch();
return 0;
}

Prepared by: Shankar Sharan Tripathi Page 49


Programming for Problem Solving

Write a Program to Print Subtraction of Two Matrixes.


#include <stdio.h>
int main()
{
int i,j, a[4][4],b[4][4],c[4][4];
clrscr();
printf("Enter The Elements in First Matrix 4x4 =\n");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{

scanf(" %d",&a[i][j]);
}
}
for(i=0;i<4;i++)
{
for(j=0; j<4;j++)
{
printf("\t a[%d][%d]= %d ",i,j,a[i][j]);
}printf("\n");
}
printf("Enter The Elements in Second Matrix of 4x4 =\n");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{

scanf(" %d",&b[i][j]);
}
}
for(i=0;i<4;i++)
{
for(j=0; j<4;j++)
{
printf("b[%d][%d]= %d ",i,j,b[i][j]);
}
printf("\n");
}

Prepared by: Shankar Sharan Tripathi Page 50


Programming for Problem Solving

printf("\tThe Subtraction of The Elements of First & Second Matrix of 4x4 =\n");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{

c[i][j]=a[i][j] - b[i][j];
}
}
for(i=0;i<4;i++)
{
for(j=0; j<4;j++)
{
printf("c[%d][%d]= %d ",i,j,c[i][j]);
}
printf("\n");
}
getch();
return 0;
}

Prepared by: Shankar Sharan Tripathi Page 51


Programming for Problem Solving

Write a Program to Print Multiplication of Two Matrixes.


#include <stdio.h>
int main()
{
int r1, c1,r2,c2, i, j, k, a[10][10], b[10][10], multi[10][10];
printf("Enter number of rows of first matrix:\n");
scanf("%d", &r1);
printf("Enter number of columns of first matrix:\n");
scanf("%d", &c1);
printf("Enter elements of first matrix:\n");
for (i = 0; i<r1 ; i++)
{
for (j = 0; j< c1; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter number of rows of second matrix:\n");
scanf("%d", &r2);
printf("Enter number of columns of second matrix:\n");
scanf("%d", &c2);
if (c1 != r2)
{
printf("The matrices can't be multiplied with each other.\n");
}
else
{
printf("Enter elements of second matrix:\n");
for (i = 0; i< r2; i++)
{
for (j= 0; j< c2; j++)
{
scanf("%d", &b[i][j]);
}
}
for (i= 0; i< r1; i++)
{
for (j = 0; j< c2; j++)
{

Prepared by: Shankar Sharan Tripathi Page 52


Programming for Problem Solving

multi[i][j]=0;
for (k = 0; k < r2; k++)
{
multi[i][j] = multi[i][j] +a[i][k]*b[k][j];
}
}
}
printf("Multiplication of the matrices:\n");
for (i= 0; i< r1; i++)
{
for (j= 0; j<c2; j++)
{
printf("%d\t", multi[i][j]);
}
printf("\n");
}
}
return 0;
}

Prepared by: Shankar Sharan Tripathi Page 53


Programming for Problem Solving

Write a Program to Search an Element from given Array using Linear Search
Algorithm.
#include<stdio.h>
int main()
{
int a[20],i,item;
clrscr();
printf("Enter 20 integer numbers :\n");
for(i=0;i<20;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the number you want to search :");
scanf("%d", &item);
for(i=0;i<20;i++)
{
if(a[i]==item)
{
printf("Item found in a[%d] index in the list & Address of the item =%d", i , &a[i]);
break;
}
}
if(i==20)
printf("Item not found in the given list");
getch();
return 0;
}

Prepared by: Shankar Sharan Tripathi Page 54


Programming for Problem Solving

Write a Program to print the sum of all the elements of an Array.


#include<stdio.h>
int main()
{
int a[10],i,sum=0;
clrscr();
printf("Enter 10 integer numbers :\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
printf("Inserted elements are :\n");
for(i=0;i<10;i++)
{ sum=sum+a[i];
printf("\ta[%d]=%d & Address of a[%d]=%d\n",i,a[i],i,&a[i]);
}
printf("The sum of all given numbers =%d\n", sum);
getch();
return 0;
}

Prepared by: Shankar Sharan Tripathi Page 55

You might also like