Monday, June 16, 2025

Programming in C — Arrays & Strings - KTU Module 1

 Arrays

An array is a variable that can store multiple values. For example, if you want to store 5 integers, you can create an array for it.

To create an array, define the data type (like int) and specify the name of the array followed by square brackets [].

To insert values to it, use a comma-separated list inside curly braces, and make sure all values are of the same data type:

//Syntax for Defining an Array
data_type array_name[array_size];

//Example
int numbers[5]; // array of 5 integers

//Array Initialization
int numbers[5] = {1, 2, 3, 4, 5};

//Accessing Array Elements - Array indices start from 0

numbers[4] = 10; // assigns 10 to the 5th element

scanf("%d", &numbers[2]); // take input and store it in the 3rd element

scanf("%d", &numbers[i-1]); // take input and store it in the ith element

printf("%d", numbers[0]); // print the first element

printf("%d", numbers[2]); // print the third element

printf("%d", numbers[i-1]); // print the ith element

NOTE:

1. It’s important to note that the size and type of an array cannot be changed once it is declared.

2. Arrays have 0 as the first index, not 1, example, array[0] is the first element.

3. If the size of an array is n, to access the last element, the n-1 index is used., example, array[4]

Example

// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array

#include <stdio.h>

int main() {

int values[5];

printf("Enter 5 integers: ");

// taking input and storing it in an array
for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of the array
for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}

Here, we have used a for loop to take five inputs and store them in an array. Then, these elements are printed using another for loop.

Enumerated Data Type

In C, an enumerated type (enum) is a user-defined data type that assigns names to integral constants. It enhances code readability and maintainability by using meaningful names instead of raw numbers.

Key characteristics:

  • User-defined type: Created using the enum keyword.
  • Named constants: Associates names with integer values.
  • Integral values: Each enum member is implicitly assigned an integer value, starting from 0 by default.
  • Scope: Each enum member must have a unique scope within its enum definition.
//Syntax
enum enum_name {value1, value2, ..., valueN};

//Example
enum week {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
enum week today = Wed;
printf("%d", today); // Output: 3 (index starts from 0)

Type Definition

Type definition refers to specifying the kind of data a variable can hold. C provides several built-in data types such as int for integers, char for characters, float for single-precision floating-point numbers, and double for double-precision floating-point numbers.

Type Definition Using typedef:

The typedef keyword is used to create an alias or a new name for an existing data type. This can make code more readable, especially when dealing with complex data types.

// Example using typedef
typedef int myInteger;
typedef unsigned long ulong;

int main() {
myInteger num1 = 10; // Using the alias 'myInteger'
ulong num2 = 100; // Using the alias 'ulong'

// ...
return 0;
}

NOTE:

typedef does not create a new data type; it only creates an alias for an existing one.

It can be used with built-in data types, user-defined data types (like struct and union), and function pointers.

typedef improves code readability by providing descriptive names for complex data types.

It can help in writing more maintainable code by reducing the impact of changes in data type declarations.

Two Dimensional Arrays

A two-dimensional array in C is essentially an array of arrays, often visualized as a table with rows and columns. It’s a way to organize data in a grid-like structure, where each element is accessed using two indices: the row and the column number.

To declare a 2D array, you specify the data type, the array name, and the number of rows and columns within square brackets:

//Syntax
dataType arrayName[rows][columns];

//Example
int array[3][4];

//Iniatialization
int array[2][2] = {{1, 2}, {3, 4}};

int value = array[1][2]; // Accesses the element at row 1, column 2

Similarly, you can declare a three-dimensional (3d) array. For example,

int array[2][4][3];

Here, the array can hold 24 elements.

Examples:

Matrix Input and Output

#include <stdio.h>

int main() {
int a[2][2], i, j;

// Input
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
scanf("%d", &a[i][j]);

// Output
for(i = 0; i < 2; i++) {
for(j = 0; j < 2; j++)
printf("%d ", a[i][j]);
printf("\n");
}
return 0;
}

Sequential Search in an Array

#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50}, key = 30, i, found = 0;

for(i = 0; i < 5; i++) {
if(arr[i] == key) {
printf("Element found at index %d\n", i);
found = 1;
break;
}
}

if(!found)
printf("Element not found\n");

return 0;
}

Bubble Sort Program

#include <stdio.h>

int main() {
int a[5] = {5, 3, 4, 1, 2}, i, j, temp;

for(i = 0; i < 5-1; i++) {
for(j = 0; j < 5-1-i; j++) {
if(a[j] > a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}

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

return 0;
}

Strings

In C, strings are arrays of characters ending with a null character '\0'.

Declaring a String Variable

//Declaring a String Variable
char str[20];
//This declares a string that can hold up to 19 characters (last one for \0).

//Initializing Strings
//You can initialize strings in a number of ways.
char str[] = "abcd";
char str[50] = "abcd";
char str[] = {'a', 'b', 'c', 'd', '\0'};
char str[5] = {'a', 'b', 'c', 'd', '\0'};

//Displaying a String
printf("%s", str);

Let’s take another example:

char c[5] = "abcde";

Here, we are trying to assign 6 characters (the last character is '\0') to a char array having 5 characters. This is bad and you should never do this.

Assigning Values to Strings

Arrays and strings are second-class citizens in C; they do not support the assignment operator once it is declared. For example,

char str[100];
str = "C programming"; // Error! array type is not assignable.

Read String from the user

You can use the scanf() function to read a string.

The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).

Example,

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

Output

Enter name: Divya Stephen
Your name is Divya.

Even though Divya Stephen was entered in the above program, only “Divya” was stored in the name string. It’s because there was a space after Divya.

NOTE THAT:

We have used the code name instead of &name with scanf(). This is because name is a char array, and we know that array names decay to pointers in C.

Thus, the name in scanf() already points to the address of the first element in the string, which is why we don't need to use &.

You can use the fgets() function to read a line of string. And, you can use puts() to display the string.

Using gets() also reads full line but its unsafe, deprecated in newer standards)

String Library Functions (from <string.h>)

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

int main() {
char str1[20] = "Hello";
char str2[20] = "World";

printf("Length: %lu\n", strlen(str1));
strcat(str1, str2);
printf("Concatenated: %s\n", str1);

strcpy(str2, "New");
printf("Copied: %s\n", str2);

int cmp = strcmp(str1, str2);
if(cmp == 0)
printf("Strings are equal\n");
else
printf("Strings are not equal\n");

return 0;
}

Program: String Matching

//This program checks if two strings are equal.

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

int main() {
char str1[100], str2[100];

printf("Enter first string: ");
scanf("%s", str1);

printf("Enter second string: ");
scanf("%s", str2);

if(strcmp(str1, str2) == 0)
printf("Strings match!\n");
else
printf("Strings do not match.\n");

return 0;
}

Program to Find a Substring

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

int main() {
char str[100], sub[20];

printf("Enter the main string: ");
scanf("%s", str);

printf("Enter the substring to find: ");
scanf("%s", sub);

if(strstr(str, sub) != NULL)
printf
("Substring found!\n");
else
printf("Substring not found.\n");

return 0;
}