C Programming: String and Array Functions Explained

Document Details

FreshWilliamsite1430

Uploaded by FreshWilliamsite1430

Tags

C programming string functions array declaration programming

Summary

This document is a collection of C programming questions and answers, focusing on string manipulation and array declaration and initialization. It explains various string functions like strcpy and strcat, demonstrating usage with examples.

Full Transcript

## Q.8 Explain any 4 String Library Functions (with Syntax and Example) Following are some of the string library functions: 1. Copy Strings (strcpy()) * **Purpose:** Copies content of one string into another. * **Syntax:** ```c #include <stdio.h> #include <string....

## Q.8 Explain any 4 String Library Functions (with Syntax and Example) Following are some of the string library functions: 1. Copy Strings (strcpy()) * **Purpose:** Copies content of one string into another. * **Syntax:** ```c #include <stdio.h> #include <string.h> char *strcpy(char *destination, const char *source); ``` * **Example:** ```c #include <stdio.h> #include <string.h> int main() { char str[] = "Rahul"; char name[6]; strcpy(name, str); printf("%s", name); return 0; } ``` 2. Compare Strings (strcmp) * **Purpose:** Compares two strings in dictionary order. Returns 0 if both strings are equal. * **Syntax:** ```c int strcmp(const char *str1, const char *str2); ``` * **Example:** ```c #include <stdio.h> #include <string.h> int main() { char str1[] = "apple"; char str2[] = "orange"; int result = strcmp(str1, str2); if (result == 0){ printf("Strings are equal \n"); } else if (result > 0) { printf("First string is greater\n"); } else { printf("First string is smaller\n"); } return 0; } ``` 3. String Length (strlen()) * **Purpose:** Returns the length of a string, excluding null terminator (\0). * **Syntax:** ```c size_t strlen(const char *str); ``` * **Example:** ```c #include <stdio.h> #include <string.h> int main() { char str[] = "Hello, World!"; printf("Length of string: %lu\n", strlen(str)); return 0; } ``` 4. String Concentration (strcat()) * **Purpose:** Concatenates (appends) one string to the end of another. * **Syntax:** ```c char *strcat(char *destination, const char *source); ``` * **Example:** ```c #include <stdio.h> #include <string.h> int main() { char str1[20] = "Hello, "; char str2[20] = "World!"; strcat(str1, str2); printf("concatenated string: %s\n", str1); return 0; } ``` ## Q.9 Demonstrate how break and continue statements are used in C programs with examples. 1. **Break statement:** * The break statement is used to exit a loop immediately, regardless of the loop's condition. * **Syntax:** `break;` * **Example:** ```c #include <stdio.h> int main() { printf("Demonstration of break:\n"); for (int i = 1; i <= 10; i++) { if (i == 5) { break; } printf("%d ", i); } printf("\nLoop exited at i = 5.\n"); return 0; } ``` * **Output:** ``` Demonstration of break 1 2 3 4 Loop exited at i = 5. ``` 2. **Continue statement:** * The continue statement is used to skip the rest of the current iteration of the loop and move to the next iteration. It is a jump statement. * **Syntax:** `continue;` * **Example:** ```c #include <stdio.h> int main() { printf("Demonstration of continue:\n"); for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; } printf("%d\n", i); } return 0; } ``` * **Output:** ``` Demonstration of continue: 1 3 5 7 9 ``` ## Q.10 Explain any two looping statements in C with examples. In C, looping statements allow us to execute a block of code repeatedly based on a condition. Some of the looping statements are: 1. **For loop:** * Used to repeat some part of code until the given condition is fulfilled. * Executed at least once, no matter what the condition is. * **Syntax:** ```c for (initialization; condition; increment/decrement) { // code to execute } ``` * **Example:** Print numbers from 1 to 5. ```c #include <stdio.h> int main() { printf("Numbers from 1 to 5: \n"); for (int i = 1; i <= 5; i++) { printf("%d\n", i); } return 0; } ``` * **Output:** ``` Numbers from 1 to 5: 1 2 3 4 5 ``` 2. **While loop:** * The while loop is an entry-controlled loop in C programming language. * This loop can be used to iterate a part of the code while the given condition remains true. * **Syntax:** ```c while (condition) { // code to execute } ``` * **Example:** Print numbers from 1 to 5. ```c #include <stdio.h> int main() { int i = 1; printf("Numbers from 1 to 5: \n"); while (i <= 5) { printf("%d\n", i); i++; } return 0; } ``` * **Output:** ``` Numbers from 1 to 5: 1 2 3 4 5 ``` ## Q.11 Explain switch statement with syntax and examples. In C, the switch statement is used for multi-way branching. * It allows you to execute one block of code from multiple options based on the value of a variable or expression. * **Syntax:** ```c switch (expression) { case value1: // Code to execute if expression == value1 break; case value2: // Code to execute if expression == value2 break; // Add more cases as needed default: // Code to execute if no case matches } ``` * **Explanation:** 1. The expression is evaluated once, and its value is compared with each case. 2. If a case matches, the corresponding code block is executed. 3. The `break` statement terminates the `switch` and prevents execution of the subsequent cases. 4. The `default` block executes if none of the cases match. * **Example:** Program to display a day of the week based on the number (1 to 7) ```c #include <stdio.h> int main() { int day; printf("Enter a no. (1-7):"); scanf("%d ", &day); switch (day) { case 1: printf("Monday\n"); break; case 7: printf("Sunday\n"); break; default: printf("Invalid Input!\n"); } return 0; } ``` * **Output 1:** ``` Enter a no. (1-7): 3 Wednesday ``` * **Output 2:** ``` Enter a no. (1-7): 9 Invalid Input. ``` ## Q.12 Using C, describe different ways to declare and initialize strings. Explain any 3 string functions. In C programming, strings are represented as arrays of characters terminated by a null character ( '\0' ). Here are several ways to declare and initialize strings in C: 1. **Using Character Arrays** * Strings can be declared as character arrays and initialized explicitly. * **a) Compile-Time Initialization** * **Syntax:** ```c char str1[] = "Hello, World!"; ``` * The string is automatically null-terminated. * The size of the array is inferred from the string length plus one (\0). * **b) Explicit Array Size** * **Syntax:** ```c char str2[20] = "Hello!"; ``` * The array is pre-allocated with 20 characters, but only the first 6 are initialized. 2. **Using Pointers** * Strings can be declared as pointers to a `char`. * **a) String Literal:** * **Syntax:** ```c char *str4 = "Hello, World!"; ``` * `str4` points to string literals stored in read-only memory (cannot be modified). Any attempt to modify the contents of `str4` results in undefined behaviour. * **b) Dynamic Memory Allocation:** * **Syntax:** ```c #include <stdlib.h> #include <string.h> char * str5 = malloc(20); strcpy(str5, "Hello!"); ``` * Allocates 20 bytes for the string. Copies a string into allocated memory. * The string can be modified. * Remember to free allocated memory to avoid memory leaks: `free(str5)` 3. **Input from user:** * Strings can be initialized at runtime using standard input functions like `scanf` or `gets`. * **Using `scanf`:** ```c char str6[50]; scanf("%s", str6); ``` * `scanf` stops reading input at whitespace. * No bounds checking - use carefully to avoid buffer overflow. ## 3 Important String Functions * **`strlen( )`** - Returns the length of the string. * **`strcpy( )`** - Copies one string to another. * **`strcat( )`** - Concatenates (appends) one string to another. ## Q.13 Define Array. Explain with suitable example how to declare and initialize a 2-Dimensional Array. An array in C is a collection of elements of the same data type, stored in contiguous memory locations. * Arrays allow storage and manipulation of multiple values using a single variable name, and an index to access the elements. ### Two-Dimensional Arrays A two-dimensional array in C is an array of arrays, where data is organized in rows and columns, similar to a matrix. 1. **Declaration of a 2D Array** * **Syntax:** ```c data-type array-name[rows][columns]; ``` * **Explanation:** * **data-type:** Specifies the type of data the array will hold. * **array-name:** Name of the array. * **rows:** Number of rows. * **columns:** Number of columns. 2. **Initialization of a 2D Array** * **a) Compile-Time Initialization**: You can initialize the array when declaring it. * **Example:** ```c int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} }; ``` * **Output:** ``` 1 2 3 4 5 6 ``` * **Explanation:** * `matrix [2] [3]`- creates a 2x3 array * `{1, 2, 3}` initializes the first row. * `{4, 5, 6}` initializes the second row. * **b) Partial Initialization:** If fewer values are provided from the size, the rest are initialized to 0 * **Example:** ```c int matrix[2][3] = { {1, 2}, {4} }; ``` * **Output:** ``` 1 2 0 4 0 0 ``` * **c) Run-Time Initialization:** You can initialize the array using loops. * **Example:** ```c #include <stdio.h> int main() { int matrix [2][3]; int i, j; for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) { printf("Enter value for matrix [%d][%d]: ", i, j); scanf("%d", &matrix[i][j]); } } printf("The 2D array is:\n"); for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) { printf("%d", matrix[i][j]); } printf("\n"); } return 0; } ``` ## Q.14 Explain `break`, `continue`, and `goto` statements in C with an example. 1. **`goto` Statement:** * The `goto` statement transfers control to a labeled statement within the same function. * It is generally discouraged because it makes code harder to read and debug. * **Syntax:** ```c goto label; label: // code to execute ``` * **Example:** ```c #include <stdio.h> int main() { int i = 1; start: if (i <= 5) { printf("%d ", i); i++; goto start; // Jump to label } return 0; } ``` * **Output:** ``` 1 2 3 4 5 ``` ## Q.15 List the difference between `while` loop and `do-while` loop with an example. | Feature | `while` loop | `do-while` loop | |---|---|---| | Condition check | Condition is checked before execution of the loop body. | Condition is checked after execution of the loop body. | | Execution | The loop body may not execute if the condition is false initially. | The loop body executes at least once, even if the condition is false. | | Preferred Use | Preferred when the loop may not need to run at all. | Preferred when the loop must execute at least once. | | Syntax | `while (condition) { // code }` | `do { // code } while (condition);` | **Example:** * **`while` loop** ```c int count = 5; while (count > 5) { System.out.println("This will not print because the condition is false."); } ``` * **Output:** No output because the condition is false initially. * **`do-while` loop** ```c int count = 5; do { System.out.println("This will print atleast once even if the condition in false."); count--; } while (count>5); ``` * **Output:** This will print at least once, even if the condition is false. ## Q.16 List all conditional control statements used in C. Explain any two with syntax and an example. The conditional control statements in C are: 1. `if` 2. `if-else` 3. `if-else if-else` 4. `nested if` 5. `switch` ## Explanations of two conditional control statements: 1. **`if` statement** * **Purpose:** The `if` statement executes a block of code only if the specified condition is true. * **Syntax:** ```c if (condition) { // code to execute if condition is true } ``` * **Example:** ```c #include <stdio.h> int main() { int number = 10; if (number > 5) { printf("The number is greater than 5.\n"); } return 0; } ``` * **Output:** ``` The number is greater than 5. ``` 2. **`switch` statement:** * **Purpose:** The switch statement allows the execution of one block of code among many alternatives based on the value of an expression. * **Syntax:** ```c switch (expression) { case value1: // Code to execute if expression == value1 break; case value2: // Code to execute if expression == value2 break; // Add more cases as needed default: // Code to execute if no case matches } ``` * **Example:** Program to display a message based on the input choice. ```c #include <stdio.h> int main() { int choice = 2; switch (choice) { case 1: printf("You selected option 1.\n"); break; case 2: printf("You selected option 2.\n"); break; case 3: printf("You selected option 3.\n"); break; default: printf("Invalid choice.\n"); } return 0; } ``` * **Output:** ``` You selected option 2. ``` ## Q.17 Discuss `strcat()` and `strcmp()` functions with an example. 1. **`strcat()` Function:** * It is used to concatenate (append) one string to the end of another. It's a part of the `string.h` library. * **Syntax:** ```c char *strcat(char *destination, const char *source); ``` * **Example:** ```c #include <stdio.h> #include <string.h> int main() { char str1[50] = "Hello, "; char str2[] = "World!"; strcat(str1, str2); printf("Concatenated String: %s\n", str1); return 0; } ``` * **Output:** ``` Concatenated String: Hello, World! ``` * **Key Notes:** * Ensure the destination array has enough space to accommodate the concatenated string. * It does not add extra space between the strings. 2. **`strcmp()` Function:** * It's used to compare two strings in dictionary order. It's a part of the `string.h` library. * **Syntax:** ```c int strcmp(const char *str1, const char *str2); ``` * **Example:** ```c #include <stdio.h> #include <string.h> int main() { char str1[] = "Hello"; char str2[] = "World"; int result = strcmp(str1, str2); if (result == 0) { printf("Strings are equal.\n"); } else if (result < 0) { printf("str1 is less than str2.\n"); } else { printf("str1 is greater than str2.\n"); } return 0; } ``` * **Output:** ``` str1 is less than str2. ``` * **Key Notes:** * It performs a case-sensitive comparison. * It does not consider string lengths explicitly. It stops comparison at the first differing character. ## Q.14 Explain the switch statement with `break` in C, with an example. The `switch` statement in C is a multi-way branching construct that allows decision-making among multiple options. Each option is identified by a `case` label. The `break` statement is used to exit the `switch` block once a specific `case` is executed, preventing the execution of subsequent cases. * **Syntax:** ```c switch (expression) { case value1: // Code to execute if expression == value1 break; case value2: // Code to execute if expression == value2 break; // Add more cases as needed default: // Code to execute if no case matches } ``` * **Example:** Program to display a day of the week based on a number inputted from the user. ```c #include <stdio.h> int main() { int day; printf("Enter a number (1-7): "); scanf("%d", &day); 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"); } return 0; } ``` * **Output:** ``` Enter a number (1-7): 3 Wednesday ``` * **Explanation:** * The `day` variable is being evaluated in the `switch` statement. * The input `day` is 3. * It matches the `case 3` so "Wednesday" is printed. * The `break` statement exits the `switch` block, preventing execution of subsequent cases. * **Without `break`**: The program continues executing all subsequent cases until the end of the `switch` block, which can lead to unintended behavior. The program could print multiple days if `break` is not used. ## Q.15 Explain the difference between call by value and call by reference with example. These functions are called by value and by reference. | Feature | Call by Value | Call by Reference | |---|---|---| | Parameter Passed | A copy of the variable's value. | Address of the variable. | | Original Variable | Remains unchanged. | Can be modified. | | Speed | Slower (copies data) | Faster (uses memory address) | | Complexity | Simple to use | Requires pointers and dereferencing | **Example:** * **Call by Value** ```c #include <stdio.h> void addFive(int num) { num = num + 5; printf("Inside function: %d\n", num); } int main() { int x = 10; addFive(x); printf("After function call: %d\n", x); return 0; } ``` * **Output:** ``` Inside function: 15 After function call: 10 ``` **Explanation:** * The `addFive` function is passed a copy of the `x` variable. So changes made to the parameter `num` inside the function do not affect the original variable `x`. * **Call by Reference** ```c #include <stdio.h> void addFive(int *num) { *num = *num + 5; printf("Inside function: %d\n", *num); } int main() { int x = 10; addFive(&x); printf("After function call: %d\n", x); return 0; } ``` * **Output:** ``` Inside function : 15 After function call : 15 ``` **Explanation:** * The `addFive` function is passed a reference (memory address) of the variable `x`. Changes made to `*num` inside the function directly modify the value of the original variable `x`. ## Q.16 Explain function call, function definition, and function prototype, with examples. * **Function call:** -It is used to execute the function. -It transfers control to the function definition when the function is called. -A function call is a statement that instructs the compiler to execute the function. -We use the function name and parameters with a function call. Parameters are written without a data type. * **Syntax:** ```c function_name(); function_name(parameters); ``` * **Example:** ```c #include <stdio.h> int sum(int a, int b) { return a + b; } int main() { int add = sum(10, 20); printf("The sum of 2 numbers: %d\n", add); return 0; } ``` * **Function Definition:** -It contains the actual code of the function. -It specifies how the function works. -It includes the return type, function name, parameters, and the body (with its statements). * **Syntax:** ```c return_type function_name(data_type1 parameter1, data_type2 parameter2, ...) { // function body return value } ``` * **Example:** ```c int add(int a, int b) { // function definition return a + b; } ``` * **Function Prototype:** - It is a declaration of the function. - It tells the compiler about the function's name, return type, and parameters before the function is used. - It ensures that the function is called correctly in the program.. * **Syntax:** ```c return_type function_name(data_type1 parameter1, data_type2 parameter2, ...); ``` * **Example:** ```c int add(int a, int b); ``` * **Example covering all parts:** ```c #include <stdio.h> int add(int a, int b); // Function prototype int main() { int num1 = 5, num2 = 3; // Function call int result = add(num1, num2); printf("sum = %d\n", result); return 0; } int add(int a, int b){ // Function definition return a + b; } ``` ## Q.17 Explain call by value and call by reference with examples. 1. **Call By Value:** * When a function is called, a copy of the variable's value is passed to the function. Changes made to the parameter inside the function do not affect the original variable. * **Example:** ```c #include <stdio.h> void addFive(int num) { num = num + 5; printf("Inside function: %d\n", num); } int main() { int x = 10; addFive(x); printf("After function call: %d\n", x); return 0; } ``` * **Output:** ``` Inside function: 15 After function call: 10 ``` * **Explanation:** * The `addFive()` function is passed a copy of the variable `x`. Therefore, the changes made to the parameter `num` inside the function do not affect the original variable `x`. 2. **Call by Reference:** * Instead of passing a copy of the variable's value, the memory address (or a reference) of the variable is passed to the function. The function can directly modify the value of the original variable. * **Example:** ```c #include <stdio.h> void addFive(int *num) { *num = *num + 5; printf("Inside function: %d\n", *num); } int main() { int x = 10; addFive(&x); printf("After function call: %d\n", x); return 0; } ``` * **Output:** ``` Inside function: 15 After function call: 15 ``` * **Explanation:** * The `addFive()` function is passed a reference (memory address) of the variable `x`. The changes made to `*num` inside the function directly modify the value of the original variable `x`. ## Q.18 What is a recursive function? Explain how recursion works with an example. * A recursive function is a function that calls itself to solve a problem. * It breaks the problem into smaller sub-problems, and the function keeps calling itself until it reaches a base condition. * **How Recursion Works:** 1. **Base Case:** This is the stopping condition. When reached, the recursion ends. 2. **Recursive Case:** This is where the function calls itself to solve smaller instances of the problem. ### Example: Calculating Factorial Using Recursion * **Factorial Definition:** Factorial of a non-negative integer, n, is denoted as n! and defined as: * 0! = 1 * n! = n * (n - 1)! (for n > 0) * **Recursive function to calculate factorial:** ```c #include <stdio.h> int factorial(int n) { if (n == 0) { // Base case return 1; } // Recursive Case return n * factorial(n - 1); } int main() { int num = 8; printf("Factorial of %d is %d (using recursion)\n", num, factorial(num)); return 0; } ``` * **Explanation:** 1. The `factorial()` function is called initially with an argument `num` (which equals 8 in this example). 2. If `n` equals 0, the base case condition is reached, so the function returns 1 (as 0! equals 1). 3. Otherwise, the function returns `n` multiplied by the result of calling `factorial(n-1)`, which essentially breaks down the problem into smaller recursive calls. * **Output:** ``` Factorial of 8 is 40320 (using recursion) ``` * **How it works (Step by step for factorial(3)):** * **Call:** factorial(3) - Returns `3 * factorial(2)` * **Call:** factorial(2) - Returns `2 * factorial(1)` * **Call:** factorial(1) - Returns `1 * factorial(0)` * **Base Case:** factorial(0) - Returns `1` (recursion stops). * **Return values:** * factorial(1) returns 1 * factorial(2) returns 2 * 1 = 2 * factorial(3) returns 3 * 2 = 6 * **Output:** factorial of 3 is 6 ## Q.19 Explain iteration function and recursion function with an example. * **Iterative Function:** * An iterative function utilizes loops (for, while, or do-while) to repeatedly execute a task until a certain condition is met. * It typically uses less memory than recursive functions. * It is often easier to understand and implement. * **Example: Calculating Factorial Using Iteration** ```c #include <stdio.h> // Iterative function to calculate factorial int factorial_iterative(int n) { int result = 1; for (int i =1; i <= n; i++) { result *= i; // multiply result by i } return result; } int main() { int num = 5; printf("Factorial of %d is %d (using iteration)\n", num, factorial_iterative(num)); return 0; } ``` * **Output:** ``` Factorial of 5 is 120 (using iteration) ``` * **Recursive Function:** * A recursive function calls itself to solve a problem by breaking it down into smaller sub-problems. * It typically uses a base case to stop the recursion. * It can be more memory-intensive due to repeated function calls. * It can be simpler and more elegant than iteration for some problems. * **Example: Calculating Factorial Using Recursion:** ```c #include <stdio.h> int factorial_recursive(int n) { if (n == 0) { return 1; } return n * factorial_recursive(n-1); } int main() { int num = 5; printf("Factorial of %d is %d (using recursion)\n", num, factorial_recursive(num)); return 0; } ``` * **Output:** ``` Factorial of 5 is 120 (using recursion) ``` ## Difference between Iteration and Recursion Functions | Feature | Iterative Function | Recursive Function | |---|---|---| | Method | Uses loops to repeat tasks. | Calls itself to repeat tasks. | | Termination | Controlled by loop condition. | Controlled by the base case. | | Memory Usage | Uses less memory | Uses more memory | | Code Complexity | Simple to understand and implement | Can be harder to understand | | Example | `for`, `while` loops | Function calling itself | ## When to Use Iteration vs. Recursion * **Use iteration** for tasks with fixed and predictable repetitions. * **Use recursion** for problems that can be broken into smaller sub-problems (e.g., factorial, Fibonacci sequence, tree traversal). ## Q.20 What is a function in C? How do you invoke a function in C? Write an example. A function in C is a block of code

Use Quizgecko on...
Browser
Browser