Assignment DCA1107 - C programming (1)
Assignment DCA1107 - C programming (1)
Set-I
Data Type Specification: In order to ensure correct formatting, they provide the type
of data (such as character, integer, or floating-point) that will be printed.
Formatting Control: They give you control over the output's width, accuracy,
alignment, and other formatting elements.
Typical Format Specifiers and the Data Types they correspond to:
Format Data
Description
Specifier Type
return 0;
}
Output:
Integer is: 43
Floating-point is: 3.152
Character is: D
String is: Happy, World1!
Unsigned Integer is: 245
Hexadecimal is: f5
2) Decision control statements in C programming allow particular code blocks to be
executed in response to predetermined criteria. They are essential for managing a
program's flow and consist of:
if Statement:
is a fundamental control structure that allows the execution of a block of code based
on whether a specified condition evaluates to true. If the condition is true, the code
within the if block is executed; otherwise, it is skipped.
Syntax:
if (condition) {
// lines of code to execute if condition is true
}
Example:
int test_num1 = 15;
if (test_num1 > 0) {
printf("The given number is positive!\n");
}
Output: The given number is positive!
if-else Statement:
execute one block of code if a specified condition is true, and another block if the
condition is false.
Syntax:
if (condition) {
// Lines of code to execute if condition is true
} else {
// Lines of code to execute if condition is false
}
Example:
int test_num1 = -62;
if (test_num1 >= 0) {
printf("The given number is non-negative.\n");
} else {
printf("The given number is negative!\n");
}
Output: The given number is negative!
if-else if-else Ladder:
is a control structure in programming that allows for the evaluation of multiple conditions
sequentially. It executes the block of code corresponding to the first condition that
evaluates to true. This structure is particularly useful when you have multiple mutually
exclusive conditions to check..
Syntax:
if (condition1) {
// lines of code to execute if condition1 is true
} else if (condition2) {
// lines of code to execute if condition2 is true
} else {
// lines of code to execute if none of the above conditions are true
}
Example:
int test_num1 = 50;
if (test_num1 > 40) {
printf("The given number is greater than 40.\n");
} else if (test_num1 < 20) {
printf("The given number is less than 20.\n");
} else {
printf("Defined number is: %d\n", test_num1);
}
Output: The given number is greater than 40.
Switch Statement:
Based on the value of an expression, it evaluates it and then runs the relevant case block.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// Additional cases as needed
default:
// Code to execute if expression doesn't match any case
}
Example:
int fruit = 2;
switch (fruit) {
case 1:
printf("it is Apple\n");
break;
case 2:
printf("it is Orange\n");
break;
case 3:
printf("it is Kivi\n");
break;
default:
printf("it is Invalid number\n");
}
Output: it is Orange
3) In C programming, an array is a data structure that allows you to store multiple values
of the same data type under a single variable name. Arrays are particularly useful
when you need to manage a collection of related data items, such as a list of integers
or a sequence of characters.
Declaring Arrays:
To declare an array in C, specify the data type of its elements, followed by the array
name and the number of elements it will hold, enclosed in square brackets.
data_type array_name[array_size];
For example, to declare an array of 5 integers:
int numbers[5];
This declaration creates an array named numbers that can hold 5 integer values.
Initializing Arrays:
Arrays can be initialized at the time of declaration using an initializer list, which
provides the values to be assigned to the array elements.
data_type array_name[array_size] = {value1, value2, value3, value4, value5};
For example:
int numbers[5] = {1, 2, 3, 4, 5};
This initializes the numbers array with the values 1 through 5.
If the number of values provided in the initializer list is less than the array size, the
remaining elements are automatically initialized to zero.
int numbers[5] = {1, 2}; // numbers[2] = 0, numbers[3] = 0, numbers[4] = 0
Alternatively, if you omit the array size, the compiler determines it based on the number
of elements in the initializer list:
int main() {
// Declare and initialize an array of 5 integers
int numbers[5] = {10, 20, 30, 40, 50};
// Access and print each element
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}
return 0;
}
Output:
Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50
In this example, the numbers array is declared with 5 elements, initialized with values 10
through 50, and each element is accessed and printed using a loop.
Understanding arrays is fundamental in C programming, as they provide a way to handle
multiple related data items efficiently.
Set-II
return 0;
}
Output:
Greeting: Hello, World!
Length: 13
Data: Hello World!
In this example, greeting is a null-terminated string, so functions like printf and strlen
work as expected. However, data is a regular character array without a null terminator,
leading to undefined behavior when using functions that expect null-terminated strings.
Null-Terminated Strings: Essential for string manipulation in C; functions rely on the
null character to determine the end of the string.
Regular Character Arrays: Do not inherently indicate their length or termination; the
programmer must manage the size and ensure proper termination when necessary.
5) In C programming, recursion refers to the process where a function calls itself directly
or indirectly to solve a problem. This technique is particularly useful for breaking
down complex problems into simpler, more manageable sub-problems.
Necessary Conditions for a Function to Be Recursive:
Base Case: A condition that terminates the recursive calls. Without a base case, the
function would call itself indefinitely, leading to a stack overflow.
Recursive Case: The part of the function where it calls itself with modified
arguments, progressively moving towards the base case.
Example: Recursive Function to Calculate Factorial
The factorial of a non-negative integer n is the product of all positive integers less
than or equal to n. Mathematically, it's defined as:
n! = n × (n - 1) × (n - 2) × ... × 1
In C, a recursive function to calculate the factorial can be implemented as follows:
#include <stdio.h>
// Function to calculate factorial
long int factorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n <= 1)
return 1;
// Recursive case: n * factorial of (n - 1)
else
return n * factorial(n - 1);
}
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
// Validate input
if (number < 0)
{ printf("Factorial is not defined for negative numbers.\n");}
else
{ printf("Factorial of %d = %ld\n", number, factorial(number));}
return 0;
}
Base Case: When n is 0 or 1, the function returns 1, as 0! and 1! are both defined as 1.
Recursive Case: For any n > 1, the function returns n multiplied by the factorial of n - 1.
This continues until the base case is reached.
Output:
Enter a positive integer: 5
Factorial of 5 = 120
In this example, the function factorial calls itself with decremented values of n until it
reaches the base case. The results are then multiplied together as the recursive calls
return, ultimately calculating the factorial of the input number.
Algorithm Steps:
Start with the first element of the array.
Find the smallest element in the unsorted portion of the array.
Swap this smallest element with the first unsorted element.
Move the boundary of the sorted and unsorted portions one element to the right.
Repeat steps 2-4 until the entire array is sorted.
Example:
Consider the array: [64, 25, 12, 22, 11]
First Pass:
Find the smallest element (11) and swap it with the first element (64).
Array after swap: [11, 25, 12, 22, 64]
Second Pass:
Find the smallest element in the unsorted portion (12) and swap it with the second
element (25).
Array after swap: [11, 12, 25, 22, 64]
Third Pass:
Find the smallest element in the unsorted portion (22) and swap it with the third element
(25).
Array after swap: [11, 12, 22, 25, 64]
Fourth Pass:
Find the smallest element in the unsorted portion (25) and swap it with the fourth element
(25).
Array remains: [11, 12, 22, 25, 64]
After these passes, the array is sorted in ascending order.
C Program Implementation:
#include <stdio.h>
// Function to perform selection sort
void selectionSort(int arr[], int n) {
int i, j, minIdx, temp;
for (i = 0; i < n - 1; i++) {
minIdx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j; }
}
// Swap the found minimum element with the first element
temp = arr[minIdx];
arr[minIdx] = 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);
selectionSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
Output:
Original array: 64 25 12 22 11
Sorted array: 11 12 22 25 64
Time Complexity:
Selection sort has a time complexity of O(n²) due to the nested loops:
Best, Average, and Worst Case: O(n²)
This quadratic time complexity makes selection sort inefficient for large datasets.
Space Complexity:
Selection sort is an in-place sorting algorithm, meaning it requires only a constant amount
of additional space.
Space Complexity: O(1)
Advantages:
Simple to understand and implement.
Does not require additional memory beyond the input array.
Disadvantages:
Inefficient for large datasets due to its O(n²) time complexity.
Not a stable sort; equal elements may not retain their original order.