0% found this document useful (0 votes)
9 views

C PROGRAMMING

The document covers various programming concepts in C, including format specifiers, decision control statements, arrays, null-terminated strings, recursion, and the selection sort algorithm. Each section provides definitions, syntax, examples, and explanations to illustrate how these concepts are utilized in C programming. The document serves as a comprehensive guide for understanding fundamental programming techniques in C.

Uploaded by

satyamkrsingh566
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

C PROGRAMMING

The document covers various programming concepts in C, including format specifiers, decision control statements, arrays, null-terminated strings, recursion, and the selection sort algorithm. Each section provides definitions, syntax, examples, and explanations to illustrate how these concepts are utilized in C programming. The document serves as a comprehensive guide for understanding fundamental programming techniques in C.

Uploaded by

satyamkrsingh566
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

ROLL NUMBER 2414511718

PROGRAM BCA
SMESTER 1ST
NAME SATYAM KUMAR SINGH
Course Code DCA1107
SET-I

ANSWER 1

In C, format specifiers are used in the printf function to define how data should be
displayed. They specify the type and format of the argument(s) passed to the function. Format
specifiers begin with a % symbol, followed by a character that indicates the data type.

Common Format Specifiers in C:

1. %d or %i:
o Data Type: int
o Usage: Prints an integer.
o Example: printf("%d", 5); // Output: 5
2. %f:
o Data Type: float or double
o Usage: Prints a floating-point number.
o Example: printf("%f", 3.14); // Output: 3.140000
3. %c:
o Data Type: char
o Usage: Prints a single character.
o Example: printf("%c", 'A'); // Output: A
4. %s:
o Data Type: char[] (string)
o Usage: Prints a string of characters.
o Example: printf("%s", "Hello"); // Output: Hello
5. %u:
o Data Type: unsigned int
o Usage: Prints an unsigned integer.
o Example: printf("%u", 25); // Output: 25
6. %x or %X:
o Data Type: int
o Usage: Prints an integer in hexadecimal format (lowercase x for lowercase
letters, X for uppercase).
o Example: printf("%x", 255); // Output: ff
7. %o:
o Data Type: int
o Usage: Prints an integer in octal format.
o Example: printf("%o", 8); // Output: 10
8. %p:
o Data Type: void* (pointer)
o Usage: Prints a memory address (pointer value).
o Example: printf("%p", &x); // Output: memory address of x
9. %lf:
o Data Type: double
o Usage: Prints a double precision floating-point number.
o Example: printf("%lf", 3.14159); // Output: 3.141590

Conclusion:
Format specifiers in printf define how different types of data should be displayed, ensuring
that data is presented in the desired format.

Answer 2

Decision Control Statements in C Programming:

Decision control statements in C programming allow the program to make decisions based on
conditions. These statements evaluate expressions and execute specific code blocks
depending on whether the condition is true or false.

Types of Decision Control Statements:

1. if Statement:
o Purpose: The if statement allows the program to execute a block of code if a
specified condition is true.
o Syntax:

c
CopyEdit
if (condition) {
// Code to be executed if the condition is true
}

o Example:

c
CopyEdit
int age = 20;
if (age >= 18) {
printf("You are eligible to vote.\n");
}

 Explanation: In this example, the program checks if the value of age


is greater than or equal to 18. If true, it prints the message.
2. if-else Statement:
o Purpose: The if-else statement allows the program to execute one block of
code if the condition is true and another block if the condition is false.
o Syntax:

c
CopyEdit
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}

o Example:

c
CopyEdit
int number = 5;
if (number > 0) {
printf("Positive number.\n");
} else {
printf("Non-positive number.\n");
}

 Explanation: The program checks if number is positive. If true, it


prints "Positive number," otherwise it prints "Non-positive number."
3. if-else if-else Statement:
o Purpose: This allows multiple conditions to be checked, where each condition
is tested in sequence. If one condition is true, its corresponding block of code
is executed. If none of the conditions are true, the else block is executed.
o Syntax:

c
CopyEdit
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if none of the conditions are true
}

o Example:

