0% found this document useful (0 votes)
9 views11 pages

DCA1107 (U)

Uploaded by

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

DCA1107 (U)

Uploaded by

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

SET-1

Que.-1:- Explain the role of format specifiers in the printf function in C. Provide
examples of different format specifiers and their corresponding data types.

Ans.:- Format specifiers are essential in the printf function of the C programming language, as
they allow programmers to specify the type of data that will be printed to the output. Format
specifiers function as placeholders within a string, enabling the function to ascertain the
appropriate interpretation and formatting of the corresponding parameters for display. Each
format specifier is associated with a specific data type, guaranteeing that the data is output in the
desired format.
A % symbol is typically used to begin the syntax for format specifiers, which is followed by a
character or combination of characters that denote the data type. For instance, %d is employed to
print integers, whereas %f is employed to print floating-point numbers. Printf is a versatile and
potent function due to the flexibility it offers in formatting output, which is facilitated by these
specifiers.
Data Types of Common Format Specifiers:
%d and %i: Both %d and %i are used for signed integers. For e.g.:

int num = 42;


printf("The number is: %d\n", num); // Output: The number is: 42

%u: This is employed for unsigned integers. It does not exhibit a negative sign for negative
numbers, in contrast to %d.
unsigned int num = 100;
printf("Unsigned number: %u\n", num); // Output: Unsigned number: 100

%f: Used for floating-point numbers. By default, it displays decimal values with six digits
following the decimal point; however, this can be modified.

float pi = 3.14159;
printf("Value of pi: %f\n", pi); // Output: Value of pi: 3.141590

%c: Represents a single character. Character variables or constants are frequently printed using
this method.
char ch = 'A';
printf("Character: %c\n", ch); // Output: Character: A

%s: Used for strings, i.e., arrays of characters terminated by a null character (\0).
char name[] = "Alice";
printf("Name: %s\n", name); // Output: Name: Alice
1.
%x and %X: These are employed to print unsigned integers in hexadecimal format, with %x
generating lowercase letters and %X generating uppercase letters.

int num = 255;


printf("Hexadecimal: %x\n", num); // Output: Hexadecimal: ff

%o: Prints an integer in octal format.

int num = 20;


printf("Octal: %o\n", num); // Output: Octal: 24

%p: Displays a memory address (pointer).

int num = 10;


printf("Memory address: %p\n", &num);

%e or %E: Prints floating-point numbers in scientific notation.

double val = 12345.6789;


printf("Scientific notation: %e\n", val); // Output: Scientific notation: 1.234568e+04

Que.-2:- In C programming, what are the decision control statements, and can you give an
example of each?

Ans.:- In the context of C programming, decision control statements are indispensable for
directing the execution process in accordance with predetermined conditions. These statements
enable a program to execute distinct segments of code and make decisions based on the outcome
of a condition, whether it is true or false. Decision control statements improve the functionality
and adaptability of a program by facilitating conditional logic. In C, the three primary categories
of decision control statements are if, if-else, and switch, each of which serves a unique purpose
in the decision-making process.
The simplest form of decision control is the if statement. It evaluates a condition, and if the
condition is satisfied, the block of code contained within the if statement is executed. The block
is skipped by the program if the condition is false. For instance,

int number = 5;
if (number > 0) {
printf("The number is positive.\n");
}
The program determines whether the value is greater than zero in this instance. The message is
printed if the condition is true.
Two alternative paths are provided by the if-else statement. One block of code is executed if the
condition is true; if it is false, another block is executed. For example,

int number = -3;


if (number > 0) {
printf("The number is positive.\n");
} else {
printf("The number is not positive.\n");
}

In this instance, the else block is executed, resulting in the printing of the alternative message, as
the condition (number > 0) is false.
The if-else-if cascade is employed in circumstances that necessitate multiple conditions. It
enables the sequential assessment of multiple conditions. The initial block of the true condition is
executed, and the subsequent blocks are omitted. For instance,

int number = 0;
if (number > 0) {
printf("The number is positive.\n");
} else if (number < 0) {
printf("The number is negative.\n");
} else {
printf("The number is zero.\n");
}

This is where the number is evaluated against a variety of conditions to ascertain whether it is
positive, negative, or zero.
The switch statement is employed to compare multiple values for a single variable. It evaluates
an expression and executes the corresponding case. For instance,

char grade = 'B';


switch (grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Good job!\n");
break;
case 'C':
printf("Well done.\n");
break;
default:
printf("Invalid grade.\n");
}

A message is printed in this example in accordance with the grade value. The execution of
subsequent cases is prevented by the break statement.
In C programming, decision control statements such as if, if-else, and switch are essential tools
that allow developers to create programs that are responsive, efficient, and logical. Differentiated
advantages are provided by each statement, which are appropriate for distinct decision-making
scenarios.

Que.-3:- Explain the concept of arrays in C programming. How are arrays declared and
initialized? Discuss with examples.

