Introduction to C Programming N Manjunath Gowda
Department of Studies in Mechanical Engineering
University B.D.T. College of Engineering, Davanagere-577004
(A Constituent College of Visvesvaraya Technological University,
Belagavi-590018)
Introduction to C Programming
Module-04
1. Explain a string and how strings are declared and initialized with examples. (7 – marks)
A string is a sequence of characters. e.g. "Programming".
Syntax
char string_name[size];
There are two ways to declaring and initializing a string in c language.
By char array
By string literal
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
char c[] = "abcd";
char c[50] = "abcd";
2. Explain the following string manipulation functions with examples. (15 – marks)
strlen(): This function is used to find the length of a string. It takes a string as input and
returns the number of characters in the string (excluding the null character).
strcpy(): This function is used to copy one string to another. It takes two arguments, the first
argument is the destination string where the source string will be copied and the second
argument is the source string.
strcat(): This function is used to concatenate two strings. It takes two arguments, the first
argument is the destination string where the source string will be appended and the second
argument is the source string.
strcmp(): This function is used to compare two strings. It takes two arguments, the first
argument is the first string and the second argument is the second string. It returns an integer
value that indicates the result of the comparison.
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
strchr(): This function is used to find the first occurrence of a character in a string. It takes
two arguments, the first argument is the string and the second argument is the character to be
searched. It returns a pointer to the first occurrence of the character in the string.
Example:
#include <stdio.h>
#include <string.h>
int main() {
// Declaration and Initialization
char str1[] = "Manjunath";
char str2[20];
char search = 'o';
// strlen - String Length
printf("Length of str1: %lu\n", strlen(str1));
// strcpy - String Copy
strcpy(str2, str1);
printf("After copying, str2: %s\n", str2);
// strcat - String Concatenation
strcat(str2, " welcomes");
printf("After concatenation, str2: %s\n", str2);
// strcmp - String Comparison
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1 is equal to str2\n");
} else if (result < 0) {
printf("str1 is less than str2\n");
} else {
printf("str1 is greater than str2\n");
}
// strchr
char *found = strchr(str1, search);
// Check if the character is found
if (found != NULL) {
printf("'%c' found at position: %ld\n", search, found - str1 + 1);
} else {
printf("'%c' not found in the string.\n", search);
}
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
return 0;
}
3. Describe different ways of reading and writing the strings with examples. (7 – marks)
Reading Strings
scanf()
scanf() reads input until it encounters whitespace, newline or End Of File(EOF). scanf() can read
multiple values of different data types
gets() {Unformatted input function}
gets() reads input until it encounters newline or End Of File(EOF), gets() does not stop reading input
when it encounters whitespace instead it takes whitespace as a string. gets() will only get character
string data.
getchar() {Unformatted input function}
getchar() is a standard library function that takes a single input character from standard input.
Writing Strings
printf()
The printf() function is also used to print data on the console, but it can print the formatted data to the
console based on a specified format string.
puts() {Unformatted output function}
The puts() function is used to write a string to the console and it automatically adds a new line
character ‘\n’ at the end.
putchar() {Unformatted output function}
The putchar() function outputs a single character to the console.
Example:
#include <stdio.h> #include <stdio.h>
int main() { int main() {
char name[20]; char name[20];
printf("Enter name: "); printf("Enter name: ");
scanf("%s", name); gets(name);
printf("Your name is %s.", name); puts(name);
return 0; } return 0; }
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
#include <stdio.h>
int main() {
char c;
printf("Enter some character:\n");
c = getchar();
printf("\n Entered character is: ");
putchar(c);
return 0; }
4. What is an array. Explain declaration and initialization of 1D and 2D arrays. (7 – marks)
1D Array
An array is defined as the collection of similar type of data items.
Syntax of 1D array
Declaration
int marks[5];
Initialization
marks[0]=80;
marks[1]=75;
marks[2]=60;
marks[3]=72;
marks[4]=78;
Declaration and Initialization
2D Array
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices
which can be represented as the collection of rows and columns.
Syntax of 2D array
data_type array_name[rows][columns];
Declaration and Initialization
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int matrix[2][3] = { 1, 4, 2, 3, 6, 8 };
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
5. Explain the representation of 2D array in memory. (7 – marks)
A 2D array is represented in memory as a contiguous block of storage where the elements are arranged
in rows and columns. The specific representation can vary based on the programming language and
memory layout conventions.
Consider an array, int arr[3][3];
In row major ordering, all the rows of the 2D array are stored into the memory contiguously.
Considering the array shown in the above image, its memory allocation according to row major order
is shown as follows.
first, the 1st row of the array is stored into the memory completely, then the 2nd row of the array is
stored into the memory completely and so on till the last row.
6. What is binary search algorithm? Explain. (5 – marks)
Binary search is a search algorithm used to find the position of a target value within a sorted array. It
works by repeatedly dividing the search interval in half until the target value is found or the interval is
empty. The search interval is halved by comparing the target element with the middle value of the
search space.
Binary Search Algorithm
Below is the step-by-step algorithm for Binary Search:
Divide the search space into two halves by finding the middle index “mid”.
Compare the middle element of the search space with the key.
If the key is found at middle element, the process is terminated.
If the key is not found at middle element, choose which half will be used as the next search
space.
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
o If the key is smaller than the middle element, then the left side is used for next search.
o If the key is larger than the middle element, then the right side is used for next search.
This process is continued until the key is found or the total search space is exhausted.
7. Explain different types of storage classes in C, with examples (8 – marks)
Storage classes in C are used to define the scope, visibility, and lifetime of variables and functions.
The four main storage classes are automatic (auto), external (extern), static (static), and register
(register). Each storage class has its own unique properties and use cases.
In simpler terms, storage classes help us understand where a variable or function can be used, who can
use it, and how long it will last in the program.
Automatic (auto)
The automatic storage class is the default storage class for local variables in C. Variables declared
within a block (i.e., between { and }) without any storage class specifier are automatically assigned the
auto storage class.
External (extern)
The external storage class is used to declare variables or functions that are defined in another file. The
extern keyword is used to declare variables or functions with external linkage.
Static (static)
The static storage class is used to declare variables or functions with internal linkage, which means
they are only accessible within the file in which they are declared. The static keyword is used to
declare variables or functions with static storage class.
Register (register)
The register storage class is used to declare variables that should be stored in a CPU register instead of
RAM. The register keyword is used to declare variables with register storage class.
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
Programs
Mean of n numbers using array
#include <stdio.h>
int main()
{
int arr[20], n, i;
float mean=0, sum =0;
printf (" Enter the Numbers of elements: ");
scanf("%d",&n);
printf("\n Enter the Numbers : \n");
for(i=0; i<=n; i++ )
{ printf("\n arr[%d]=",i);
scanf("%d", &arr[i]);
}
for (i=1 ; i<=n ; i++ )
{ sum = sum + arr[i];
mean = sum / n;
}
printf("\n Mean of entered Numbers are : %f ", mean);
return 0;
}
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
Largest of n numbers using array
#include <stdio.h>
int main()
int arr[20], n, i, large = -1111;
printf (" Enter the Numbers of elements: ");
scanf("%d",&n);
printf("\n Enter the Numbers : \n");
for(i=0; i<=n; i++ )
{ printf("\n arr[%d]=",i);
scanf("%d", &arr[i]);
for (i=1 ; i<=n ; i++ )
{ if(arr[i]>large)
large = arr[i];
}
printf("\n The largest number in the array is : %d ",
large);
return 0;
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
Sorting array elements in ascending order
#include <stdio.h>
void main (){
int num[20];
int i, j, temp, n;
printf("enter number of elements in an array:\n");
scanf("%d", &n);
printf("Enter the elements:\n");
for (i = 0; i < n; ++i)
scanf("%d", &num[i]);
for (i = 0; i < n-1; ++i){
for (j = 0; j < n-1-i; ++j){
if (num[j] > num[j+1]){
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
printf("The numbers in ascending order are:");
for (i = 0; i < n; ++i){
printf("%d \t", num[i]);
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
To reverse the order of numbers in an array
#include <stdio.h>
int main ()
int a[10]={8,25,2,11,51,29,23,58,13,47};
int i;
printf("Original order \n");
for (i=0;i<=9;i++)
printf("%d \t",a[i]);
printf("\n");
printf("Reverse order \n");
for (i=9;i>=0;i--)
printf("%d \t“,a[i]);
return 0;
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
Length of a string without using built-in functions
#include <stdio.h>
int main()
char str[100];
int i,length=0;
printf("Enter a string: \n");
scanf("%s",str);
for(i=0; str[i]!='\0'; i++)
{ length++; }
printf("\nLength of input string: %d",length);
return 0;
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
String comparison without using built-in functions
#include <stdio.h>
#include <string.h>
int main()
char Str1[100], Str2[100];
int result, i;
printf("\n Please Enter the First String : ");
gets(Str1);
printf("\n Please Enter the Second String : ");
gets(Str2);
for(i = 0; Str1[i] == Str2[i] && Str1[i] == '\0'; i++);
if(Str1[i] < Str2[i])
{ printf("\n str1 is Less than str2"); }
else if(
Str1[i] > Str2[i])
{ printf("\n str2 is Less than str1"); }
else { printf("\n str1 is Equal to str2"); }
return 0;
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
Binary search for integers
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int x)
{
while (low <= high)
{ int mid = low + (high - low) / 2;
// Check if x is present at mid
if (arr[mid] == x)
return mid;
// If x greater, ignore left half
if (arr[mid] < x)
low = mid + 1;
// If x is smaller, ignore right half
else
high = mid - 1;
}
// If we reach here, then element was not present
return -1;
}
// Driver code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
if(result == -1)
printf("Element is not present in array");
else printf("Element is present at index %d",result); }
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
Matrix Multiplication
#include <stdio.h>
#define N 3 // Size of square matrices
int main() {
int matrix1[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int matrix2[N][N] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int result[N][N];
int i, j, k;
// Multiply the two matrices
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
int sum = 0;
for (k = 0; k < N; k++) {
sum += matrix1[i][k] * matrix2[k][j];
}
result[i][j] = sum;
}
}
// Print the resulting matrix
printf("Result Matrix:\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
Transpose a Matrix
#include<stdio.h>
int main(){
int m, n;
printf("Enter the number of rows: ");
scanf("%d", &m);
printf("Enter the number of columns: ");
scanf("%d", &n);
int matrix[10^5][10^5];
printf("Enter the elements of the matrix:\n");
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
scanf("%d", &matrix[i][j]);
}
}
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
printf("The transposed matrix is:\n");
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0; }
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
Program to store and print the elements of an array
#include <stdio.h>
// Main function
int main()
{
int arr[10]; // Declare an array of size 10 to store integer values
int i;
// Print a message to prompt the user for input
printf("\n\nRead and Print elements of an array:\n");
printf("-----------------------------------------\n");
// Prompt the user to input 10 elements into the array
printf("Input 10 elements in the array :\n");
for(i=0; i<10; i++)
{
printf("element - %d : ",i); // Prompt the user to input the i-th element
scanf("%d", &arr[i]); // Read the input and store it in the array
}
// Display the elements in the array
printf("\nElements in array are: ");
for(i=0; i<10; i++)
{
printf("%d ", arr[i]); // Print each element in the array
}
printf("\n");
return 0;
}
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
Largest of n numbers using array
#include <stdio.h>
int main() {
int arr[] = {30, 15, 25, 40, 20};
int max = arr[0];
for (int i = 1; i < 5; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
printf("Largest element in array: %d\n", max);
return 0;
}
Smallest of n numbers using array
#include <stdio.h>
int main() {
int arr[] = {30, 15, 25, 40, 20};
int min = arr[0];
for (int i = 1; i < 5; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
printf("Smallest element in array: %d\n", min);
return 0;
}
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
Sorting array elements in ascending order (Bubble sort)
#include <stdio.h>
int main() {
int arr[] = {30, 15, 25, 40, 20};
// Calculate the size of the array
int size = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Sort the array using bubble sort
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Sorted array (ascending): ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
Duplicate elements in an array
#include <stdio.h>
int main() {
int arr[] = {5, 10, 15, 20, 25, 10, 30, 25};
int size = sizeof(arr) / sizeof(arr[0]); // Calculate
the size of the array
printf("Duplicate elements in array: ");
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (arr[i] == arr[j]) {
printf("%d ", arr[i]);
break;
}
}
}
printf("\n");
return 0;
}
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda
Addition of two matrices
#include <stdio.h>
int main() {
int mat1[3][3], mat2[3][3], sum[3][3];
printf("Enter elements of first matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &mat1[i][j]);
}
}
printf("Enter elements of second matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &mat2[i][j]);
}
}
printf("Sum of the matrices:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum[i][j] = mat1[i][j] + mat2[i][j];
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
Department of Mechanical Engineering, UBDTCE, Davangere