School of Engineering and Technology
Module 3 -Array Strings and Storage Classes
SL QUESTIONS MARKS COs BL
NO
1. What is an array? Write the syntax for array. 2 3 1
Ans: A Dimensional array is a structure created in the memory to
represent a number of values of the same data type with the
variables having the same variable name along with different
subscripts. A Dimensional array is also called Subscripted
Variable.
Syntax:
1. Single dimensional/Single Subscripted array:
<Data type><variable>[ ] = <Data type><[Number of values to
stored]>
2. Double Dimensional/Multi-Dimensional /Double
Subscripted Array:
<Data type><variable>[ ] = <Data type><[row
value]><[column value]
2. What is an array in C? Explain with an example. 2 3 1
Ans: A Dimensional array is a structure created in the memory to
represent a number of values of the same data type with the
variables having the same variable name along with different
subscripts. A Dimensional array is also called Subscripted
Variable.
It is of two types:
1. Single Dimensional Array
2. Multi-Dimensional Array
For example:
int scores[5] = {10, 20, 30, 40, 50};
This array scores has 5 elements of type int.
3. How do you declare an array of integers with 10 elements in 2 3 3
C?
Ans: To declare an array of integers with 10 elements in C, you can
use the following syntax:
int array_name[10];
Example:
int arr[10];
4. Write the syntax to initialize an array of 5 floats with values 2 3 3
1.1, 2.2, 3.3, 4.4, and 5.5.
Ans: The syntax to initialize an array of 5 floats with values 1.1, 2.2,
3.3, 4.4, and 5.5 is:
School of Engineering and Technology
float scores[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
5. Explain how to find the length of an array in C. 2 3 2
Ans: To find the length of an array in C, you can use the following
formula:
length = sizeof(array) / sizeof(array[0]);
Example:
int scores[5] = {10, 20, 30, 40, 50};
int length = sizeof(scores) / sizeof(scores[0]);
printf("Length of array: %d\n", length);
6. Explain how string is defined in C. List the various inbuilt 2 3 2
string functions.
Ans: A set of characters within double quotes is known as String.
It is also known as an array of characters.
A string may consist of a set of only letters, a set of
alphanumeric characters or a set of only digits.
• The various inbuilt string functions are in in string
library #include<string.h> are:
1. strcpy(): Copies one string to another.
2. strcat(): Concatenates two strings.
3. strlen(): Returns the length of a string.
4. strcmp(): Compares two strings.
5. strchr(): Returns a pointer to the first occurrence of
a character in a string.
6. strrchr(): Returns a pointer to the last occurrence of
a character in a string.
7. Explain strcat(), strlen() and strcpy() functions with examples. 2 3 1
Ans: Here are explanations of the strcat(), strlen(), and strcpy()
functions with examples:
- strcat(): Concatenates two strings.
char str1[10] = "Hello";
char str2[10] = "World";
strcat(str1, str2);
printf("%s\n", str1);
Output: HelloWorld
- strlen(): Returns the length of a string.
char str[10] = "Hello";
int length = strlen(str);
printf("Length of string: %d\n", length);
School of Engineering and Technology
Output: 5
- strcpy(): Copies one string to another.
char str1[10] = "Hello";
char str2[10];
strcpy(str2, str1);
printf("%s\n", str2);
Output: Hello
8. Define a string in C 2 3 1
Ans: A set of characters within double quotes is known as String.
It is also known as an array of characters.
A string may consist of a set of only letters, a set of
alphanumeric characters or a set of only digits.
9. What is the null character in a string, and why is it important? 2 3 2
Ans: The null character (\0) is a special character that marks the
end of a string in C.
• It is important because it allows functions to know
when to stop processing a string.
10. How do you declare a string in C? Provide an example. 2 3 2
Ans: To declare a string in C.
The Syntax is:
char string_name[string_length];
Example:
char name[10] = "John";
11. Write a C statement to initialize a string with "Hello". 2 3 3
Ans: Here is a C statement to initialize a string with "Hello":
char str[10] = "Hello";
(OR)
char str[10] = {'H', 'E', 'L', 'L', 'O', '\0'};
12. Write a C statement to print a string using printf. 2 3 2
Ans: Here is a C statement to print a string using printf:
int main(){
char str[100] = “Hello”;
printf("%s\n", str);
return 0; }
13. Define Automatic variables (Local variable). 2 3 1
School of Engineering and Technology
Ans: Automatic variables, also known as local variables, are
variables that are declared within a function or block and
cannot be accessed outside the function or the block but only
can be accessed inside the function or the block.
14. Define External variables and Static variables. 2 3 1
Ans: External variables are variables that are declared outside of a
function or block and are accessible from multiple functions or
blocks.
Static variables are variables that are declared within a
function or block and retain their value between function calls.
15. Define Register variables. 2 3 1
Ans: Register variables are variables that are stored in a register
instead of memory, which can improve performance. They are
declared using the register keyword.
16. Explain the declaration and initialization of one dimensional 5 3 2
and two-dimensional array with an example.
Ans: Declaration syntax for single dimensional array:
<data_type> <array_name>[array_size];
For Example:
int scores[5];
Declaration syntax for double dimensional array:
<data_type> <array_name>[row_size][column_size];
For Example:
int matrix[3][4];
Initialization syntax for single dimensional array:
<array_name>[array_size] = {values};
For Example:
int scores[5] = {10, 20, 30, 40, 50};
Initialisation syntax for double dimensional array:
<array_name>[row size][column size] = {values};
For Example:
int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8},{9, 10, 11, 12}};
17. Define array. Explain with suitable example how to declare 5 3 1
and initialize 1D array
Ans: An array is a collection of elements of the same data type
stored in contiguous memory locations.
A Dimensional array is a structure created in the memory to
represent a number of values of the same data type with the
variables having the same variable name along with different
subscripts. A Dimensional array is also called Subscripted
Variable.
School of Engineering and Technology
For Example:
int main()
{
int arr[100] = {12 , 34 , 56 , 90};
// Here both declaration and initialisation are done at once.
int n = sizeof(arr)/sizeof(arr[0]);
for(int i = 0; i<=n; i++)
printf(“%d\n”,arr[i]);
return 0;
}
18. What is array? Give example and advantages of array. 5 3 1
Ans: A Dimensional array is a structure created in the memory to
represent a number of values of the same data type with the
variables having the same variable name along with different
subscripts. A Dimensional array is also called Subscripted
Variable.
For Example:
int main()
{
int arr[100] = {12 , 34 , 56 , 90};
// Here both declaration and initialisation are done at once.
int n = sizeof(arr)/sizeof(arr[0]);
for(int i = 0; i<=n; i++)
printf(“%d\n”,arr[i]);
return 0;
}
The Advantages of Array are:
1. Efficient Memory Usage: Arrays store elements of the
same data type in contiguous memory locations, making
efficient use of memory.
2. Fast Access Time: Array elements can be accessed
directly using their index, making it a fast operation.
3. Easy to Implement: Arrays are a fundamental data
structure and are easy to implement in most programming
languages.
4. Cache-Friendly: The contiguous memory allocation of
arrays makes them cache-friendly, which can improve
performance.
5. Simple to Understand: Arrays are a simple and intuitive
data structure, making them easy to understand and work
with.
6. Supports Random Access: Arrays support random
access, meaning elements can be accessed directly without
having to traverse the entire array.
7. Efficient for Large Datasets: Arrays are efficient for
storing and manipulating large datasets.
8. Improves Code Readability: Using arrays can improve
School of Engineering and Technology
code readability by making it clear what data is being stored
and manipulated.
19. What is String? Write a program in C to reverse the input 5 3 3
string.
Ans: A string is an array of characters terminated by a null
character.
• Here is a program to reverse the input string:
#include<stdio.h>
#include<string.h>
void reverse(char* str) {
// Initialize first and last pointers.
int first = 0;
int last = strlen(str) - 1;
char temp;
// Swap characters till first and last meet.
while (first < last) {
// Swap characters
temp = str[first];
str[first] = str[last];
[last] = temp;
// Move pointers towards each other.
first++;
last--; }
}
int main() {
char str[100] = "sapthagiri NPS university";
// Reversing string.
reverse(str);
printf("%s\n", str);
return 0; }
Output: Enter a string: sapthagiri NPS university
Reverse of the string: ytisrevinu SPN irigahtpas
20. How do you find the length of a string in C? Which library 5 3 3
function is used?
Ans: C program to find length of string:
#include<stdio.h>
int stringLen(char *str)
{
int length = 0;
// Loop till the NULL character is found.
while (*str != '\0')
School of Engineering and Technology
{
length++;
// Move to the next character.
str++;
}
return length;
}
int main() {
char str[1000] = "sapthagiri NPS university";
int length = stringLen(str);
printf("Length of the String is %d", length);
return 0;
}
Output:
Length of the string : 25
• Instead of writing this Big Programme we can use a string
library function:
strlen(argument);
Code:
#include<stdio.h>
#include<string.h>
int main() {
char str[1000] = "sapthagiri NPS university";
int length = stringlen(str);
printf("Length of the String is %d", length);
return 0;
}
21. Explain the difference between character array and string in 5 3 2
C.
Ans: In C, a character array and a string are often used
interchangeably, but there is a subtle difference:
Character Array: String:
- A character array is a - A string is a special type of
collection of characters character array that is null-
stored in contiguous memory terminated (\0).
locations.
- It can contain any - The null character
characters, including null indicates the end of the
characters (\0). string.
- It does not necessarily have - It is a sequence of
to be null-terminated. Usage: characters terminated by a
- Character arrays can be null character (\0).
used for any type of - Strings are typically used
character data. for text processing
School of Engineering and Technology
- Example: char arr[5] ={'H', - Example: char str[6] = {'H',
'E', 'L', 'L', 'O'}; 'E', 'L', 'L', 'O', '\0'}
(or)
char str[] = "HELLO";
22. Explain how the strcpy() function works internally. Provide an 5 3 2
implementation example.
Ans: The strcpy() function copies a source string to a destination
string.
* The strcpy() function works internally by following ways:
1. Source and Destination Pointers: The function takes two
arguments: dest (destination string pointer) and src (source
string pointer).
2. Null-Termination Check: The function checks if the source
string is null-terminated. If not, it will lead to undefined
behaviour.
3. Character-by-Character Copy: The function iterates
through each character of the source string, copying it to the
corresponding position in the destination string.
4. Null-Termination: After copying all characters, the function
appends a null character (\0) to the end of the destination
string to ensure its properly terminated.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int main(){
int i=0,j=0;
char arStr[40] , acRev[40] , acTempStr[40];
printf(“\n Enter a string”);
scanf(“%s”, acStr);
for(i=strlen(arStr) - 1 ; i>=0 ; i- -){
if(isalpha(arStr[i]))
{
acTempStr[j++] = acStr[i];
}
}
acTempStr[j] = ‘\0’;
strcpy(aeRevStr , acStr);
i=0;
j=0;
while(arRevStr[i]!=‘\0’)
{
if(isalpha(arRevStr[i]))
{
acRevStr[i] = acTempStr[j];
i++;
j++;
School of Engineering and Technology
}
else{
i++;
}
}
printf(“\n Input String :%s\n”,acStr);
printf(“\n Output String :%s\n”,acRevStr);
return 0;
}
23. Write a C program to search an element using linear and 10 3 2
binary techniques.
Ans: 1. Program to search an element using linear search:
#include<stdio.h>
int linearSearch(int* arr, int size, int key)
{
for (int i = 0; i < size; i++)
{
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main() {
int arr[10] = { 3, 4, 1, 7, 5, 8, 11, 42, 3, 13 };
int size = sizeof(arr)/sizeof(arr[0]);
int key = 4;
int index = linearSearch(arr, size, key);
if (index == -1) {
printf("The element is not present in the arr.");
}
else {
printf("The element is present at arr[%d].", index);
}
return 0;
}
Output: The element is present at arr[1].
2. Program to search an element using Binary Search:
#include<stdio.h>
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
School of Engineering and Technology
if (arr[mid] > x) {
return binarySearch(arr, l, mid - 1, x);
}
return binarySearch(arr, mid + 1, r, x);
} return -1;
}
int main(void) {
int arr[] = { 2, 3, 4, 10, 40 };
int size =sizeof(arr)/sizeof(arr[0]);
int x = 10;
int index = binarySearch(arr, 0, size - 1, x);
if (index == -1) {
printf("Element is not present in array");
}
else {
printf("Element is present at index %d", index);
}
return 0;
}
Output: Element is present at index 3
24. Write a C program for [consider integer data] 10 3 2
(i) Bubble sort (ii) Linear search
Ans: (i) Bubble sort: Code:
// C program for implementation of Bubble sort
#include<stdio.h>
// Swap function
void swap(int* arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
// Last i elements are already in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr, j, j + 1);
}
// Function to print an array
void printArray(int arr[], int size)
{
int i;
School of Engineering and Technology
for (i = 0; i < size; i++)
printf("%d ", arr[i]); printf("\n");
}
// Driver code
int main() {
int arr[] = { 5, 1, 4, 2, 8 };
int N = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, N);
printf("Sorted array: ");
printArray(arr, N);
return 0;
}
Output:
Sorted array:
12458
(ii) Linear search: Code:
#include<stdio.h>
int linearSearch(int* arr, int size, int key)
{
for (int i = 0; i < size; i++)
{
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main() {
int arr[10] = { 3, 4, 1, 7, 5, 8, 11, 42, 3, 13 };
int size = sizeof(arr)/sizeof(arr[0]);
int key = 4;
int index = linearSearch(arr, size, key);
if (index == -1) {
printf("The element is not present in the arr.");
}
else {
printf("The element is present at arr[%d].", index);
}
return 0;
}
Output: The element is present at arr[1].
25. Define an array. Explain declaration and initialization of one 10 3 2
dimensional, two dimensional and multi-dimensional arrays.
Ans: A Dimensional array is a structure created in the memory to
represent a number of values of the same data type with the
School of Engineering and Technology
variables having the same variable name along with different
subscripts. A Dimensional array is also called Subscripted
Variable.
Declaration syntax for single dimensional array:
<data_type> <array_name>[array_size];
For Example:
int scores[5];
Declaration syntax for double/ multi-dimensional array:
<data_type> <array_name>[row_size][column_size];
For Example:
int matrix[3][4];
Declaration syntax for single dimensional array:
<data_type> <array_name>[array_size];
For Example:
int scores[5];
Initialization syntax for double/ multi-dimensional array:
<array_name>[row size][column size] = {values};
For Example:
int matrix[3][4] = {{1, 2, 3, 4},{5, 6, 7, 8},{9, 10, 11, 12}};
26. Explain two-dimension arrays and write a program to read 10 3 2
and write a 2D array.
Ans: Double Dimensional array is a structure created in the
memory to contain the data values by using rows and columns.
A Double Dimensional array is also referred to as a double
subscripted variable because it uses two types of subscripts,
one for the rows number and the other for the column number
to represent any element of the array.
This declares a 2D array matrix with 3 rows and 4 columns.
Program to Read and Write a 2D Array:
#include <stdio.h>
int main() {
int rows, cols;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
int matrix[rows][cols];
// Read the 2D array
printf("Enter the elements of the matrix:\n");
for (int i = 0; i < rows; i++) {
School of Engineering and Technology
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Write the 2D array
printf("The matrix is:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
27. What is string? Write a program to concatenate two strings 10 3 3
without using built in function.
Ans: A string is an array of characters terminated by a null
character.
Program to concatenate two strings without using built in
function:
#include <stdio.h>
// Function to calculate the length of a string
int stringLength(const char *str) {
int length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}
// Function to concatenate two strings
void concatenateStrings(char *dest, const char *src) {
int destLength = stringLength(dest);
int srcLength = stringLength(src);
// Check if the destination array has enough space
// to hold the concatenated string
// For simplicity, we assume it does
// Copy the source string to the end of the destination string
for (int i = 0; i <= srcLength; i++) {
dest[destLength + i] = src[i];
}
}
int main() {
School of Engineering and Technology
char str1[20] = "Hello, ";
char str2[] = "World!";
printf("String 1: %s\n", str1);
printf("String 2: %s\n", str2);
concatenateStrings(str1, str2);
printf("Concatenated String: %s\n", str1);
return 0;
}
Output:
String 1: Hello,
String 2: World!
Concatenated String: Hello, World!
28. Write a program to copy one string into another and count the 10 3 3
number of characters copied.
Ans: Code:
#include <stdio.h>
int main() {
char source[] = "Hello, World!";
char target[20];
int count = 0;
// Copy characters from source to target and count
while (source[count] != '\0') {
target[count] = source[count];
count++;
}
// Add null terminator to target
target[count] = '\0';
printf("Source string: %s\n", source);
printf("Target string: %s\n", target);
printf("Number of characters copied: %d\n", count);
return 0;
}
Output:
Source string: Hello, World!
Target string: Hello, World!
Number of characters copied: 13
29. Write a short note on storage classes. 5 3 1
Ans: Storage Classes in C:
School of Engineering and Technology
In C, a storage class determines the scope, visibility, and
lifetime of a variable. There are four storage classes:
1. Auto: Variables declared inside a function or block with the
auto keyword have automatic storage class. They are created
when the function is called and destroyed when the function
returns.
Default storage class for local variables.
2. Register: Variables declared with the register keyword have
register storage class. They are stored in a register for faster
access.
Keyword: register
3. Static: Variables declared with the static keyword have
static storage class. They retain their value between function
calls and are initialized only once.
Keyword: static
4. Extern: Variables declared with the extern keyword have
external storage class. They are shared among multiple files
and have global scope.
Keyword: extern
Understanding storage classes is essential for managing
memory and variables effectively in C programming.
30. Write a program to store 20 numbers in an array. Then find 20 3 3
out Sum, Maximum and Average of these 20 numbers.
Ans: Code:
#include <stdio.h>
int main() {
int numbers[20];
int sum = 0;
int max;
float average;
// Input 20 numbers
printf("Enter 20 numbers:\n");
for (int i = 0; i < 20; i++) {
scanf("%d", &numbers[i]);
}
// Calculate sum and find maximum
max = numbers[0];
for (int i = 0; i < 20; i++) {
sum += numbers[i];
if (numbers[i] > max) {
max = numbers[i];
}
}
School of Engineering and Technology
// Calculate average
average = (float) sum / 20;
// Print results
printf("Sum: %d\n", sum);
printf("Maximum: %d\n", max);
printf("Average: %.2f\n", average);
return 0;
}
31. Write a program to find out the largest of an array. 20 3 3
Ans: Code:
#include <stdio.h>
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
printf("Largest element: %d\n", max);
return 0;
}
Output:
Enter the number of elements: 5
Enter 5 elements:
10
20
30
40
50
Largest element: 50
32. a) Write a C program to convert lowercase string to uppercase 20 3 3
using array
School of Engineering and Technology
b) Write a C program to convert uppercase string to lowercase
Ans: using array.
a) Code: Program to convert lowercase string to uppercase
using array:
#include <stdio.h>
int main() {
char str[100];
printf("Enter a lowercase string: ");
scanf("%[^\n]s", str);
// Convert lowercase to uppercase
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = str[i] - 32; // Convert to uppercase
}
}
printf("Uppercase string: %s\n", str);
return 0;
}
Output:
Enter a lowercase string: hello world
Uppercase string: HELLO WORLD
b) Code: Program to convert uppercase string to lowercase
using array:
#include <stdio.h>
int main() {
char str[100];
printf("Enter an uppercase string: ");
scanf("%[^\n]s", str);
/* The \n in the format string tells scanf to read and discard
any whitespace characters (including newlines) until it
encounters a non-whitespace character */
// Convert uppercase to lowercase
for (int i = 0; str[i] != '\0'; i++) {
School of Engineering and Technology
if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = str[i] + 32; // Convert to lowercase
printf("Lowercase string: %s\n", str);
return 0;
Output:
Enter an uppercase string: HELLO WORLD
Lowercase string: hello world
33. Write a C program to read 10 numbers from user and store 20 3 3
them in an array. Display Sum, Minimum and Average of the
numbers.
Ans: #include <stdio.h>
int main() {
int numbers[10];
int sum = 0;
int min;
float average;
// Read 10 numbers from user
printf("Enter 10 numbers:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &numbers[i]);
}
// Calculate sum and find minimum
min = numbers[0];
for (int i = 0; i < 10; i++) {
sum += numbers[i];
if (numbers[i] < min) {
min = numbers[i];
}
}
// Calculate average
average = (float) sum / 10;
// Display results
printf("Sum: %d\n", sum);
School of Engineering and Technology
printf("Minimum: %d\n", min);
printf("Average: %.2f\n", average);
return 0;
}
Output:
Example output:
Enter 10 numbers:
10 20 30 40 50 60 70 80 90 100
Sum: 550
Minimum: 10
Average: 55.00
34. Write a C program to read N integers into an array A and to 20 3 3
find the
(i)sum of odd numbers,
(ii) sum of even numbers,
(iii) average of all numbers.
Output the results computed with appropriate headings.
Ans: Code:
#include <stdio.h>
// Function to calculate sum of odd numbers
int sum_of_odd_numbers(int array[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
if (array[i] % 2 != 0) {
sum += array[i];
}
}
return sum;
}
// Function to calculate sum of even numbers
int sum_of_even_numbers(int array[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
if (array[i] % 2 == 0) {
sum += array[i];
}
}
return sum;
}
// Function to calculate average of all numbers
float average_of_numbers(int array[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += array[i];
}
School of Engineering and Technology
return (float) sum / n;
}
int main() {
int n;
printf("Enter the number of integers (N): ");
scanf("%d", &n);
int array[n];
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &array[i]);
}
int sum_odd = sum_of_odd_numbers(array, n);
int sum_even = sum_of_even_numbers(array, n);
float average = average_of_numbers(array, n);
printf("Sum of odd numbers: %d\n", sum_odd);
printf("Sum of even numbers: %d\n", sum_even);
printf("Average of all numbers: %.2f\n", average);
return 0;
}
Output:
Enter the number of integers (N): 5
Enter 5 integers:
12345
Sum of odd numbers: 9
Sum of even numbers: 6
Average of all numbers: 3.00
35. Write a C program to convert a given string to uppercase 20 3 3
without using any library functions. Explain the logic used in
your implementation.
Ans: #include <stdio.h>
// Function to convert a character to uppercase
char to_uppercase(char c) {
if (c >= 'a' && c <= 'z') {
return c - 32; // Convert to uppercase
} else {
return c; // Return character as is
}
}
// Function to convert a string to uppercase
void string_to_uppercase(char str[]) {
int i = 0;
while (str[i]!= '\0') {
School of Engineering and Technology
str[i] = to_uppercase(str[i]);
i++;
}
}
int main() {
char str[100];
printf("Enter a string: ");
scanf("%[^\n]s", str);
/* The \n in the format string tells scanf to read and discard
any whitespace characters (including newlines) until it
encounters a non-whitespace character */
string_to_uppercase(str);
printf("Uppercase string: %s\n", str);
return 0;
}
Output:
Enter a string: hello world
Uppercase string: HELLO WORLD
Module 4- Functions
SL MARKS COs BL
NO ǪUESTIONS
1. Define an array and explain how to declare and initialize 2 4 2
a one-dimensional array in C.
Ans: A Dimensional array is a structure created in the memory to
represent a number of values of the same data type with the
variables having the same variable name along with different
subscripts. A Dimensional array is also called Subscripted
Variable.
Declaration syntax for single dimensional array:
<data_type> <array_name>[array_size];
For Example:
int scores[5];
Initialization syntax for single dimensional array:
<array_name>[array_size] = {values};
For Example:
int scores[5] = {10, 20, 30, 40, 50};
2. Define two-dimensional array? How is it different from a 2 4 2
one-dimensional array?
Ans:
School of Engineering and Technology
Double Dimensional array is a structure created in the
memory to contain the data values by using rows and
columns.
A Double Dimensional array is also referred to as a double
subscripted variable because it uses two types of subscripts,
one for the rows number and the other for the column
number to represent any element of the array.
Double dimensional array: Single dimensional array:
• It is represented • It is represented
along X-axis and Y- along X-axis.
axis.
• The variables with • The variables with
same name have two same name have
types of subscripts single subscript.
representing row
number and column
number.
• It is also called as • It is also called single
double subscripted subscripted variable.
variable.
3. Illustrate declare and initialize a multi-dimensional 2 4 3
array with an example.
Ans: Declaration syntax for double/ multi-dimensional array:
<data_type> <array_name>[row_size][column_size];
For Example:
int matrix[3][4];
Initialization syntax for double/ multi-dimensional array:
<array_name>[row size][column size] = {values};
For Example:
int matrix[3][4] = {{1, 2, 3, 4},{5, 6, 7, 8},{9, 10, 11,
12}};
4. Write a short code snippet to declare and initialize an 2 4 3
array of 10 integers.
Code:
Ans:
int main()
{
int a[10]={12 , 13 , 2 , 4 , 5 , 4 , 6 , 7 , 8 , 5};
//int a is declaration
//a[10] ={12,13,2,4,5,4,6,7,8,5}; is initialization.
int n=sizeof(arr)/sizeof(arr[0]);
for(int i=0 ; i <n ; i++)
printf(“%d\n”,a[i]);
School of Engineering and Technology
}
5. Define string in C? explain how do you declare and 2 4 2
initialize a string?
Ans: A string is an array of characters terminated by a null
character.
To declare a string:
Syntax: <data type><string variable>[ string size+1];
For example: char str[10];
To initialize a string:
Syntax: <string variable> []= “ String ”;
For example: char str[] = "Hello";
(OR)
char str[] = { ‘H’ , ‘e’ , ‘l’ , ‘l’ , ‘o’ , ‘\0’ };
6. Explain how to find the length of a string in C using a 2 4 2
standard library function.
Ans: To find the length of the string in C program we use
strlen() function from the string library of C program.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int length = strlen(str);
printf("Length of the string: %d\n", length);
return 0;
}
Output:
Length of the string: 13
Note:
The strlen() function returns the number of characters in
the string, excluding the null terminator (\0).
7. Illustrate the function used in C to copy one string to 2 4 3
another string with example.
Ans: The function present in string library of C program
to copy one string to another string is strcpy()
function.
Code:
#include <stdio.h>
#include <string.h>
School of Engineering and Technology
int main() {
char src[] = "Hello, World!";
char dest[20];
// Copy the source string to the destination string
strcpy(dest, src);
printf("Source string: %s\n", src);
printf("Destination string: %s\n", dest);
return 0;
}
Output:
Source string: Hello, World!
Destination string: Hello, World!
Note:
strcpy() assumes that the destination string has
enough space to hold the copied string. If the
destination string is not large enough, it can lead to a
buffer overflow, which can cause undefined behavior.
8. Explain arrays of strings with an example. 2 4 2
Ans: In C, an array of strings is a two-dimensional array where
each element is a string.
Code:
#include <stdio.h>
int main() {
// Declare an array of strings
char colors[3][10] = {
"Red",
"Green",
"Blue"
};
// Access and print each string in the array
for (int i = 0; i < 3; i++) {
printf("Color %d: %s\n", i + 1, colors[i]);
}
return 0;
}
Output:
Color 1: Red
Color 2: Green
Color 3: Blue
9. Explain an automatic storage class in C with an example. 2 4 2
Ans: The automatic storage class is a type of memory allocation
that is automatically managed by the compiler.
School of Engineering and Technology
Variables with automatic storage class are allocated
memory on the stack, and their memory is automatically
deallocated when the block or function in which they are
declared ends.
Code:
include <stdio.h>
void myFunction() {
int x = 10; // automatic storage class variable
printf("Value of x: %d\n", x);
}
int main() {
myFunction();
return 0;
}
10. Define an external variable and explain its scope 2 4 2
with an example.
Ans: Definition: External variables are variables that are
declared outside of a function or block and are accessible
from multiple functions or blocks.
Scope: External variables are also known as
"global variables" because they are accessible from
any function or block within the same source file or
even from other source files.
For Example:
#include <stdio.h>
int globalVar = 10; // external variable
void main() {
printf("Value of globalVar in myFunction:
%d\n", globalVar);
}
11. Explain the static storage class with an example. 2 4 2
Ans: Static variables are variables that are declared within a
function or block and retain their value between function
calls.
Static variable is also like global variable but the only
difference of it from global variable is that it has only one
copy in the entire program which is shared by all the
functions of the program.
For Example:
#include <stdio.h>
void myFunction() {
static int count = 0; // static variable
count++;
printf("Count: %d\n", count);
}
int main() {
School of Engineering and Technology
myFunction(); // Count: 1
myFunction(); // Count: 2
myFunction(); // Count: 3
return 0;
}
Output:
The output of the program is:
Count: 1
Count: 2
Count: 3
12. Define register variables and how do they differ 2 4 2
from automatic variables?
Ans: In C, Register variables are a type of automatic
variable that is stored in a register instead of
RAM.
Register Variable: Automatic Variable:
1. Stored in a 1. Stored in
register (if RAM.
available).
2. Faster access 2. Slower access
since since RAM
registers are access is
part of the required.
CPU.
3. Same scope 3. Limited to the
and lifetime block or
as automatic function.
variables
(limited to the
block or
function).
4. Initialized to 4. Also
indeterminate initialized to
values unless indeterminate
explicitly values unless
initialized. explicitly
initialized.
5. No memory 5. Has a
address since memory
stored in a address.
register.
6. Declared 6. No specific
using the keyword
register required.
keyword.
7. Limited 7. No such
availability limitation.
since the
School of Engineering and Technology
number of
registers is
limited.
13. Explain in detail the process of declaring and initializing a 10 4 2
two- dimensional array in C. Provide code examples and
explain how data is stored and accessed.
Ans:
Declaration syntax for double dimensional
array:<data_type> <array_name>[row_size][column_size];
For Example:
int matrix[3][4];
Initialisation syntax for double dimensional array:
<array_name>[row size][column size] = {values};
For Example:
int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8},{9, 10, 11, 12}};
Data Storage and Access:
A 2D array in C is stored in row-major order, which means
that the elements of the first row are stored contiguously in
memory, followed by the elements of the second row, and so
on.
To access an element in a 2D array, you need to specify the
row index and column index. The general syntax is:
array_name[row_index][column_index]
For example, to access the element at row 1, column 2 in the
myArray array, you can use the following code:
int value = myArray[1][2];
Code:
#include <stdio.h>
int main() {
// Declare and initialize a 2D array
int myArray[3][4] = {{1, 2, 3, 4},{5, 6, 7, 8},{9, 10, 11, 12}};
// Print the array elements
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", myArray[i][j]);
}
School of Engineering and Technology
printf("\n");
}
// Access and print a specific element
int value = myArray[1][2];
printf("Value at row 1, column 2: %d\n", value);
return 0;
}
Output:
1234
5678
9 10 11 12
Value at row 1, column 2: 7
14. Describe the various operations that can be performed on 10 4 3
string in C. Include examples for each operation.
Ans: In C, strings are arrays of characters terminated by a null
character (\0). Here are the various operations that can be
performed on strings in C:
1. String Initialization
Strings can be initialized using the char array syntax.
char str[] = "Hello, World!";
2. String Input/Output
Strings can be input/output using scanf() and printf()
functions.
Code:
#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
scanf("%99s", str);
// Note: %99s to prevent buffer overflow
printf("You entered: %s\n", str);
return 0;
}
3. String Concatenation
Strings can be concatenated using the strcat() function.
Code:
School of Engineering and Technology
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
printf("%s\n", str1); // Output: Hello, World!
return 0;
}
4. String Copying
Strings can be copied using the strcpy() function.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, World!";
char str2[100];
strcpy(str2, str1);
printf("%s\n", str2); // Output: Hello, World!
return 0;
}
5. String Comparison
Strings can be compared using the strcmp() function.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, World!";
char str2[] = "Hello, World!";
if (strcmp(str1, str2) == 0) {
printf("Strings are equal\n");
} else {
printf("Strings are not equal\n");
}
return 0;
}
6. String Length
The length of a string can be calculated using the strlen()
function.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
School of Engineering and Technology
printf("Length of string: %d\n", strlen(str));
return 0;
}
7. String Tokenization
Strings can be tokenized using the strtok() function.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "apple,banana,cherry";
char* token = strtok(str, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
return 0;
}
8. String Search
A substring can be searched within a string using the
strstr() function.
Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char* substr = "World";
char* result = strstr(str, substr);
if (result != NULL) {
printf("Substring found\n");
} else {
printf("Substring not found\n");
}
return 0;
}
15. Discuss the differences between automatic, external, 10 4 4
static, and register storage classes in C. Provide examples
to illustrate each type.
Ans:
Automatic Storage Class
Automatic variables, also known as local variables, are
variables that are declared within a function or block and
cannot be accessed outside the function or the block but only
can be accessed inside the function or the block.
- Variables are allocated memory on the stack.
School of Engineering and Technology
- Variables are initialized to garbage values.
- Scope is limited to the block or function in which they are
declared.
- Lifetime ends when the block or function ends.
- No keyword is required.
Example:
void myFunction() {
int x = 10; // automatic variable
printf("%d\n", x);
}
External Storage Class
External variables are variables that are declared outside of
a function or block and are accessible from multiple
functions or blocks.
- Variables are allocated memory in the data segment.
- Variables are initialized to zero.
- Scope is global, meaning they can be accessed from any file.
- Lifetime is the entire program execution.
- extern keyword is required for declaration in other files.
Example:
// file1.c
int globalVar = 10; // external variable
// file2.c
extern int globalVar; // declaration using extern
void myFunction() {
printf("%d\n", globalVar);
}
Static Storage Class
Static variables are variables that are declared within a
function or block and retain their value between function
calls.
- Variables are allocated memory in the data segment.
- Variables are initialized to zero.
- Scope depends on the context:
- Inside a function: scope is limited to that function.
- Outside a function: scope is global, but the variable is not
accessible from other files.
- Lifetime is the entire program execution.
- static keyword is required.
School of Engineering and Technology
Example:
void myFunction() {
static int x = 10; // static variable
x++;
printf("%d\n", x);
}
int main() {
myFunction(); // prints 11
myFunction(); // prints 12
return 0;
}
Register Storage Class
Register variables are variables that are stored in a
register instead of memory, which can improve
performance. They are declared using the register
keyword.
- Variables are allocated memory in a CPU register (if
possible).
- Variables are initialized to garbage values.
- Scope is limited to the block or function in which they
are declared.
- Lifetime ends when the block or function ends.
- register keyword is required.
Example:
void myFunction() {
register int x = 10; // register variable
printf("%d\n", x);
}
16. Write a C program to input and display a multi- 10 4 2
dimensional array. Explain the code and how memory is
allocated for the array.
Ans: /* These two lines are examples of preprocessor directives
in C, specifically using the #define directive.
#define is a preprocessor directive that allows you to
define constants or macros. In this case:
- #define ROWS 3 defines a constant named ROWS with
the value 3.
- #define COLS 4 defines a constant named COLS with
the value 4.
These constants can then be used throughout your C
program, making it easier to modify the values later if
needed.
For example, instead of hardcoding the values 3 and 4 in
your array declaration:
int array[3][4];
You can use the defined constants:
School of Engineering and Technology
int array[ROWS][COLS];
This makes your code more readable, maintainable, and
flexible. */
Code:
#include <stdio.h>
#define ROWS 3
#define COLS 4
int main() {
// Declare a 2D array
int array[ROWS][COLS];
// Input array elements
printf("Enter %d elements:\n", ROWS * COLS);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("Element [%d][%d]: ", i, j);
scanf("%d", &array[i][j]);
}
}
// Display array elements
printf("\nArray Elements:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
return 0;
}
Code Explanation:
1. We start by including the stdio.h header file for
input/output operations.
2. We define two constants, ROWS and COLS, to
represent the number of rows and columns in the 2D
array.
3. In the main function, we declare a 2D array array with
ROWS rows and COLS columns.
4. We use nested for loops to input array elements from
the user. The outer loop iterates over the rows, and the
inner loop iterates over the columns.
5. After inputting the array elements, we use another set
of nested for loops to display the array elements.
Memory Allocation:
When we declare a 2D array array with ROWS rows and
COLS columns, the compiler allocates a contiguous block
of memory to store the array elements.
The memory allocation for the 2D array can be visualized
as follows:
array[0][0] array[0][1] ... array[0][COLS-1]
array[1][0] array[1][1] ... array[1][COLS-1]
School of Engineering and Technology
...
array[ROWS-1][0] array[ROWS-1][1] ... array[ROWS-
1][COLS-1]
The total memory allocated for the 2D array is ROWS *
COLS * sizeof(int), where sizeof(int) represents the size of
an int data type in bytes.
In this example, since ROWS is 3 and COLS is 4, the total
memory allocated for the 2D array is 3 * 4 * sizeof(int).
17. Illustrate the concept of arrays of strings in C. Write a 10 4 3
programto demonstrate how to read and display multiple
strings.
Ans:
#include <stdio.h>
#define NUMBER_OF_STRINGS 3
#define MAX_STRING_LENGTH 100
int main() {
char
strings[NUMBER_OF_STRINGS][MAX_STRING_LEN
GTH];
// Read multiple strings
printf("Enter %d strings:\n",
NUMBER_OF_STRINGS);
for (int i = 0; i < NUMBER_OF_STRINGS; i++) {
printf("String %d: ", i + 1);
fgets(strings[i], MAX_STRING_LENGTH, stdin);
// Remove the newline character
strings[i][strcspn(strings[i], "\n")] = 0;
}
// Display the strings
printf("\nYou entered the following strings:\n");
for (int i = 0; i < NUMBER_OF_STRINGS; i++) {
printf("String %d: %s\n", i + 1, strings[i]);
}
return 0;
}
The Program Explanation:
1. The program starts by including the stdio.h header file
for input/output operations.
2. It defines two constants: NUMBER_OF_STRINGS (the
number of strings to read) and MAX_STRING_LENGTH
(the maximum length of each string).
3. In the main function, it declares a 2D array strings to
store the input strings.
4. The program uses a for loop to read
NUMBER_OF_STRINGS strings from the user. For each
string, it uses fgets to read a line of input and stores it in
School of Engineering and Technology
the corresponding row of the strings array.
5. After reading all the strings, the program displays them
using another for loop.
Output:
Enter 3 strings:
String 1: Hello
String 2: World
String 3: Programming
You entered the following strings:
String 1: Hello
String 2: World
String 3: Programming
18. Compare and contrast the four storage classes in C in 10 4 3
terms of scope, life time, and default initial value. Provide
examples for better understanding.
Ans:
Automatic Storage Class:
void myFunction() {
int x = 10; // automatic variable
printf("%d\n", x);
}
- Scope: Local to the block or function in which it is
declared.
- Lifetime: Exists only during the execution of the block or
function.
- Default Initial Value: Garbage value (indeterminate).
External Storage Class:
// file1.c
int globalVar = 10; // external variable
// file2.c
extern int globalVar; // declaration using extern
void myFunction() {
printf(“%d\n”, globalVar);
}
- Scope: Global (accessible from any file).
- Lifetime: Exists for the entire program execution.
- Default Initial Value: Zero.
Static Storage Class:
void myFunction() {
static int x = 10; // static variable
x++;
printf("%d\n", x);
}
int main() {
myFunction(); // prints 11
myFunction(); // prints 12
School of Engineering and Technology
return 0;
}
- Scope:
1. Local to the block or function in which it is declared
(if declared inside a block or function).
2. Global (if declared outside a block or function).
- Lifetime: Exists for the entire program execution.
- Default Initial Value: Zero.
Register Storage Class:
void myFunction() {
register int x = 10; // register variable
printf("%d\n", x);
}
- Scope: Local to the block or function in which it is
declared.
- Lifetime: Exists only during the execution of the block or
function.
- Default Initial Value: Garbage value (indeterminate).
19. Write a C program to perform matrix multiplication 15 4 3
using two-dimensional arrays. Explain the logic, and how
the arrays are declared, initialized, and accessed.
Ans:
Code:
#include <stdio.h>
#define ROWS_A 2
#define COLS_A 3
#define ROWS_B 3
#define COLS_B 2
int main() {
// Declare and initialize matrices A and B
int matrixA[ROWS_A][COLS_A] = {{1, 2, 3},{4, 5, 6}};
int matrixB[ROWS_B][COLS_B] = {{7, 8},{9, 10},{11,12}};
// Declare the result matrix
int result[ROWS_A][COLS_B];
// Perform matrix multiplication
for (int i = 0; i < ROWS_A; i++) {
for (int j = 0; j < COLS_B; j++) {
result[i][j] = 0;
for (int k = 0; k < COLS_A; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
// Print the result matrix
printf("Matrix A:\n");
for (int i = 0; i < ROWS_A; i++) {
for (int j = 0; j < COLS_A; j++) {
School of Engineering and Technology
printf("%d ", matrixA[i][j]);
}
printf("\n");
}
printf("Matrix B:\n");
for (int i = 0; i < ROWS_B; i++) {
for (int j = 0; j < COLS_B; j++) {
printf("%d ", matrixB[i][j]);
}
printf("\n");
}
printf("Result Matrix:\n");
for (int i = 0; i < ROWS_A; i++) {
for (int j = 0; j < COLS_B; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Logic:
1. The program starts by defining the dimensions of the
matrices A and B.
2. It then declares and initializes matrices A and B with
the given values.
3. The result matrix is declared with the correct
dimensions.
4. The program performs matrix multiplication using
nested loops.
5. The result matrix is printed along with matrices A and
B.
Array Declaration, Initialization, and Access:
1. Declaration: Matrices A and B are declared as two-
dimensional arrays using the syntax int
matrixA[ROWS_A][COLS_A];.
2. Initialization: The matrices are initialized with values
using the syntax:
int matrixA[ROWS_A][COLS_A] = {{1, 2, 3}, {4, 5, 6}};.
3. Access: Elements of the matrices are accessed using the
syntax matrixA[i][j], where i is the row index and j is the
column index.
20. Write a C program that demonstrates the useof various 15 4 3
string operations such as concatenation, comparison,and
length calculation.
Ans:
Code:
School of Engineering and Technology
#include <stdio.h>
#include <string.h>
int main() {
// Declare and initialize strings
char str1[20] = "Hello";
char str2[20] = "World";
// Concatenate strings
char result[40];
strcpy(result, str1);
strcat(result, " ");
strcat(result, str2);
printf("Concatenated string: %s\n", result);
// Compare strings
int comparison = strcmp(str1, str2);
if (comparison == 0) {
printf("Strings are equal\n");
} else if (comparison < 0) {
printf("String '%s' is less than '%s'\n", str1, str2);
} else {
printf("String '%s' is greater than '%s'\n", str1,
str2); }
// Calculate string length
int length = strlen(str1);
printf("Length of '%s': %d\n", str1, length);
return 0;
}
This program demonstrates the following string
operations:
- Concatenation: The strcpy and strcat functions are used
to concatenate strings.
- Comparison: The strcmp function is used to compare
strings lexicographically.
- Length calculation: The strlen function is used to
calculate the length of a string.
Output:
Concatenated string: Hello World
String 'Hello' is less than 'World'
Length of 'Hello': 5
21. Explain in detail the use and importance of static and 15 4 2
external storage classes and write a program to that
utilizes both storage classes and explain how they interact.
Ans:
External Storage Class:
// file1.c
int globalVar = 10; // external variable
School of Engineering and Technology
// file2.c
extern int globalVar; // declaration using extern
void myFunction() {
printf(“%d\n”, globalVar);
}
- Scope: Global (accessible from any file).
- Lifetime: Exists for the entire program execution.
- Default Initial Value: Zero.
Static Storage Class:
void myFunction() {
static int x = 10; // static variable
x++;
printf("%d\n", x);
}
int main() {
myFunction(); // prints 11
myFunction(); // prints 12
return 0;
}
- Scope:
1. Local to the block or function in which it is declared
(if declared inside a block or function).
2. Global (if declared outside a block or function).
- Lifetime: Exists for the entire program execution.
- Default Initial Value: Zero.
Code: Program Utilizing Static and External Storage Classes
file1.c
#include <stdio.h>
// External variable declaration
extern int externalVar;
// Static variable declaration
static int staticVar = 10;
void incrementStaticVar() {
staticVar++;
}
void printStaticVar() {
printf("Static variable value: %d\n", staticVar);
}
void printExternalVar() {
printf("External variable value: %d\n", externalVar);
School of Engineering and Technology
}
file2.c
#include <stdio.h>
// External variable definition
int externalVar = 20;
int main() {
// Call functions from file1.c
incrementStaticVar();
printStaticVar();
printExternalVar();
return 0;
}
bash
gcc -c file1.c
gcc -c file2.c
gcc file1.o file2.o -o program
./program
/*
a) gcc -c file1.c: Compile file1.c into an object file file1.o.
b) gcc -c file2.c: Compile file2.c into an object file file2.o.
c) gcc file1.o file2.o -o program: Link the object files
file1.o and file2.o together to create an executable file
named program.
d) ./program: Run the executable file program. */
Output:
Static variable value: 11
External variable value: 20