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

questions on cs

The document explains conditional branching and loops in C programming, detailing various conditional statements such as if, if-else, nested if, and switch statements. It also covers different types of loops including for, while, and do-while, along with their syntax and use cases. Additionally, it discusses the significance of break and continue statements in loops, as well as examples demonstrating their functionality.

Uploaded by

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

questions on cs

The document explains conditional branching and loops in C programming, detailing various conditional statements such as if, if-else, nested if, and switch statements. It also covers different types of loops including for, while, and do-while, along with their syntax and use cases. Additionally, it discusses the significance of break and continue statements in loops, as well as examples demonstrating their functionality.

Uploaded by

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

CONDITIONAL BRANCHING AND LOOPS The switch statement is used when a variable needs to be tested

1. What is conditional branching? against multiple constant values.


Conditional branching in C is a programming concept where a set Example:
of statements is executed based on whether a condition evaluates to int choice = 2;
true or false. It allows the program to take different execution paths switch (choice) {
depending on given conditions. case 1: printf("Option 1");
break;
2. Name different types of conditional statements in C. case 2: printf("Option 2");
The different types of conditional statements in C are: break;
default: printf("Invalid Option");
• if statement
}
• if-else statement
• nested if statement 9. What happens if a break statement is missing in a switch
• else if ladder case?
• switch statement If the break statement is missing, execution will continue into the
next case.
3. What is the syntax of an if statement in C? Example:
int num = 2;
The basic syntax of an if statement is:
switch (num) {
if (condition) {
case 1: printf("One ");
// Code to execute if the condition is
case 2: printf("Two ");
true
case 3: printf("Three ");
}
}
Example:
int x = 10; Output:
Two Three
if (x > 5) {
printf("X is greater than 5");
} 10. Define loops in C.
Loops in C allow a set of statements to be executed repeatedly
4. What is the difference between if and if-else statements? based on a condition.
Feature if Statement if-else Statement 11. Name the different types of loops in C.
Execution Executes only when the Executes different code for • for loop
Path condition is true true and false cases • while loop
if (condition) { • do-while loop
if (condition) {
Syntax statement1; } else
statement; }
{ statement2; }
12. What is the syntax of a for loop?
if (x > 5) for(initialization; condition;
if (x > 5) printf("True"); increment/decrement) {
Example printf("True"); else
// Code to execute in each iteration
printf("False"); }
Example:
5. What does the else statement do? for(int i = 1; i <= 5; i++) {
The else statement provides an alternative block of code that printf("%d ", i);
executes if the if condition evaluates to false. }
Example: Output:
int num = 10; 1 2 3 4 5
if (num % 2 == 0) {
printf("Even"); 13. What is the difference between a while and do-while loop?
} else { Feature while Loop do-while Loop
printf("Odd");
Condition
} Before execution After execution
Check
6. Can an if statement exist without an else? Execution May not run at all Runs at least once
Yes, an if statement can exist without an else. The else block while(condition) do { statements; }
Syntax { statements; } while(condition);
is optional.
Example:
if (x > 10) { 14. How many times does a do-while loop execute at minimum?
printf("X is greater than 10"); At least one time, even if the condition is false.
}
15. What is an infinite loop?
7. What is a nested if statement? A loop that never terminates because the condition is always true.
A nested if statement is an if condition inside another if Example:
statement. while(1) {
Example: printf("Infinite Loop");
int num = 10; }
if (num > 0) {
if (num % 2 == 0) { 16. What is the purpose of the break statement in loops?
printf("Positive Even Number"); The break statement is used to exit a loop prematurely when a
} condition is met.
} Example:
for(int i = 1; i <= 5; i++) {
8. What is the purpose of the switch statement in C? if(i == 3) break;
printf("%d ", i);
} while(1) {
Output: printf("Looping...");
1 2 }

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");

Long Answer Type Questions (5-6 Marks Each) return 0;


