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

Assignment DCA1107 - C programming (1)

The document provides an overview of fundamental concepts in C programming, including format specifiers for output, decision control statements, arrays, null-terminated strings, recursion, and the selection sort algorithm. It includes syntax examples and explanations for each concept, illustrating how they are implemented in C. The document serves as a guide for understanding basic programming structures and techniques in C.

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 (1)

The document provides an overview of fundamental concepts in C programming, including format specifiers for output, decision control statements, arrays, null-terminated strings, recursion, and the selection sort algorithm. It includes syntax examples and explanations for each concept, illustrating how they are implemented in C. The document serves as a guide for understanding basic programming structures and techniques in C.

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) 1) To produce prepared text to the standard output, like the console, in C


programming, use the printf function. The printf function's format specifiers are
placeholders that specify the format and presentation of the following parameters.
They make sure that every value is displayed accurately by telling the compiler what
kind of data should be printed..

What Format Specifiers Do:

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

%d int A signed decimal integer is printed.

It functions identically to the %d specifier; %i


%i int serves as a placeholder for signed decimal
integers.

formats and outputs an unsigned decimal


%u unsigned int
integer.

float or formats and outputs a floating-point number in


%f
double decimal notation.

formats and outputs a floating-point number in


%lf double
fixed-point notation (double precision).

Float or formats and outputs a floating-point number in


%e
double scientific notation (lowercase 'e').
Format Data
Description
Specifier Type

float or formats and outputs a floating-point number in


%E
double scientific notation (uppercase 'E').

formats and outputs a floating-point number in


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

%c char formats and outputs a single character.

%s char* formats and outputs a string of characters.

%p void* formats and outputs a pointer address.

formats and outputs an unsigned hexadecimal


%x unsigned int
integer (lowercase letters).

formats and outputs an unsigned hexadecimal


%X unsigned int
integer (uppercase letters).

%o unsigned int formats and outputs an unsigned octal integer.

%% None formats and outputs a literal '%' character.


Examples:
#include <stdio.h>
int main() {
int integer_53 = 43;
float floating_point17 = 3.1517637;
char character_75 = 'D';
char* test_string_54 = "Happy, World1!";
unsigned int unsigned_int_543 = 245;

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


printf("Floating-point is: %.3f\n", floating_point17);
printf("Character is: %c\n", character_75);
printf("String is: %s\n", test_string_54);
printf("Unsigned Integer is: %u\n", unsigned_int_543);
printf("Hexadecimal is: %x\n", unsigned_int_543);

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 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