0% found this document useful (0 votes)
27 views20 pages

Module 3 Notes - Arrays Strings Arrays

The document outlines Module-3 of a C programming course, focusing on arrays, strings, and pointers. It covers single and multi-dimensional arrays, pointer usage, and includes example programs demonstrating array manipulation, string functions, and pointer arithmetic. Additionally, it discusses memory allocation and the concept of void pointers in C.

Uploaded by

Aditya Ram
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)
27 views20 pages

Module 3 Notes - Arrays Strings Arrays

The document outlines Module-3 of a C programming course, focusing on arrays, strings, and pointers. It covers single and multi-dimensional arrays, pointer usage, and includes example programs demonstrating array manipulation, string functions, and pointer arithmetic. Additionally, it discusses memory allocation and the concept of void pointers in C.

Uploaded by

Aditya Ram
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

B.M.S.

College of Engineering, Bengaluru

Department of Computer Science and Engineering

Structured Programming in C
25CS1PSSPC

Module-3: Arrays, Strings and Pointers

Syllabus

Single-Dimension Arrays, Generating a Pointer to an Array, Passing Single-Dimension Arrays to


Functions, Strings, Two-Dimensional Arrays, Multidimensional Arrays, Array Initialization,
Variable -Length Arrays.

What Are Pointers?, Pointer Variables, The Pointer Operators, Pointer Expressions, Pointers and
Arrays, Multiple Indirection, Initializing Pointers.
Arrays

An array is a collection of variables of the same type that are referred to through a common name.
A specific element in an array is accessed by an index. In C, all arrays consist of contiguous
memory locations. The lowest address corresponds to the first element and the highest address to
the last element. Arrays can have from one to several dimensions.

Single-Dimension Arrays
The general form for declaring a single-dimension array is
type var_name[size];

Like other variables, arrays must be explicitly declared so that the compiler can allocate space for
them in memory. Here, type declares the base type of the array, which is the type of each element
in the array, and size defines how many elements the array will hold.
Ex. int num[10];
char ch[20]
float balance[15]

The amount of storage required to hold an array is directly related to its type and size. For a single
dimension array, the total size in bytes is computed as shown here: total bytes = sizeof(base type)
× length of array.
Individual array elements are accessed using [ ] and index values. The first element in the array
will be having index value 0.
C program to demonstrate to declare and print array
#include <stdio.h>

int main() {
// Declare an array of size 5
int numbers[5];

// Store values in the array


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Display the array elements


printf("The elements of the array are:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}

return 0;
}

Index 0 1 2 3 4

Value 10 20 30 40 50

Address 1000 1004 1008 1012 1016


(example)

In the above example program, size of numbers = 4 x 5 = 20 bytes.

Array Declaration with initialization:

Arrays can be declared and initialized together to assign values at the time of creation.
#include <stdio.h>

int main() {
// Declare and initialize an array of size 5
int numbers[5] = {10, 20, 30, 40, 50};

// Display the array elements


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

return 0;
}

ex.2
#include <stdio.h>

int main() {
// Declare and initialize a character array
char vowels[5] = {'A', 'E', 'I', 'O', 'U'};

// Display the character array


printf("The vowels are:\n");
for (int i = 0; i < 5; i++) {
printf("%c ", vowels[i]);
}

return 0;
}

Generating a Pointer to an Array

You can generate a pointer to the first element of an array by simply specifying the array name,
without any index.

int *p;
int sample[10];
p = sample;
Below program demonstrates accessing array elements using pointer

#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr;

// Point to the first element of the array


ptr = arr;

printf("Accessing array elements using pointer:\n");

for (int i = 0; i < 5; i++) {


// *(ptr + i) gives the value at index i
printf("Element %d = %d\n", i, *(ptr + i));
}

return 0;
}

C program to implement bubble sort


#include <stdio.h>

int main()
{
int n, i, j, temp;

printf("Enter number of elements: ");


scanf("%d", &n);

int a[n];

printf("Enter %d elements:\n", n);


for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
// Bubble Sort
for(i = 0; i < n - 1; i++)
{
for(j = 0; j < n - i - 1; j++)
{
if(a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}

printf("Sorted array:\n");
for(i = 0; i < n; i++)
printf("%d ", a[i]);

return 0;
}

Two Dimensional Arrays:

C supports multidimensional arrays. The simplest form of the multidimensional array is the two-
dimensional array. A two-dimensional array is, essentially, an array of one-dimensional arrays
ex. int d[10][20];
Here d is two-dimensional integer array of size 10,20
int Arr[5][5]
C program to read and print simple 2D array

#include <stdio.h>

int main() {
int rows, cols;

printf("Enter number of rows: ");


scanf("%d", &rows);

printf("Enter number of columns: ");


scanf("%d", &cols);

int a[rows][cols];

// Reading elements
printf("Enter the elements of the 2D array:\n");
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
scanf("%d", &a[i][j]);
}
}

// Printing elements
printf("\nThe 2D array is:\n");
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}