Ans.:- An array in C programming is a collection of elements of the same data type that are
stored in contiguous memory locations. Arrays enable developers to efficiently manage and
manipulate large quantities of data by utilizing a single variable name, rather than designating
multiple individual variables. An index is used to access each element in an array, with the first
element being indexed at 0. When dealing with collections of data, such as marks of students, a
sequence of numbers, or characters in a string, arrays are particularly beneficial.
Declaring Arrays:
In order to designate an array in C, the data type, array name, and array size (number of
elements) are encapsulated in square brackets []. For instance,

int numbers[5]; // Declares an array of 5 integers.

In this context, the array "numbers" is capable of accommodating five integer values. The array's
capacity must be a constant expression, as it determines the amount of memory it will consume.
Initializing Arrays: Arrays may be initialized at the time of declaration or designated values at a
later time. Specific values are assigned to array elements during initialization. For instance,

int numbers[5] = {10, 20, 30, 40, 50}; // Initializes an array with values.

The array numbers consist of five elements: 10, 20, 30, 40, and 50. The remaining elements are
automatically initialized to zero if fewer values are provided during initialization:
int numbers[5] = {10, 20}; // Remaining elements will be 0.

The number of elements is used to infer the array size if the size is omitted during initialization:
int numbers[] = {10, 20, 30}; // Size is 3.

Array Elements Accessibility: The index of an array element is utilized in square brackets to
access it. For instance,

printf("First element: %d\n", numbers[0]); // Outputs the first element (10).


numbers[1] = 25; // The second element is updated to 25.

Example of Array Utilization: The following program computes the sum of the elements in an
integer array:
#include <stdio.h>
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i]; // Add each element to the sum.
}
printf("Sum of array elements: %d\n", sum);
return 0;
}
The for loop in this example calculates the sum of the array elements by iterating through them.
In conclusion, arrays in C offer a streamlined approach to organizing collections of related data.
They are declared with a data type and capacity, and they can be initialized with specific values.
Arrays are a fundamental concept in C programming because they enable the access or
modification of individual elements through the use of indices.

SET-2

Que.-4:- Explain null-terminated strings in C programming. Discuss how they are different
from a regular character array. Provide an example to illustrate your answer.

Ans.:- A null-terminated string in C programming is a series of characters stored in a character


array, concluded by a null character ('\0'). The null character signifies the termination of the
string, enabling functions and operations to ascertain the point at which the string concludes. In
C, strings are fundamentally character arrays terminated by a null character, distinguishing them
from standard character arrays.
Null-Terminated Strings vs Standard Character Arrays:
The primary distinction between null-terminated strings and conventional character arrays is to
their function and behavior:
1. Null Character ('\0):
○ A null-terminated string must conclude with the null character ('\0'). Functions
that manipulate strings, such as strlen and printf, depend on the null character to
ascertain the termination of the string.
○ A standard character array does not need a null character and may include any
data without a designated delimiter.
2. Usage:
○ Null-terminated strings are used to represent and modify textual data, such as
words and phrases.
○ Standard character arrays may include any sequence of letters or data without
being construed as a string.
3. Memory Consideration:
○ Null-terminated strings need an additional byte for the null character, resulting in
a size that is often one more than the character count of the string.
○ Standard character arrays do not need this additional byte unless specifically
specified.

Example to Illustrate:
Here is an example to demonstrate the difference:
#include <stdio.h>

int main() {
// Null-terminated string
char str1[] = "Hello";

// Regular character array


char arr[] = {'H', 'e', 'l', 'l', 'o'}; // No null character

// Printing the null-terminated string


printf("String str1: %s\n", str1); // Works correctly, prints "Hello"

// Printing the regular character array


printf("Character array arr: %s\n", arr); // Undefined behavior, may print garbage after "Hello"

// Accessing elements individually


printf("First character of str1: %c\n", str1[0]);
printf("First character of arr: %c\n", arr[0]);

return 0;
}

Explanation of the Example:


String str1: It is a null-terminated string since it was initialized with the string literal "Hello".
The compiler automatically adds a '\0' at the conclusion.
When produced with %s, printf identifies the '\0' and stops printing after "Hello".
Character array arr: It is a standard character array initialized with distinct characters. In the
absence of a '\0' terminator, printf cannot ascertain the string's endpoint, leading to undefined
behavior, such as garbage values or memory leaks.
In C, null-terminated strings are character arrays explicitly intended for text storage, concluding
with a '\0' character. The null character differentiates them from conventional character arrays
and enables ordinary string methods to operate accurately. Comprehending this difference is
essential for the accurate handling of strings in C.

Que.-5:- Explain the concept of recursion in C programming. What are the necessary
conditions for a function to be recursive? Provide an example of a recursive function in C
that calculates the factorial of a number.

Ans.:- In C programming, recursion is a method in which a function invokes itself to resolve an


issue. Recursion is often used for issues that may be decomposed into smaller, analogous sub-
problems. Recursion involves a function addressing an issue by resolving lesser instances of that
problem until it attains a base case, which yields a direct solution.

Necessary Conditions for Recursion:


For a function to be recursive, it must satisfy two essential conditions:
1. The function must have a base case, which is a condition that halts further recursive calls.
This prevents the function from invoking itself endlessly, resulting in infinite recursion.
2. The function must invoke itself with an altered parameter that progresses towards the
base case. This phase lowers the issue size in each recursive invocation, guaranteeing that
the function ultimately attains the base case.

In the absence of a base case, or if the recursive call fails to reach the base case, the function will
result in indefinite recursion, potentially leading to a stack overflow issue or computer crash.
Illustration of a Recursive Function: Computation of Factorials
A quintessential illustration of recursion is the computation of a number's factorial. The factorial
of a non-negative number n is the product of all integers from 1 to n, represented as n!. The
factorial is defined recursively as follows:
● Base Case: 0! = 1 (or 1! = 1)
● Recursive Case: n! = n * (n-1)!

Here's how we can implement this in C:


#include <stdio.h>

// Recursive function to calculate factorial


int factorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n == 0 || n == 1) {
return 1;
} else {
// Recursive case: n * factorial of (n-1)
return n * factorial(n - 1);
}
}