31. Explain conditional branching in C with examples of if, if- }
else, nested if, and switch statements.
Conditional branching allows a program to make decisions based 33. Write a program to determine whether a number is even or
on conditions. odd using if-else.
1. if Statement #include <stdio.h>
if (condition) { int main() {
// Code executes if condition is true int num;
} printf("Enter a number: ");
Example: scanf("%d", &num);
if (age >= 18) {
printf("Eligible to vote."); if (num % 2 == 0)
} printf("Even");
2. if-else Statement else
if (condition) { printf("Odd");
// Executes if true
} else { return 0;
// Executes if false }
}
Example:
if (age >= 18) {
printf("Eligible to vote."); 34. Program to Find the Largest of Three Numbers
} else { Explanation
printf("Not eligible."); • We take three numbers as input.
} • Use if-else conditions to compare the numbers.
3. Nested if Statement
• Print the largest number.
if (condition1) {
Code
if (condition2) { #include <stdio.h>
// Executes if both are true
} int main() {
} int a, b, c;
Example: printf("Enter three numbers: ");
if (age >= 18) { scanf("%d %d %d", &a, &b, &c);
if (citizen == 1) {
printf("Can vote."); if (a >= b && a >= c)
} printf("Largest number: %d\n", a);
} else if (b >= a && b >= c)
4. switch Statement printf("Largest number: %d\n", b);
Used for multiple choices.
else 1 2 3 4 5 6 7 8 9 10
printf("Largest number: %d\n", c);
38. Sum of First 10 Natural Numbers Using While Loop
return 0; Code
} #include <stdio.h>
Output
Enter three numbers: 10 25 7 int main() {
Largest number: 25 int i = 1, sum = 0;

35. Program to Check if a Character is a Vowel or Consonant while (i <= 10) {


Using Switch sum += i;
Explanation i++;
• Take a character as input. }
• Check if it is a, e, i, o, u (both uppercase and lowercase) using a
printf("Sum: %d\n", sum);
switch statement.
return 0;
• If it matches, print "Vowel"; otherwise, print "Consonant". }
Code Output
#include <stdio.h> Sum: 55
int main() { 39. Multiplication Table of a Number Using Loops
char ch;
Code
printf("Enter a character: "); #include <stdio.h>
scanf("%c", &ch);
int main() {
switch (ch) { int num;
case 'a': case 'e': case 'i': case printf("Enter a number: ");
'o': case 'u': scanf("%d", &num);
case 'A': case 'E': case 'I': case
'O': case 'U': for (int i = 1; i <= 10; i++)
printf("Vowel\n"); printf("%d x %d = %d\n", num, i, num
break; * i);
default:
printf("Consonant\n"); return 0;
} }
return 0;
40. Factorial of a Number Using a For Loop
}
Code
Output #include <stdio.h>
Enter a character: E
Vowel int main() {
int num, fact = 1;
36. Explanation of Loops in C printf("Enter a number: ");
Types of Loops scanf("%d", &num);
1. For Loop → Best when iteration count is known.
2. While Loop → Best when iteration count is unknown. for (int i = 1; i <= num; i++)
3. Do-While Loop → Runs at least once before checking the fact *= i;
condition.
Example of For Loop printf("Factorial: %d\n", fact);
for (int i = 1; i <= 5; i++) { return 0;
printf("%d ", i); }
}
Example of While Loop 41. Difference Between Break and Continue
int i = 1; Break
while (i <= 5) {
printf("%d ", i); • Terminates the loop immediately.
for (int i = 1; i <= 5; i++) {
i++;
if (i == 3)
}
break;
Example of Do-While Loop printf("%d ", i);
int i = 1;
}
do {
printf("%d ", i); Output: 1 2
i++; Continue
} while (i <= 5); • Skips the current iteration.
for (int i = 1; i <= 5; i++) {
37. Program to Print Numbers from 1 to 10 Using a For Loop if (i == 3)
Code continue;
#include <stdio.h> printf("%d ", i);
}
int main() { Output: 1 2 4 5
for (int i = 1; i <= 10; i++)
printf("%d ", i); 42. Print Even Numbers Between 1 and 50 Using a While Loop
return 0; Code
} #include <stdio.h>
Output
int main() { printf("Enter a year: ");
int i = 2; scanf("%d", &year);

while (i <= 50) { if ((year % 4 == 0 && year % 100 != 0) ||


printf("%d ", i); (year % 400 == 0))
i += 2; printf("%d is a leap year\n", year);
} else
printf("%d is not a leap year\n",
return 0; year);
}
return 0;
43. Count the Number of Digits in an Integer }
Code
#include <stdio.h> 47. Menu-Driven Program for Arithmetic Operations Using
Switch
int main() { Code
int num, count = 0; #include <stdio.h>
printf("Enter an integer: ");
scanf("%d", &num); int main() {
int choice, a, b;
while (num != 0) { printf("1. Add\n2. Subtract\n3.
num /= 10; Multiply\n4. Divide\nEnter choice: ");
count++; scanf("%d", &choice);
}
printf("Enter two numbers: ");
printf("Number of digits: %d\n", count); scanf("%d %d", &a, &b);
return 0;
} switch (choice) {
case 1: printf("Sum: %d\n", a + b);
44. Nested Loops: Printing a Pyramid Pattern break;
Code case 2: printf("Difference: %d\n", a
#include <stdio.h> - b); break;
case 3: printf("Product: %d\n", a *
int main() { b); break;
int rows = 5; case 4: printf("Quotient: %d\n", a /
b); break;
for (int i = 1; i <= rows; i++) { default: printf("Invalid choice\n");
for (int j = 1; j <= i; j++) }
printf("* ");
printf("\n"); return 0;
} }

return 0; 48. Write a program that calculates the sum of digits of a


} number using a loop.
Output Explanation:
* • The user enters a number.
* * • We extract each digit using the modulus (%) operator.
* * *
* * * * • We sum the digits and update the number by dividing it by 10.
* * * * * Code:
#include <stdio.h>
45. Reverse a Number Using a While Loop
Code int main() {
#include <stdio.h> int num, sum = 0, digit;

int main() { printf("Enter a number: ");


int num, rev = 0; scanf("%d", &num);
printf("Enter a number: ");
scanf("%d", &num); while (num > 0) {
digit = num % 10; // Extract the
while (num != 0) { last digit
rev = rev * 10 + num % 10; sum += digit; // Add it to sum
num /= 10; num = num / 10; // Remove the last
} digit
}
printf("Reversed number: %d\n", rev);
return 0; printf("Sum of digits: %d\n", sum);
} return 0;
}
46. Check if a Year is a Leap Year Example Run:
Code Enter a number: 1234
#include <stdio.h> Sum of digits: 10

int main() { 49. Write a program to check if a number is a palindrome


int year; using loops.
Explanation:
• A palindrome number reads the same forward and backward. for (i = 2; i <= 100; i++) {
isPrime = 1; // Assume the number is
• We reverse the number and compare it with the original.
prime
Code:
#include <stdio.h>
for (j = 2; j * j <= i; j++) {
int main() { if (i % j == 0) {
int num, reversed = 0, remainder, isPrime = 0;
original; break;
}
printf("Enter a number: "); }
scanf("%d", &num);
original = num; if (isPrime)
printf("%d ", i);
while (num > 0) { }
remainder = num % 10;
reversed = reversed * 10 + remainder; return 0;
num = num / 10; }
} Output:
Prime numbers between 1 and 100:
if (original == reversed) 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53
printf("Palindrome\n"); 59 61 67 71 73 79 83 89 97
else
printf("Not a Palindrome\n"); 52. Write a program that reverses a string using loops.
Code:
return 0; #include <stdio.h>
} #include <string.h>
Example Run:
Enter a number: 121 int main() {
Palindrome char str[100], temp;
Enter a number: 123 int i, len;
Not a Palindrome
printf("Enter a string: ");
scanf("%s", str);
50. Write a program that prints the Fibonacci series up to n
terms using a loop.
len = strlen(str);
Explanation:
• Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13... for (i = 0; i < len / 2; i++) {
• Each term is the sum of the two previous terms. temp = str[i];
Code: str[i] = str[len - 1 - i];
#include <stdio.h> str[len - 1 - i] = temp;
}
int main() {
int n, first = 0, second = 1, next; printf("Reversed string: %s\n", str);
return 0;
printf("Enter the number of terms: "); }
scanf("%d", &n); Example Run:
Enter a string: hello
printf("Fibonacci Series: "); Reversed string: olleh
for (int i = 1; i <= n; i++) {
printf("%d ", first); 53. Write a program that finds the greatest common divisor
next = first + second; (GCD) of two numbers using a loop.
first = second; Code:
second = next; #include <stdio.h>
}
int main() {
return 0; int a, b, gcd, i;
}
Example Run: printf("Enter two numbers: ");
Enter the number of terms: 7 scanf("%d %d", &a, &b);
Fibonacci Series: 0 1 1 2 3 5 8
for (i = 1; i <= a && i <= b; i++) {
51. Write a program to print prime numbers between 1 and if (a % i == 0 && b % i == 0)
100 using loops. gcd = i;
Explanation: }
• A prime number is only divisible by 1 and itself.
• We check divisibility using a loop. printf("GCD: %d\n", gcd);
Code: return 0;
#include <stdio.h> }
Example Run:
int main() { Enter two numbers: 36 48
int i, j, isPrime; GCD: 12

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]); }

printArray(numbers, size); 30. What is a string in C? How is it different from a character


array?
return 0; A string in C is a null-terminated character array (char
} str[]), meaning it ends with \0.
Output: Difference:
5 10 15 20
Feature Character Array String
26. How does a 2-D array differ from a 1-D array? A sequence of
Definition A collection of characters characters ending
Feature 1-D Array 2-D Array
with \0
Stores elements in a Stores elements in a table
Storage char arr[5] =
single row or column. (rows and columns). char str[] =
Example {'H', 'e', 'l',
Accessed using a Accessed using two "Hello";
Access 'l', 'o'};
single index arr[i]. indices arr[i][j].
Null
Example No Yes (\0 at the end)
int arr[5]; int arr[3][3]; Termination
Declaration
Example arr[2] arr[1][2] 31. Write a program to input and print a string using gets().
Access #include <stdio.h>

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");