return 0;
}
C program to add two matrixes

#include <stdio.h>

int main() {
int r, c;

// Input number of rows and columns


printf("Enter number of rows: ");
scanf("%d", &r);

printf("Enter number of columns: ");


scanf("%d", &c);

int A[r][c], B[r][c], Sum[r][c];

// Read first matrix


printf("\nEnter elements of Matrix A:\n");
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
scanf("%d", &A[i][j]);
}
}

// Read second matrix


printf("\nEnter elements of Matrix B:\n");
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
scanf("%d", &B[i][j]);
}
}

// Add both matrices


for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
Sum[i][j] = A[i][j] + B[i][j];
}
}

// Print result
printf("\nSum of the two matrices:\n");
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
printf("%d ", Sum[i][j]);
}
printf("\n");
}

return 0;
}

C program to search an element in the given array using binary search method.
#include <stdio.h>

int main() {
int arr[50], n, key, low, high, mid;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter %d elements in ascending order:\n", n);


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

printf("Enter the element to search: ");


scanf("%d", &key);

low = 0;
high = n - 1;

while(low <= high) {


mid = (low + high) / 2;

if(arr[mid] == key) {
printf("Element %d found at position %d\n", key, mid + 1);
return 0; // Exit after finding
}
else if(arr[mid] < key) {
low = mid + 1;
}
else {
high = mid - 1;
}
}

printf("Element %d not found in the array\n", key);

return 0;
}
Strings:

String is an array of characters terminated with a null character(\0).

Declaration:
char name[20];
This creates an array that can store up to 19 characters + \0

char name[20] = "Hello";


This creates an array and initializes. Null character is automatically added.

Another way
char name[] = {'H', 'e', 'l', 'l', 'o', '\0'};

Reading A string:

Using scanf (stops at space):

scanf("%s", name);

Please note that & operator is not required before variable name in scanf statement.

Using gets()
gets(name)
Some compilers won’t support this function as it is unsafe to use. Some compilers supports with
warning message.

Using fgets()
fgets(name, sizeof(name), stdin);
This method is safe to use. Here the first parameter is the name of the string, second parameter is
size of the string and third parameter indicates input is taken from standard input (keyboard).

Printing a String
printf("%s", name);

Simple C Program to read and print a string

#include <stdio.h>

int main() {
char name[20];

printf("Enter your name: ");


scanf(“%s”, name);

printf("You entered: %s", name);

return 0;
}

Common String Functions (string.h)

strlen() – Length of a string


Returns the number of characters excluding \0
int len = strlen("Hello"); // len = 5

strcpy() – Copy one string to another


Copies src → dest
char a[20], b[20] = "BMSCE";
strcpy(a, b);
// a becomes "BMSCE"

strcat() – Concatenate strings


Adds src to the end of dest.
char a[30] = "BMSCE ";
char b[10] = "Bengaluru";
strcat(a, b);
// a becomes "BMSCE Bengaluru"

strcmp() – Compare two strings


Compares character-by-character.
Return Value Meaning
0 strings are equal
>0 str1 > str2
<0 str1 < str2

strchr() – Find first occurrence of a character


Returns pointer to first matching character.
char *p = strchr("Hello", 'l');
// points to first 'l'
strstr() – Find substring inside string
Searches for a smaller string
char *p = strstr("Welcome to C language", "C");
// points to "C language"

C program to demonstrate string functions


#include <stdio.h>
#include <string.h>

int main() {
char a[50] = "Hello";
char b[50] = "World";

printf("Length of a: %d\n", strlen(a));

strcat(a, b);
printf("Concatenated: %s\n", a);

printf("Compare: %d\n", strcmp(a, b));

return 0;
}

Array of Stings:

An array of strings in C is essentially a two-dimensional character array used to store multiple


strings together in a single structure. Since a string in C is represented as a sequence of characters
terminated by a null character (\0), an array of strings means you are creating an array where each
element is itself a character array that can hold one complete string.
For example, in a declaration like

char names[5][20]

the first dimension (5) represents the number of different strings that can be stored, and the second
dimension (20) represents the maximum length of each string including the null terminator. This
allows user to store multiple names or words, such as lists of students or places, in a structured
way. Each row in the 2D array acts as a separate string, and user can access or modify them
individually using indexing like
names[0], names[1], etc.
Program to read and display array of strings
#include <stdio.h>

