0% found this document useful (0 votes)
3 views12 pages

Assignment DCA1107 - C programming

The document provides an overview of key concepts in C programming, including the use of the printf function with format specifiers, decision control statements, arrays, null-terminated strings, recursion, and the selection sort algorithm. It explains the syntax and examples for each concept, emphasizing their importance in programming. Additionally, it outlines the time and space complexity of the selection sort algorithm.

Uploaded by

ssmanoj580
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
3 views12 pages

Assignment DCA1107 - C programming

The document provides an overview of key concepts in C programming, including the use of the printf function with format specifiers, decision control statements, arrays, null-terminated strings, recursion, and the selection sort algorithm. It explains the syntax and examples for each concept, emphasizing their importance in programming. Additionally, it outlines the time and space complexity of the selection sort algorithm.

Uploaded by

ssmanoj580
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 12

Name: ARCHANA H C

Roll Number: 2414509246


Semester: 1ST SEMISTER
Course Name: BCA
Course Code: DCA1107

Set-I

1) In C programming, the printf function is utilized to output formatted text to the


standard output, such as the console. Format specifiers within the printf function are
placeholders that define how the subsequent arguments should be formatted and
displayed. They inform the compiler about the type of data to be printed, ensuring that
each value is presented correctly.

Role of Format Specifiers:

Data Type Specification: They indicate the type of data (e.g., integer, floating-point,
character) to be printed, ensuring proper formatting.
Formatting Control: They allow control over the width, precision, alignment, and
other formatting aspects of the output.

Common Format Specifiers and Their Corresponding Data Types:

Format Data
Description
Specifier Type

%d int Prints a signed decimal integer.

%i int Same as %d; prints a signed decimal integer.

%u unsigned int Prints an unsigned decimal integer.

float or Prints a floating-point number in fixed-point


%f
double notation.

Prints a floating-point number in fixed-point


%lf double
notation (double precision).

Float or Prints a floating-point number in scientific


%e
double notation (lowercase 'e').

float or Prints a floating-point number in scientific


%E
double notation (uppercase 'E').
Format Data
Description
Specifier Type

Prints a floating-point number in either


float or
%g normal or scientific notation, whichever is
double
more compact.

%c char Prints a single character.

%s char* Prints a string of characters.

%p void* Prints a pointer address.

Prints an unsigned hexadecimal integer


%x unsigned int
(lowercase letters).

Prints an unsigned hexadecimal integer


%X unsigned int
(uppercase letters).

%o unsigned int Prints an unsigned octal integer.

%% None Prints a literal '%' character.


Examples:
#include <stdio.h>
int main() {
int integer = 42;
float floating_point = 3.14159;
char character = 'A';
char* string = "Hello, World!";
unsigned int unsigned_integer = 255;

printf("Integer: %d\n", integer);


printf("Floating-point: %.2f\n", floating_point);
printf("Character: %c\n", character);
printf("String: %s\n", string);
printf("Unsigned Integer: %u\n", unsigned_integer);
printf("Hexadecimal: %x\n", unsigned_integer);

return 0;
}
Output:
yaml
Integer: 42
Floating-point: 3.14
Character: A
String: Hello, World!
Unsigned Integer: 255
Hexadecimal: ff
2) In C programming, decision control statements enable the execution of specific blocks
of code based on certain conditions. They are fundamental for controlling the flow of
a program and include:

if Statement:
Purpose: Evaluates a condition; if true, executes the associated block of code.
Syntax:

if (condition) {
// Code to execute if condition is true
}
Example:
int number = 10;
if (number > 0) {
printf("Number is positive.\n");
}
Output: Number is positive.
if-else Statement:
Evaluates a condition; if true, executes one block of code; otherwise, executes another.
Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example:
int number = -5;
if (number >= 0) {
printf("Number is non-negative.\n");
} else {
printf("Number is negative.\n");
}
Output: Number is negative.
if-else if-else Ladder:
Evaluates multiple conditions sequentially; executes the block of the first true condition.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if none of the above conditions are true
}
Example:
int number = 0;
if (number > 0) {
printf("Number is positive.\n");
} else if (number < 0) {
printf("Number is negative.\n");
} else {
printf("Number is zero.\n");
}
Output: Number is zero.
Switch Statement:
Evaluates an expression and executes the corresponding case block based on the value.
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 day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day\n");
}
Output: Wednesday

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 numbers[] = {1, 2, 3, 4, 5}; // Compiler sets size to 5


Accessing Array Elements:
Array elements are accessed using their index, with indexing starting from 0.
int first_number = numbers[0]; // Accesses the first element
int second_number = numbers[1]; // Accesses the second element
Example:
Here's a complete example demonstrating the declaration, initialization, and access of an
array:
#include <stdio.h>
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

4) In C programming, a null-terminated string is a sequence of characters stored in an


array, with a special null character ('\0') marking the end of the string. This null
character serves as a sentinel value, allowing functions to determine where the string
ends. This convention is fundamental in C, as it enables functions to process strings
without needing explicit length information.

Difference Between Null-Terminated Strings and Regular Character Arrays:


Null-Terminated Strings:
An array of characters ending with a null character ('\0').Commonly used to represent
strings in C. Functions like printf, strlen, and strcpy rely on the null character to
determine the end of the string.
Example:
char greeting[] = "Hello, World!";
Here, greeting is a null-terminated string. The compiler automatically adds the null
character at the end, so the actual storage is: {'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\
0'}.
Regular Character Arrays:
An array of characters without any inherent indication of its length or termination.Used
for storing fixed-size character data. Functions do not inherently know the length of the
array; the programmer must manage the size explicitly.
Example:
char data[10] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l'};
In this case, data is a regular character array. It does not contain a null character, so
functions like printf would not know where the string ends without additional
information.
Example Illustrating the Difference:
#include <stdio.h>
#include <string.h>
int main() {
// Null-terminated string
char greeting[] = "Hello, World!";
printf("Greeting: %s\n", greeting); // Output: Hello, World!
printf("Length: %zu\n", strlen(greeting)); // Output: 13

// Regular character array


char data[10] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l'};
printf("Data: %s\n", data); // Undefined behavior: may not print correctly
// printf("Length: %zu\n", strlen(data)); // Undefined behavior: may not work correctly

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.

6) Selection Sort is a simple comparison-based sorting algorithm that operates by


repeatedly selecting the smallest (or largest) element from the unsorted portion of the
list and swapping it with the first unsorted element. This process continues until the
entire list is sorted.

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.

You might also like