c
CopyEdit
int marks = 75;
if (marks >= 90) {
printf("Grade A\n");
} else if (marks >= 70) {
printf("Grade B\n");
} else if (marks >= 50) {
printf("Grade C\n");
} else {
printf("Fail\n");
}

 Explanation: The program evaluates the marks and prints the grade
based on the conditions provided.
4. switch Statement:
o Purpose: The switch statement evaluates an expression and executes one of
many possible blocks of code based on the value of the expression. It is
typically used when there are multiple possible values for a single variable.
o Syntax:

c
CopyEdit
switch (expression) {
case value1:
// Code to be executed if expression == value1
break;
case value2:
// Code to be executed if expression == value2
break;
default:
// Code to be executed if expression doesn't match any case
}

o Example:

c
CopyEdit
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;
default: printf("Invalid day\n");
}

 Explanation: The program checks the value of day and prints the
corresponding weekday. If day does not match any case, the default
block is executed.

Summary of Decision Control Statements:

 if: Executes code if the condition is true.


 if-else: Executes one block of code if true, another if false.
 if-else if-else: Tests multiple conditions sequentially.
 switch: Evaluates an expression and executes a block of code based on matching case
values.

These decision control statements allow a program to make choices and adapt its behavior
based on different inputs or conditions.

Answer 3

Arrays in C Programming:

An array in C is a collection of elements of the same data type, stored in contiguous memory
locations. Arrays allow you to store multiple values in a single variable, making it easier to
manage large sets of data.

Array Declaration:

To declare an array in C, you specify the data type followed by the array name and the size
(number of elements) in square brackets.
Syntax:

c
CopyEdit
data_type array_name[array_size];

Array Initialization:

Arrays can be initialized either during declaration or later.

1. At Declaration: You can initialize an array at the time of declaration by providing


values in curly braces {}.

Example:

c
CopyEdit
int numbers[5] = {1, 2, 3, 4, 5};

2. Without Specifying Size: If the size is omitted, the array will automatically have the
size based on the number of elements provided.

Example:

c
CopyEdit
int numbers[] = {1, 2, 3, 4, 5}; // Size is inferred as 5

3. Partial Initialization: If you provide fewer values than the array size, the remaining
elements are initialized to 0.

Example:

c
CopyEdit
int numbers[5] = {1, 2}; // Remaining elements will be 0: {1, 2, 0, 0, 0}

Accessing Array Elements:

You can access array elements using an index, where the index starts from 0.

Example:

c
CopyEdit
int numbers[] = {1, 2, 3, 4, 5};
printf("%d", numbers[2]); // Output: 3

Conclusion:

Arrays in C are used to store multiple values of the same type. They are declared with a
specific size and can be initialized either at declaration or later in the program.
ANSWER 4

Null-Terminated Strings in C Programming:

In C, a null-terminated string is an array of characters that ends with a special null character
'\0'. This null character marks the end of the string and is used to determine where the string
finishes in memory.

Difference Between Null-Terminated Strings and Regular Character Arrays:

1. Null-Terminated String:
o It is a character array with a null character '\0' at the end to signify the string's
end.
o The size of the array is determined by the length of the string plus one for the
null terminator.
2. Regular Character Array:
o A regular character array does not necessarily have a null character '\0' to
indicate the end of the data. It is just a collection of characters without a
defined end.

Example:

Null-Terminated String:

c
CopyEdit
char str[] = "Hello"; // Automatically includes the null character '\0'
printf("%s", str); // Output: Hello

 Here, str is a null-terminated string with '\0' at the end. The printf function uses '\0' to
identify where the string ends.

Regular Character Array:

c
CopyEdit
char arr[] = {'H', 'e', 'l', 'l', 'o'};
printf("%s", arr); // Undefined behavior: no null terminator

 In this case, arr does not have a null terminator. Attempting to print it with %s could
result in undefined behavior because there is no clear end to the array.

Conclusion:

A null-terminated string in C is a character array that ends with '\0', allowing functions like
printf to identify where the string ends. A regular character array lacks this null terminator,
which can cause issues when processing the array as a string.
Answer 5