29. Write a program to transpose a 2-D matrix. return 0;


#include <stdio.h> }
Output:
int main() { Strings are different
int matrix[2][2] = {{1, 2}, {3, 4}}; 33. Write a program to reverse a string without using a built-in
int transpose[2][2]; function.
We can reverse a string using two-pointer technique by swapping • Fixed memory location makes inserting and deleting elements
characters from both ends. inefficient.
C Program: • Shifting elements is required:
#include <stdio.h>
• int arr[] = {1, 2, 3, 4, 5};
void reverseString(char str[]) { • // To delete arr[2], we need to shift all
int left = 0, right = 0; elements.
4. Cannot Return Arrays from Functions
// Find the length of the string • In C, functions cannot return entire arrays directly.
while (str[right] != '\0') { • Solution: Return pointers to dynamically allocated arrays.
right++; 5. Wasted Memory (Fragmentation)
}
• Static allocation may lead to unused memory.
right--; // Adjust for null character
• Example:
// Swap characters from both ends • int arr[1000]; // Uses memory even if we
while (left < right) { need only 10 elements
char temp = str[left]; ✅ Solution: Use dynamic memory allocation (malloc()) or
str[left] = str[right]; linked lists.
str[right] = temp; 36. Explain in detail how arrays are stored in memory and how
left++; their addresses are calculated.
right--; Memory Storage of Arrays
} An array is stored in contiguous memory locations. The elements
} are placed sequentially, one after another. The memory address of
each element is calculated using a formula.
int main() { Address Calculation in a 1D Array
char str[100]; If we have an array:
int arr[5] = {10, 20, 30, 40, 50};
printf("Enter a string: "); Assuming:
scanf("%s", str); // Taking input • Base Address = 1000 (memory location of arr[0])
reverseString(str); • Size of each element = 4 bytes (for int)
The address of any element arr[i] is:
printf("Reversed string: %s\n", str); Address of A[i]=Base Address+(i×Size of each element)\text{Addr
return 0; ess of } A[i] = \text{Base Address} + (i \times \text{Size of each
} element})
Explanation: Index Value Address
1. We first find the length of the string. arr[0] 10 1000
2. We use two pointers:
arr[1] 20 1004
o left starts from the beginning.
o right starts from the end. arr[2] 30 1008
3. Swap the characters from both ends until the pointers meet. arr[3] 40 1012
✅ Time Complexity: O(n) arr[4] 50 1016
34. Explain how strings are stored in memory. For arr[3], the address is:
In C, strings are stored as character arrays terminated by a null 1000+(3×4)=1012\text{1000} + (3 \times 4) = 1012
character (\0). 37. Write a program to sort an array using Bubble Sort.
Memory Representation: #include <stdio.h>
char str[] = "HELLO";
H E L L O \0 void bubbleSort(int arr[], int n) {
100 101 102 103 104 105 for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
Each character occupies 1 byte, and \0 is automatically added.
if (arr[j] > arr[j + 1]) {
Using Pointers: // Swap
char *str = "HELLO";
int temp = arr[j];
• str is a pointer to a string literal stored in read-only memory. arr[j] = arr[j + 1];
• Modifying str[0] leads to undefined behavior. arr[j + 1] = temp;
Key Points: }
1. Strings stored in arrays (char str[]) are mutable. }
2. Strings stored in pointers (char *str) are immutable. }
3. The null character (\0) marks the end of the string. }
4. Strings are stored contiguously in memory, enabling fast
traversal. int main() {
35. What are the limitations of arrays? int arr[] = {64, 34, 25, 12, 22, 11, 90};
Arrays in C have certain drawbacks: int n = sizeof(arr) / sizeof(arr[0]);
1. Fixed Size
bubbleSort(arr, n);
• The size of an array must be declared during compilation.
• Cannot dynamically resize without manual memory allocation. printf("Sorted array: ");
2. No Built-in Bounds Checking for (int i = 0; i < n; i++)
• Accessing an out-of-bounds index leads to undefined behavior. printf("%d ", arr[i]);
• Example:
• int arr[5] = {1, 2, 3, 4, 5}; return 0;
}
• printf("%d", arr[10]); // Undefined behavior
Output:
3. Inefficient Insertion & Deletion Sorted array: 11 12 22 25 34 64 90
38. Write a program to merge two sorted arrays into a third else if (arr[mid] < key)
sorted array. low = mid + 1;
#include <stdio.h> else
high = mid - 1;
void mergeArrays(int arr1[], int n1, int }
arr2[], int n2, int merged[]) { return -1;
int i = 0, j = 0, k = 0; }

