questions on cs
questions on cs
17. What is the use of the continue statement in loops? I have provided detailed answers for each question. Let me know if
The continue statement skips the current iteration and moves you need more elaboration! 🚀
to the next. Since you requested detailed answers, I'll provide step-by-step
Example: explanations with examples for each question.
for(int i = 1; i <= 5; i++) {
if(i == 3) continue; Short Answer Type Questions (2-3 Marks Each)
printf("%d ", i); 25. Explain the use of the break statement with an example.
} The break statement is used to exit a loop or a switch statement
Output: immediately when a specific condition is met. It helps in
1 2 4 5 optimizing the program by avoiding unnecessary iterations.
Example: Using break in a for loop
18. Which loop is best when the number of iterations is known? #include <stdio.h>
The for loop is best suited when the number of iterations is fixed. int main() {
for (int i = 1; i <= 5; i++) {
19. Which loop is best when the number of iterations is if (i == 3) {
unknown? break; // Exits the loop when i
The while loop is best suited when the number of iterations == 3
depends on a condition. }
printf("%d ", i);
20. Can loops be nested in C? }
Yes, loops can be nested, meaning a loop inside another loop. return 0;
Example: }
for(int i = 1; i <= 3; i++) { Output:
for(int j = 1; j <= 3; j++) { 1 2
printf("* "); • The loop stops when i == 3, so 3, 4, 5 are not printed.
}
printf("\n"); 26. Explain the use of the continue statement with an example.
} The continue statement skips the current iteration of a loop
Output: and moves to the next iteration without exiting the loop.
* * * Example: Using continue to skip printing 3
* * * #include <stdio.h>
* * * int main() {
for (int i = 1; i <= 5; i++) {
Short Answer Questions (2-3 Marks Each) if (i == 3) {
21. Explain the working of an if-else statement with an continue; // Skips when i == 3
example. }
The if-else statement allows execution of one block if a printf("%d ", i);
condition is true and another block if false. }
Example: return 0;
int num = 5; }
if(num % 2 == 0) { Output:
printf("Even"); 1 2 4 5
} else {
printf("Odd");
• The loop continues but skips 3.
}
27. How does a nested loop work? Give an example.
Output: Odd
A nested loop is a loop inside another loop. The inner loop runs
completely for each iteration of the outer loop.
22. What is a switch statement? How is it different from if-else?
Example: Printing a 3×3 matrix
A switch is used for multiple constant conditions, whereas #include <stdio.h>
if-else can handle complex conditions. int main() {
for (int i = 1; i <= 3; i++) { // Outer
23. How does a while loop work? Write an example. loop (rows)
The while loop runs as long as the condition is true. for (int j = 1; j <= 3; j++) { //
Example: Inner loop (columns)
int i = 1; printf("%d ", j);
while(i <= 3) { }
printf("%d ", i); printf("\n"); // Moves to the next
i++; line after inner loop
} }
Output: 1 2 3 return 0;
}
24. Compare for, while, and do-while loops. Output:
• for is used when iterations are known. 1 2 3
• while is used when the condition controls iteration. 1 2 3
1 2 3
• do-while ensures at least one execution.
• The inner loop runs 3 times for each outer loop iteration.
30. What is an infinite loop? Give an example.
28. What will be the output of the following code snippet?
An infinite loop never stops. int x = 10;
Example:
if (x > 5) switch (expression) {
printf("Hello"); case value1:
else // Code
printf("World"); break;
Output: case value2:
Hello // Code
• Since x = 10 is greater than 5, the if condition is true, so break;
"Hello" is printed. default:
// Code
}
29. What will be the output of the following loop?
int i = 1; Example:
while (i <= 3) { int day = 3;
printf("%d ", i); switch (day) {
i++; case 1: printf("Monday"); break;
} case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
Output:
1 2 3 default: printf("Invalid");
}
• The loop runs as long as i <= 3, printing i before incrementing Output:
it. Wednesday
30. What is an infinite loop? Give an example. 32. Write a program that takes a number as input and checks
An infinite loop is a loop that never terminates because the whether it is positive, negative, or zero.
stopping condition is never met. #include <stdio.h>
Example: int main() {
#include <stdio.h> int num;
int main() { printf("Enter a number: ");
while (1) { // Always true condition scanf("%d", &num);
printf("This is an infinite
loop!\n"); if (num > 0)
} printf("Positive");
return 0; else if (num < 0)
} printf("Negative");
This program will keep printing "This is an infinite else
loop!" forever unless manually stopped. printf("Zero");
printf("Prime numbers between 1 and 54. Write a program to check if a number is an Armstrong
100:\n"); number using loops.
Explanation: o if-else can become long and hard to read.
• An Armstrong number is a number where the sum of the cubes 3. Optimized by Compiler
of its digits is equal to the number itself. o Compilers optimize switch using jump tables, whereas if-
• Example: 153 = 1³ + 5³ + 3³ else chains rely on logical comparisons.
Code: 4. Use Case
#include <stdio.h> o switch is best when checking a variable against fixed values.
#include <math.h> o if-else is best when evaluating complex conditions (e.g.,
ranges, logical expressions).
int main() {
int num, original, remainder, sum = 0; 57. What are the advantages and disadvantages of using do-
while loops?
printf("Enter a number: "); ✅ Advantages:
scanf("%d", &num); 1. Guarantees at least one execution
original = num; o Unlike while, a do-while loop runs at least once, even if the
condition is false.
while (num > 0) { 2. Useful for Menu-Driven Programs
remainder = num % 10;
o Example: ATM machine operations, user input validation.
sum += pow(remainder, 3);
3. Better readability when at least one iteration is required
num /= 10;
o Makes logic clear when a loop must execute before checking the
}
condition.
if (sum == original) ❌ Disadvantages:
printf("Armstrong number\n"); 1. Unintended Execution
else o If the condition is initially false, executing the loop once might be
printf("Not an Armstrong number\n"); undesired.
2. Less commonly used
return 0; o while and for are more intuitive in most scenarios.
}
Example Run: 58. When would you use a while loop instead of a for loop?
Enter a number: 153 A while loop is preferred when:
Armstrong number 1. The number of iterations is unknown beforehand.
o Example: Reading a file until EOF.
55. Write a program that finds the sum of all even numbers up o while (!feof(file)) { read file; }
to n using a loop. o
Code: 2. Waiting for user input
#include <stdio.h> o while (user_input != 'q') { scanf("%c",
&user_input); }
int main() { o
int n, sum = 0; 3. Checking real-time conditions
o Example: Continuously monitoring sensor data.
printf("Enter a number: "); o while (temperature < 100) { read sensor; }
scanf("%d", &n); o
On the other hand, a for loop is better when the iteration count
for (int i = 2; i <= n; i += 2) { is known (e.g., iterating from 1 to 10).
sum += i;
} 59. What are the main differences between break and continue
statements?
printf("Sum of even numbers up to %d:
Feature break continue
%d\n", n, sum);
return 0; Skips the current
Purpose Terminates the entire loop
} iteration
Example Run: Effect on Moves to the next
Enter a number: 10 Exits completely
loop iteration
Sum of even numbers up to 10: 30
When a condition is met and
(2 + 4 + 6 + 8 + 10 = 30) When some iterations
Use case no further iterations are
should be skipped
needed
Final Thoughts
These C programs demonstrate essential looping concepts and if (x == 5)
Example if (x == 5) break; continue;
conditional checks. Do you need any modifications or
explanations for a specific part? 😊 Example: Using break in a loop:
Here are detailed answers to your questions: for(int i = 1; i <= 5; i++) {
if(i == 3) break;
56. Why is a switch statement more efficient than multiple if- printf("%d ", i);
else statements? }
A switch statement is often more efficient than multiple if- Output: 1 2 (Loop exits at 3)
else statements because: Example: Using continue in a loop:
1. Direct Jump via Lookup Table for(int i = 1; i <= 5; i++) {
o The switch statement uses a jump table or binary search, if(i == 3) continue;
allowing direct access to cases. printf("%d ", i);
o In contrast, if-else evaluates conditions sequentially, making it }
slower for large conditions. Output: 1 2 4 5 (Skips 3)
2. Improved Readability
o switch is more structured and clear, especially for multiple fixed 60. What is the significance of the loop control variable in
choices. iteration?
A loop control variable (LCV): o Optimized by compilers better than while.
• Controls the execution of the loop.
• Is initialized, checked in the condition, and updated in each 🚀 Summary:
iteration. • switch is faster than if-else for multiple conditions.
• Prevents infinite loops by ensuring a termination condition is met. • do-while ensures at least one execution.
Example: • Use while when iterations are unknown.
for(int i = 1; i <= 5; i++) { // i is the
loop control variable • break stops the loop; continue skips one iteration.
printf("%d ", i); • Nested loops increase time complexity.
} • Infinite loops must be prevented carefully.
Without proper control, loops may never terminate. • Loops are essential for iteration in real-world applications like
AI, authentication, and automation.
61. How does nesting loops affect time complexity? Let me know if you need further explanation! 🚀🔥
When loops are nested, time complexity increases exponentially.
Example: ARRAYS
for(int i = 1; i <= n; i++) { // O(n)
1. What is an Array?
for(int j = 1; j <= n; j++) { // O(n)
An array is a collection of elements of the same data type stored
printf("%d ", i * j);
in contiguous memory locations. It allows storing multiple values
}
using a single variable name.
}
For example, an array of integers:
• Outer loop runs n times int arr[5] = {1, 2, 3, 4, 5};
• Inner loop runs n times per outer loop 2. How is an Array Different from a Normal Variable?
• Total operations: O(n^2) Feature Normal Variable Array
💡 Optimization Tip: Stores Single value Multiple values
• Avoid unnecessary nested loops. Memory Single memory Contiguous memory
• Use better algorithms (e.g., sorting with O(n log n) instead of Allocation location locations
O(n^2)). Accessing Data Direct access Access via index
Declaration int a; int arr[5];
62. What precautions should be taken to avoid infinite loops?
1. Ensure a stopping condition exists 3. What Are the Types of Arrays in C?
2. while (x > 0) { x--; } // Correct 1. One-Dimensional Array (1-D) → int arr[5];
3. while (x > 0) { } // Incorrect (No 2. Two-Dimensional Array (2-D) → int arr[3][3];
decrement) 3. Multi-Dimensional Array → int arr[2][3][4];
4. Update loop control variable properly 4. How Do You Declare a 1-D Array in C?
5. for (int i = 1; i <= 5; i++) // Correct int arr[5]; // Declares an integer array of
6. for (int i = 1; i <= 5;) // Incorrect size 5
(No increment) 5. How Do You Initialize an Array in C?
7. Avoid conditions that always evaluate true int arr[5] = {10, 20, 30, 40, 50}; //
8. while (1) { /* Infinite Loop */ } Initializing all elements
int arr[] = {1, 2, 3}; // Size inferred from
63. What are some real-world applications of conditional values
branching? int arr[5] = {1, 2}; // Remaining values set
1. User authentication systems to 0
2. if (username == "admin" && password == 6. What is the Index of the First Element in an Array?
"1234") { printf("Access granted"); } • Indexing starts from 0 in C.
3. Traffic light control systems • The first element of arr[5] is accessed as arr[0].
4. if (signal == "red") { stop(); }
7. What Happens if You Access an Array Index Out of
5. Game development (AI decision making) Bounds?
6. if (enemy_health <= 0) { enemy_defeated(); }
• Undefined behavior occurs.
64. How does a loop work internally in memory? • The program may crash or produce garbage values.
• Registers store loop control variables (fast execution). Example:
int arr[3] = {1, 2, 3};
• Memory stores conditions and statements. printf("%d", arr[5]); // Out-of-bounds
• Stack memory manages recursion if used inside loops. access
Example of memory visualization for: 8. How Do You Declare a 2-D Array in C?
for(int i = 1; i <= 3; i++) { int matrix[3][3]; // 2D array with 3 rows
printf("%d", i); and 3 columns
} 9. What is the Formula for Finding the Address of an Element
Iteration i Value Condition Check Output in a 1-D Array?
1st 1 True 1 If arr is a 1-D array with base address BA and element size w,
then:
2nd 2 True 2
Address of arr[i]=BA+(i×w)\text{Address of arr[i]} = BA + (i
3rd 3 True 3 \times w)
4th 4 False (Exit) - Example for an integer array (w = 4 bytes):
• Address of arr[2] = Base Address + (2 × 4)
65. Why is a for loop preferred for counter-based iteration? 10. How Do You Access Elements in a 2-D Array?
1. More concise syntax int matrix[2][2] = {{1, 2}, {3, 4}};
2. for(int i = 0; i < n; i++) { } // Compact printf("%d", matrix[1][0]); // Accessing row
3. Easy to understand and modify 1, column 0
o Initialization, condition, and increment in one place. 11. What is a Character Array?
4. Faster execution
A character array is an array of characters, often used to store • Size of each element is the size of the data type (e.g., 4
strings. bytes for an integer in most systems).
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'}; For example, if A[0] is stored at memory address 1000 and the
12. How Do You Initialize a Character Array in C? data type is int (4 bytes), then:
char str1[] = "Hello"; // Implicitly adds
'\0' • A[1] is at 1004
char str2[] = {'H', 'e', 'l', 'l', 'o', • A[2] is at 1008
'\0'}; // Explicit null terminator • and so on.
13. What is a Null Character (\0) in Strings?
• \0 marks the end of a string in C. 22. What are the advantages of using arrays?
• It helps C functions like printf() to know when to stop reading Arrays provide several benefits:
1. Efficient Storage – Elements are stored in contiguous memory
a string.
locations, making access fast.
14. How Does a String Differ from a Character Array?
2. Easy Access – Elements can be accessed using an index (O(1)
Feature Character Array String time complexity).
Null
Not necessary Ends with \0 3. Code Optimization – Arrays allow storing multiple values under a
terminator single variable name.
Can be dynamically 4. Iteration – They can be easily looped through using loops.
Memory Fixed size 5. Sorting & Searching – Useful for implementing algorithms like
allocated
char arr[5] = {'H', char str[] = sorting (Bubble Sort, Quick Sort) and searching (Binary Search,
Example Linear Search).
'e', 'l', 'l', 'o'}; "Hello";
15. What is the Syntax for Declaring a String in C? 23. Write a program to find the largest element in a 1-D array.
char str[10] = "Hello"; // String #include <stdio.h>
declaration
16. What is the Output of strlen("Hello")? int main() {
• strlen("Hello") returns 5 (excludes \0). int arr[] = {10, 50, 25, 75, 30};
17. What Function is Used to Copy One String to Another in int n = sizeof(arr) / sizeof(arr[0]);
C? int max = arr[0];
• strcpy(destination, source);
Example: for (int i = 1; i < n; i++) {
char src[] = "World"; if (arr[i] > max) {
char dest[10]; max = arr[i];
strcpy(dest, src); }
printf("%s", dest); // Output: World }
18. How Do You Concatenate Two Strings in C?
printf("Largest element in the array:
• strcat(destination, source); %d\n", max);
Example: return 0;
char str1[20] = "Hello "; }
char str2[] = "World!";
Output:
strcat(str1, str2); Largest element in the array: 75
printf("%s", str1); // Output: Hello World!
19. Difference Between gets() and scanf() for Reading 24. Write a program to count the number of even and odd
Strings numbers in an array.
Feature gets() scanf() #include <stdio.h>
Spaces Reads entire line Stops at first space
int main() {
Security Unsafe (buffer overflow) Safer
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9,
Example gets(str); scanf("%s", str); 10};
20. What Will Be the Output of the Following Code? int n = sizeof(arr) / sizeof(arr[0]);
Code int even_count = 0, odd_count = 0;
char str[] = "Hello";
printf("%c", str[1]); for (int i = 0; i < n; i++) {
Explanation if (arr[i] % 2 == 0)
• str[1] is the second character of "Hello", which is 'e'. even_count++;
Output else
e odd_count++;
}
Let me know if you need any clarifications or modifications! 😊
Here are detailed answers to your questions: printf("Even numbers count: %d\n",
even_count);
21. Explain how a 1-D array is stored in memory. printf("Odd numbers count: %d\n",
A 1-D array (one-dimensional array) is stored in a contiguous odd_count);
block of memory. Each element is placed sequentially in memory,
one after another. The address of each element is determined by the return 0;
formula: }
Address of A[i]=Base Address+(i×Size of each element)\text{Addr Output:
ess of } A[i] = \text{Base Address} + (i \times \text{Size of each Even numbers count: 5
element}) Odd numbers count: 5
where:
• Base Address is the address of the first element (A[0]). 25. Explain the concept of passing arrays to functions with an
• i is the index of the element. example.
In C, arrays are passed to functions by reference, meaning changes for (int i = 0; i < 2; i++) {
inside the function affect the original array. for (int j = 0; j < 2; j++) {
Example: Passing an array to a function transpose[j][i] = matrix[i][j];
#include <stdio.h> }
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) { printf("Transpose of the matrix:\n");
printf("%d ", arr[i]); for (int i = 0; i < 2; i++) {
} for (int j = 0; j < 2; j++) {
printf("\n"); printf("%d ", transpose[i][j]);
} }
printf("\n");
int main() { }
int numbers[] = {5, 10, 15, 20};
int size = sizeof(numbers) / return 0;
sizeof(numbers[0]); }
27. Write a program to find the sum of all elements in a 2-D int main() {
array. char str[100];
#include <stdio.h>
printf("Enter a string: ");
int main() { gets(str);
int arr[2][2] = {{1, 2}, {3, 4}};
int sum = 0; printf("You entered: %s\n", str);
return 0;
for (int i = 0; i < 2; i++) { }
for (int j = 0; j < 2; j++) { Warning: gets() is unsafe; use fgets(str,
sum += arr[i][j]; sizeof(str), stdin) instead.
}
} 32. Explain the use of strcmp() function in C with an
example.
printf("Sum of all elements: %d\n", sum); strcmp() compares two strings:
return 0;
} • Returns 0 if equal.
Output: • Returns a positive or negative value otherwise.
Sum of all elements: 10 Example:
#include <stdio.h>
28. How do you declare and initialize a 2-D array in C? #include <string.h>
Declaration:
int matrix[3][3]; int main() {
Initialization: char str1[] = "Hello";
int matrix[2][3] = { char str2[] = "World";
{1, 2, 3},
{4, 5, 6} if (strcmp(str1, str2) == 0)
}; printf("Strings are equal\n");
Accessing elements: else
printf("%d", matrix[1][2]); // Output: 6 printf("Strings are different\n");
findFrequency(str); 52. Write a program to check if two matrices are equal or not.
#include <stdio.h>
return 0;
} int areEqual(int A[3][3], int B[3][3], int
Example Output: rows, int cols) {
Enter a string: hello for (int i = 0; i < rows; i++) {
Character frequencies: for (int j = 0; j < cols; j++) {
h -> 1 if (A[i][j] != B[i][j])
e -> 1 return 0;
l -> 2 }
o -> 1 }
return 1;
49. Explain passing a string to a function with an example. }
Strings in C are passed to functions as character arrays using
pointers. int main() {
Example: int A[3][3] = {{1, 2, 3}, {4, 5, 6}, {7,
#include <stdio.h> 8, 9}};
int B[3][3] = {{1, 2, 3}, {4, 5, 6}, {7,
void printString(char str[]) { 8, 9}};
printf("You entered: %s\n", str);
} if (areEqual(A, B, 3, 3))
printf("Matrices are equal.\n");
int main() { else
char str[100]; printf("Matrices are not equal.\n");
printf("Enter a string: ");
gets(str); return 0;
}
printString(str); Output:
Matrices are equal.
return 0;
}
53. Write a program to print the upper and lower triangular printf("Word count: %d\n",
parts of a matrix. countWords(str));
#include <stdio.h> return 0;
}
int main() { Output:
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, Word count: 5
{7, 8, 9}}; 56. Write a program to replace all occurrences of a character
in a string.
printf("Upper Triangular Matrix:\n"); #include <stdio.h>
for (int i = 0; i < 3; i++) { #include <string.h>
for (int j = 0; j < 3; j++) {
if (i > j) void replaceChar(char str[], char oldChar,
printf(" "); char newChar) {
else for (int i = 0; str[i] != '\0'; i++)
printf("%d ", matrix[i][j]); if (str[i] == oldChar)
} str[i] = newChar;
printf("\n"); }
}
int main() {
printf("\nLower Triangular Matrix:\n"); char str[] = "hello world";
for (int i = 0; i < 3; i++) { replaceChar(str, 'o', 'x');
for (int j = 0; j < 3; j++) { printf("Updated string: %s\n", str);
if (i < j) return 0;
printf(" "); }
else Output:
printf("%d ", matrix[i][j]); Updated string: hellx wxrld
}
printf("\n"); 57. Write a program to swap two strings without using a third
} variable.
#include <stdio.h>
return 0; #include <string.h>
}
54. Write a program to print all substrings of a given string. int main() {
#include <stdio.h> char str1[100] = "Hello";
#include <string.h> char str2[100] = "World";
int main() { 58. Write a program to print the second largest number in an
char str[] = "abc"; array.
printSubstrings(str); #include <stdio.h>
return 0;
} int main() {
Output: int arr[] = {12, 35, 1, 10, 34, 1};
a int n = sizeof(arr) / sizeof(arr[0]);
ab int first = arr[0], second = -1;
abc
b for (int i = 1; i < n; i++) {
bc if (arr[i] > first) {
c second = first;
55. Write a program to count the number of words in a string. first = arr[i];
#include <stdio.h> } else if (arr[i] > second && arr[i]
#include <string.h> != first) {
second = arr[i];
int countWords(char str[]) { }
int count = 1; }
for (int i = 0; str[i] != '\0'; i++)
if (str[i] == ' ' && str[i + 1] != ' printf("Second largest element: %d\n",
') second);
count++; return 0;
return count; }
}
59. Write a program to reverse a 1-D array.
int main() { #include <stdio.h>
char str[] = "Hello World This is C";
void reverseArray(int arr[], int n) {
int temp; printf("Memory allocation failed\n");
for (int i = 0; i < n / 2; i++) { } else {
temp = arr[i]; // Use the array
arr[i] = arr[n - i - 1]; free(arr); // Free the allocated memory
}
CONCEPTUAL AND ANALYTICAL QUESTIONS Dynamic allocation is useful when the array size is unknown at
61. Why is the size of an array fixed in C? compile time.
In C, when an array is declared, it is allocated a contiguous block
of memory in RAM. The size is fixed because: 66. How does pointer arithmetic work in arrays?
1. Memory Allocation: The compiler needs to allocate a specific Pointer arithmetic allows traversal through an array using pointer
amount of memory at compile time. increment and decrement.
2. Indexing Efficiency: Knowing the size allows direct index-based Example:
access to elements using pointer arithmetic. int arr[] = {10, 20, 30, 40};
3. No Built-in Dynamic Resizing: Unlike languages like Python, C int *ptr = arr;
does not support automatic resizing of arrays.
4. Prevention of Memory Issues: If arrays could change sizes printf("%d\n", *ptr); // 10
dynamically, it would lead to fragmentation and inefficiencies. printf("%d\n", *(ptr + 1)); // 20 (Moves to
To overcome this limitation, dynamic memory allocation using next integer in memory)
malloc() or calloc() is used. Each increment (ptr + 1) moves the pointer by the size of the
data type (e.g., sizeof(int)).
62. Explain how pointer notation can be used to access array
elements. 67. Why does scanf("%s", str) not require an & before
Arrays and pointers are closely related in C. The name of an array str?
is essentially a pointer to its first element. Normally, scanf() requires & because it needs the address of a
Using array notation: variable.
int arr[3] = {10, 20, 30}; Example with integers:
printf("%d", arr[1]); // Output: 20 int x;
Using pointer notation: scanf("%d", &x); // Address of x is required
int *ptr = arr; For strings, str is already an address:
printf("%d", *(ptr + 1)); // Output: 20 char str[20];
• ptr points to the first element (arr[0]). scanf("%s", str); // `str` is an address, so
• *(ptr + 1) accesses the second element (arr[1]). `&` is not needed
Both notations are equivalent, and pointer arithmetic can be used to
traverse arrays efficiently. 68. Compare strcpy() and strncpy().
Function Description Safety
63. What is the difference between character arrays and strcpy(dest, Copies entire string, Unsafe (buffer
pointers in strings? src) including \0 overflow possible)
Feature Character Array Pointer to String strncpy(dest, Copies at most n Safer but may not
Memory Stores the string in a Stores the address of a string src, n) characters null-terminate
Storage fixed array literal Example:
Mutable (can Immutable (modifying leads char src[] = "Hello";
Mutability
modify contents) to undefined behavior) char dest[10];
Stored in stack String literals are stored in strcpy(dest, src); // Safe if dest is large
Allocation enough
memory read-only memory
Using strncpy():
Example:
char arr[] = "Hello"; // Stored in stack, strncpy(dest, src, 3);
mutable dest[3] = '\0'; // Ensuring null termination
char *ptr = "Hello"; // Stored in read-only
memory, immutable 69. What happens if you try to store more characters in a
If you modify ptr[0] = 'h';, it causes undefined behavior. string than its declared size?
If a string exceeds its allocated memory, it overwrites adjacent
64. Why is gets() considered unsafe for reading strings? memory, leading to:
The gets() function reads input until a newline character is 1. Segmentation faults
2. Buffer overflow vulnerabilities
encountered, but it does not check for buffer overflow. If the input
3. Corrupt data
is longer than the allocated array, it overwrites adjacent memory,
Example of overflow:
leading to:
char str[5] = "Hello"; // Array is too small
1. Buffer Overflow Attacks – Hackers can exploit this to inject for "Hello" + '\0'
malicious code.
To prevent this, always allocate enough memory and use
2. Memory Corruption – Overwriting adjacent memory may crash
fgets() instead of gets().
the program.
Safe Alternative:
char str[50]; 70. Why is char str[] = "Hello" different from char
fgets(str, sizeof(str), stdin); // Limits *str = "Hello"?
input size to prevent overflow Declaration Description
char str[] = Creates a mutable array, stored in stack
65. How can you dynamically allocate memory for arrays? "Hello"; memory.
In C, we use malloc(), calloc(), or realloc() for
char *str = Creates a pointer to a string literal, stored
dynamic allocation. "Hello"; in read-only memory.
Example using malloc():
int *arr = (int*)malloc(5 * sizeof(int)); // Example:
Allocates memory for 5 integers char str1[] = "Hello";
if (arr == NULL) { str1[0] = 'h'; // ✅ Allowed
char *str2 = "Hello";
str2[0] = 'h'; // ❌ Undefined behavior
Trying to modify str2 causes a segmentation fault because
string literals are stored in a read-only section of memory.