int main() {
char name[10][30]; // Max 10 names, each up to 29 chars
int n;

printf("Enter number of names (max 10): ");


scanf("%d", &n);

printf("Enter %d names:\n", n);

for(int i = 0; i < n; i++) {


scanf("%29s", name[i]); // Limit to avoid overflow
}

printf("\nYou entered:\n");
for(int i = 0; i < n; i++) {
printf("%s\n", name[i]);
}

return 0;
}
Pointer:

A pointer is a variable that stores the memory address of another variable. Instead of holding a
direct value, it holds the address where the value is stored in memory.

Syntax:
Data_type *name

Ex: int num = 10;


int *ptr;
ptr = &num

#include <stdio.h>
int main ()
{
int num = 10; // integer variable
int *ptr; // pointer variable

ptr = &num; // pointer stores address of num

printf("Value of num = %d\n",num);


printf("Value of num = %d\n",*ptr);//accessing value through pointer
printf("Address of num = %p\n", &num);
printf("Address stored in ptr = %p\n", ptr);//%p for address

return 0;
}

Pointer Assignments:

We can use a pointer on the right-hand side of an assignment statement to assign its value to another
pointer. When both pointers are the same type, the situation is straightforward.
#include <stdio.h>

int main ()
{
int num = 10;
int *p1, *p2;

p1 = &num;
p2 = p1;

printf("Value of num = %d\n",num);


printf("Value of num = %d\n",*p1);
printf("Value of num = %d\n",*p2);

return 0;
}

Void * pointer:

A void pointer in C is a special type of pointer that can store the address of any data type. It is also
known as a generic pointer because it does not have a specific data type associated with it. Since
the compiler does not know what type of data a void pointer points to, it cannot be directly
dereferenced or used in pointer arithmetic. To access the value stored at the address held by a void
pointer, it must first be typecast into an appropriate pointer type, such as int* or float*. Void
pointers are commonly used in situations where a function needs to handle different types of data
using the same pointer, such as in dynamic memory allocation functions (malloc) which return
void*. Thus, a void pointer provides flexibility in programming by allowing pointers to be type-
independent.

#include <stdio.h>

int main() {
int a = 10;
float b = 20.5;
void *ptr; // void pointer

ptr = &a; // store address of integer


printf("Value of a using void pointer = %d\n", *(int *)ptr);

ptr = &b; // store address of float


printf("Value of b using void pointer = %f\n", *(float *)ptr);
return 0;
}

Pointer Arithmetic

Pointer arithmetic in C refers to performing operations like addition or subtraction on pointers so


that they move through memory locations based on the size of the data type they point to.

When you add or subtract a number from a pointer, the pointer does not simply increase by that
number of bytes — instead, it moves by that number multiplied by the size of the data type.

For example, if an integer pointer p points to an integer array, then p + 1 makes the pointer move
to the next integer location in memory, which is typically 4 bytes ahead. Pointer arithmetic helps
access array elements efficiently using pointers instead of array indexing.

However, operations like pointer multiplication or division are not allowed, and arithmetic should
only be performed within the bounds of an allocated memory block to avoid undefined behavior.

#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *p;

p = arr; // pointer points to first element of array

printf("Accessing array elements using pointer:\n");

for(int i = 0; i < 5; i++) {


printf("Element at %d = %d\n", p++, *p); // pointer arithmetic
}

return 0;
}
Array of Pointers

An array of pointers in C is an array where each element is a pointer rather than a normal data
value. Instead of storing actual data like integers or characters, the array stores addresses pointing
to data stored elsewhere in memory.

#include <stdio.h>

int main() {
int a = 10, b = 20, c = 30;

int *ptr[3]; // array of 3 integer pointers

ptr[0] = &a;
ptr[1] = &b;
ptr[2] = &c;

printf("Accessing values using array of pointers:\n");


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

return 0;
}

Multiple Indirection
#include <stdio.h>

int main() {
int a = 10;

int *b; // pointer to integer


int **c; // pointer to pointer

b = &a; // p holds address of x


c = &b; // pp holds address of p

printf("Value of x = %d\n", a);


printf("Value using pointer p = %d\n", *b);
printf("Value using pointer to pointer pp = %d\n", **c);

return 0;
}

Initializing Pointers

When you create a local pointer in C and do not assign it a value, it contains a random
(unknown) address. This is dangerous. If you try to use the pointer before giving it a proper
address, your program will likely crash or behave unpredictably.

Ex. 1

#include <stdio.h>

int main() {
int a = 25;
int *p = &a; // pointer initialized with address of a

printf("Value of a = %d\n", a);


printf("Value using pointer = %d\n", *p);
printf("Address stored in pointer = %p\n", p);

return 0;
}
Ex. 2
#include <stdio.h>

int main() {
char *names[] = {"Ram", "Sita", "Krishna", "Radha"};

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


printf("%s\n", names[i]);
}

return 0;
}

Null Pointer:

A null pointer is a pointer that does not point to any valid memory location.
int *p = 0

You might also like