int main() {
int number = 5;
printf("Factorial of %d is: %d\n", number, factorial(number));
return 0;
}

Explanation of the Code:


1. Factorial Function:
○ The factorial function accepts an integer n as its input.
○ If n equals 0 or 1, the method returns 1 as the basic case.
○ Alternatively, the function invokes itself with n - 1 and multiplies the outcome by
n, therefore deconstructing the issue into smaller sub-problems until it attains the
base case.
2. Main Function: In the main function, we use factorial(5) to compute the factorial of 5,
and the result is shown.
How Recursion Works in This Example:
When factorial(5) is called, the following steps happen:
● factorial(5) calls factorial(4) and multiplies the result by 5
● factorial(4) calls factorial(3) and multiplies the result by 4
● factorial(3) calls factorial(2) and multiplies the result by 3
● factorial(2) calls factorial(1) and multiplies the result by 2
● factorial(1) reaches the base case and returns 1
Now, the recursive calls start to return:
● factorial(2) returns 2 * 1 = 2
● factorial(3) returns 3 * 2 = 6
● factorial(4) returns 4 * 6 = 24
● factorial(5) returns 5 * 24 = 120
The final value is 120, representing the factorial of 5.
Recursion in C enables a function to address an issue by invoking itself. For recursion to
function properly, it requires a base case to end the process and a recursive case to decompose
the issue. The factorial function exemplifies recursion by diminishing the issue size with each
invocation until the base case is attained. Recursion is a potent technique that must be used
judiciously to prevent limitless recursion or excessive memory consumption.

Que.-6:- Discuss the selection sort algorithm with an example. Write a C program to
implement selection sort.

Ans.:- Selection Sort is a fundamental comparison-based sorting algorithm. The algorithm


operates by consistently identifying the least (or largest) element from the unsorted segment of
the array and exchanging it with the first unsorted element. The method partitions the array into
two segments: the sorted segment and the unsorted segment. At the outset, the sorted segment is
devoid of items, whereas the unsorted segment has all components. Following each traversal of
the unsorted segment, a single element is included into the sorted segment.

Working of Selection Sort:


1. Commence with the first element: Regard the first member in the array as the minimum.
2. Identify the minimal element inside the unsorted segment that remains: Contrast this
element with all other items in the unsorted segment of the array.
3. Exchange the minimal element: Upon identifying the smallest element, exchange it with
the initial element.
4. Proceed to the subsequent element: Next, examine the second member and repeat the
procedure for the remaining unsorted segment of the array.
5. Iterate until the array is ordered: Persist with this procedure until the whole array is
organized.

Time Complexity:
● Best, Average, and Worst Case: O(n²)

Example of Selection Sort:


Consider the following array:
[64, 25, 12, 22, 11]

Step 1: discover the smallest element in the array (11) and swap it with the 1st element:
[11, 25, 12, 22, 64]

Step 2: Identify the smallest element in the unsorted section (12) and exchange it with the second
element.

[11, 12, 25, 22, 64]


Step 3: Identify the smallest element in the unsorted portion (22) and exchange it with the third
element.

[11, 12, 22, 25, 64]

Step 4: Identify the smallest element in the unsorted segment (25) and exchange it with the
fourth element.

[11, 12, 22, 25, 64]

Step 5: The array is now sorted as [11, 12, 22, 25, 64].
C Program for Selection Sort:

#include <stdio.h>

// Function to implement selection sort


void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;

// One by one move the boundary of unsorted subarray


for (i = 0; i < n - 1; i++) {
// Find the minimum element in unsorted array
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}

// Swap the found minimum element with the first element


temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}

// Function to print the array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


printArray(arr, n);

// Call the selectionSort function


selectionSort(arr, n);

printf("Sorted array: ");


printArray(arr, n);

return 0;
}

You might also like