Recursion in C Programming:

Recursion in C occurs when a function calls itself to solve smaller instances of a problem. It
is commonly used for problems that can be broken down into simpler, identical subproblems,
like factorials, Fibonacci series, etc.

Necessary Conditions for Recursion:

1. Base Case: The function must have a base case, a condition where the function stops
calling itself. This prevents infinite recursion.
2. Recursive Case: The function must call itself with a modified argument that brings
the problem closer to the base case.

Example: Recursive Function to Calculate Factorial:

Factorial of a number n is defined as:

 n! = n * (n-1) * (n-2) * ... * 1


 0! = 1 (Base case)

Recursive function to calculate factorial:

c
CopyEdit
#include <stdio.h>

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

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

Explanation:

 The function factorial() calls itself with a reduced value of n until n reaches 0.
 When n == 0, the base case is reached, and the recursion stops.

Output:

csharp
CopyEdit
Factorial of 5 is 120

Conclusion:

Recursion in C allows a function to solve complex problems by repeatedly breaking them


into simpler subproblems. For a function to be recursive, it must have a base case and a
recursive case.

Answer 6

Selection Sort Algorithm:

Selection Sort is a simple comparison-based sorting algorithm. The main idea is to


repeatedly find the minimum (or maximum) element from the unsorted part of the array and
move it to the sorted part. It works by dividing the array into two sections: the sorted section
(which starts empty) and the unsorted section (which starts with the entire array). At each
step, the smallest element in the unsorted section is selected and swapped with the first
element of the unsorted section, growing the sorted section.

Steps of Selection Sort:

1. Start from the first element of the array and assume it is the smallest.
2. Compare it with the remaining elements of the array to find the actual smallest
element.
3. Swap the smallest element with the element at the current position.
4. Move the boundary between the sorted and unsorted sections one element forward.
5. Repeat the process until the entire array is sorted.

Time Complexity:

 Worst-case and Average-case: O(n²), where n is the number of elements in the array.
 Best-case: O(n²), because the algorithm always performs the same number of
comparisons, regardless of whether the array is already sorted.

Example:

Consider an array: [64, 25, 12, 22, 11]

Step-by-step process:

1. Find the smallest element in the array [64, 25, 12, 22, 11] (11), and swap it with the
first element: [11, 25, 12, 22, 64].
2. Now, find the smallest element in the remaining unsorted array [25, 12, 22, 64] (12),
and swap it with the second element: [11, 12, 25, 22, 64].
3. Find the smallest element in the remaining unsorted array [25, 22, 64] (22), and swap
it with the third element: [11, 12, 22, 25, 64].
4. Find the smallest element in the remaining unsorted array [25, 64] (25), and no swap
is needed as it is already in place.
5. The array is now sorted: [11, 12, 22, 25, 64].
Selection Sort C Program:

c
CopyEdit
#include <stdio.h>

void selectionSort(int arr[], int n) {


int i, j, minIdx, temp;

// One by one move boundary of unsorted subarray


for (i = 0; i < n - 1; i++) {
minIdx = i;

// Find the minimum element in unsorted array


for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}

// Swap the found minimum element with the first element


if (minIdx != i) {
temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
}
}
}

void printArray(int arr[], int n) {


for (int i = 0; i < n; 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: \n");


printArray(arr, n);

selectionSort(arr, n);

printf("Sorted array: \n");


printArray(arr, n);

return 0;
}

Explanation of the C Program:


 The function selectionSort() performs the selection sort.
 It iterates through the array, finds the minimum element in the unsorted section, and
swaps it with the first unsorted element.
 The printArray() function is used to display the array before and after sorting.

Output:

c
CopyEdit
Original array:
64 25 12 22 11
Sorted array:
11 12 22 25 64

Conclusion:

Selection Sort is easy to understand and implement, but it is inefficient for large datasets due
to its O(n²) time complexity. It is useful when memory space is a concern because it is an in-
place sorting algorithm. However, more efficient algorithms like QuickSort or MergeSort are
generally preferred for larger datasets.

You might also like