while (i < n1 && j < n2) { int main() {


if (arr1[i] < arr2[j]) int arr[] = {10, 20, 30, 40, 50};
merged[k++] = arr1[i++]; int key = 30;
else int n = sizeof(arr) / sizeof(arr[0]);
merged[k++] = arr2[j++];
} int index = binarySearch(arr, 0, n - 1,
key);
while (i < n1) merged[k++] = arr1[i++];
while (j < n2) merged[k++] = arr2[j++]; if (index != -1)
} printf("Element found at index %d\n",
index);
int main() { else
int arr1[] = {1, 3, 5, 7}; printf("Element not found\n");
int arr2[] = {2, 4, 6, 8};
int merged[8]; return 0;
}
mergeArrays(arr1, 4, arr2, 4, merged); Output:
Element found at index 2
printf("Merged Sorted Array: ");
for (int i = 0; i < 8; i++) 41. Write a program to multiply two matrices using a 2-D
printf("%d ", merged[i]); array.
#include <stdio.h>
return 0;
} void multiplyMatrices(int a[2][2], int
Output: b[2][2], int result[2][2]) {
Merged Sorted Array: 1 2 3 4 5 6 7 8 for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
39. Write a program to search for an element in an array using result[i][j] = 0;
Linear Search. for (int k = 0; k < 2; k++) {
#include <stdio.h> result[i][j] += a[i][k] *
b[k][j];
int linearSearch(int arr[], int n, int key) { }
for (int i = 0; i < n; i++) { }
if (arr[i] == key) }
return i; }
}
return -1; int main() {
} int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int main() { int result[2][2];
int arr[] = {10, 20, 30, 40, 50};
int key = 30; multiplyMatrices(a, b, result);
int n = sizeof(arr) / sizeof(arr[0]);
printf("Product of matrices:\n");
int index = linearSearch(arr, n, key); for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if (index != -1) printf("%d ", result[i][j]);
printf("Element found at index %d\n", }
index); printf("\n");
else }
printf("Element not found\n");
return 0;
return 0; }
} Output:
Output: Product of matrices:
Element found at index 2 19 22
43 50
40. Write a program to search for an element using Binary 42. Explain the difference between row-major and column-
Search. major order in 2-D arrays.
#include <stdio.h> Row-Major Order:
• In row-major order, elements of a 2D array are stored row by
int binarySearch(int arr[], int low, int row in contiguous memory.
high, int key) { • The formula for accessing an element A[i][j] in a row-major
while (low <= high) {
order is:
int mid = (low + high) / 2;
if (arr[mid] == key)
return mid;
Address=Base Address+[(i×Total columns)+j]×Size of element\tex if (str[i] >= 'a' && str[i] <= 'z')
t{Address} = \text{Base Address} + [(i \times \text{Total str[i] -= 32;
columns}) + j] \times \text{Size of element} }
• Example:
void toLowercase(char str[]) {
• int A[2][3] = {
for (int i = 0; str[i] != '\0'; i++)
• {1, 2, 3}, if (str[i] >= 'A' && str[i] <= 'Z')
• {4, 5, 6} str[i] += 32;
• }; }
Stored in memory as:
1 2 3 4 5 6 int main() {
Column-Major Order: char str[100];
printf("Enter a string: ");
• In column-major order, elements are stored column by column
scanf("%s", str);
in memory.
• The formula for column-major order is: toUppercase(str);
Address=Base Address+[(j×Total rows)+i]×Size of element\text{A printf("Uppercase: %s\n", str);
ddress} = \text{Base Address} + [(j \times \text{Total rows}) + i]
\times \text{Size of element} toLowercase(str);
• Example: printf("Lowercase: %s\n", str);
• 1 4
• 2 5 return 0;
}
• 3 6
Example Output:
Most programming languages like C and C++ use row-major Enter a string: Hello
order, while languages like Fortran use column-major order. Uppercase: HELLO
43. Write a program to find the sum of the main diagonal Lowercase: hello
elements of a square matrix. 46. Write a program to remove all vowels from a string.
#include <stdio.h> #include <stdio.h>
#include <string.h>
int main() {
int matrix[3][3] = { void removeVowels(char str[]) {
{1, 2, 3}, int i, j = 0;
{4, 5, 6}, char result[100];
{7, 8, 9}
}; for (i = 0; str[i] != '\0'; i++) {
int sum = 0; if (str[i] != 'a' && str[i] != 'e' &&
str[i] != 'i' &&
for (int i = 0; i < 3; i++) str[i] != 'o' && str[i] != 'u' &&
sum += matrix[i][i]; str[i] != 'A' && str[i] != 'E' &&
str[i] != 'I' &&
printf("Sum of main diagonal elements: str[i] != 'O' && str[i] != 'U') {
%d\n", sum); result[j++] = str[i];
return 0; }
} }
Output: result[j] = '\0';
Sum of main diagonal elements: 15 strcpy(str, result);
44. Write a program to check if a given string is a palindrome. }
#include <stdio.h>
#include <string.h> int main() {
char str[100];
int main() { printf("Enter a string: ");
char str[100], rev[100]; gets(str);
printf("Enter a string: ");
scanf("%s", str); removeVowels(str);
printf("String after removing vowels:
strcpy(rev, str); %s\n", str);
strrev(rev); // Reverse the string
return 0;
if (strcmp(str, rev) == 0) }
printf("Palindrome\n"); Example Output:
else Enter a string: Hello World
printf("Not a palindrome\n"); String after removing vowels: Hll Wrld
47. Explain the concept of pointer arithmetic in arrays with
return 0; examples.
}
Pointer arithmetic refers to operations that can be performed on
Example Output: pointers, such as:
Enter a string: madam
1. Incrementing a pointer: ptr++ moves the pointer to the next
Palindrome
element.
45. Write a program to convert a string to uppercase and
2. Decrementing a pointer: ptr-- moves the pointer to the
lowercase without using built-in functions.
#include <stdio.h> previous element.
3. Adding an integer to a pointer: ptr + n moves n elements
void toUppercase(char str[]) { ahead.
for (int i = 0; str[i] != '\0'; i++)
4. Subtracting an integer from a pointer: ptr - n moves n Example Output:
elements back. Enter a string: Programming
Example: You entered: Programming
#include <stdio.h> 50. Write a program to copy one string to another without
using strcpy().
int main() { #include <stdio.h>
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; void copyString(char dest[], char src[]) {
int i;
printf("First element: %d\n", *ptr); for (i = 0; src[i] != '\0'; i++)
ptr++; dest[i] = src[i];
printf("Second element: %d\n", *ptr); dest[i] = '\0';
ptr += 2; }
printf("Fourth element: %d\n", *ptr);
int main() {
return 0; char str1[100], str2[100];
} printf("Enter a string: ");
Output: gets(str1);
First element: 10
Second element: 20 copyString(str2, str1);
Fourth element: 40 printf("Copied string: %s\n", str2);
48. Write a program to find the frequency of each character in
a string. return 0;
#include <stdio.h> }
#include <string.h>
51. Write a program to find the smallest element in an array.
void findFrequency(char str[]) { #include <stdio.h>
int freq[256] = {0};
int main() {
for (int i = 0; str[i] != '\0'; i++) int arr[] = {34, 15, 88, 2, 43};
freq[str[i]]++; int n = sizeof(arr) / sizeof(arr[0]);
int min = arr[0];
printf("Character frequencies:\n");
for (int i = 0; i < 256; i++) { for (int i = 1; i < n; i++) {
if (freq[i] > 0) if (arr[i] < min)
printf("%c -> %d\n", i, freq[i]); min = arr[i];
} }
}
printf("Smallest element: %d\n", min);
int main() { return 0;
char str[100]; }
printf("Enter a string: "); Output:
gets(str); Smallest element: 2

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

void printSubstrings(char str[]) { strcat(str1, str2);


int len = strlen(str); strcpy(str2, str1);
for (int i = 0; i < len; i++) { strcpy(str1, str2 + strlen(str1) -
for (int j = i; j < len; j++) { strlen(str2));
for (int k = i; k <= j; k++)
printf("%c", str[k]); printf("After swapping: \nstr1 = %s\nstr2
printf("\n"); = %s\n", str1, str2);
} return 0;
} }
}

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.

You might also like