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

Untitled Document

Uploaded by

Nahemiah Rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views12 pages

Untitled Document

Uploaded by

Nahemiah Rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

Reverse an Array

Problem: Write a C program to reverse the elements of an integer array in-place (without using
a second array).

Example:

●​ Input: [10, 20, 30, 40, 50]


●​ Output: [50, 40, 30, 20, 10]

Logic/Approach:

●​ Use two pointers: start pointing to the first element and end pointing to the last.
●​ In a loop, swap the elements at the start and end pointers.
●​ Increment start and decrement end in each iteration.
●​ Stop when the start pointer crosses the end pointer.

C Code:

C
#include <stdio.h>

void reverseArray(int arr[], int size) {


int start = 0;
int end = size - 1;
int temp;

while (start < end) {


// Swap elements
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;

// Move pointers towards the center


start++;
end--;
}
}

int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


for (int i = 0; i < n; i++) printf("%d ", arr[i]);

reverseArray(arr, n);

printf("\nReversed array: ");


for (int i = 0; i < n; i++) printf("%d ", arr[i]);

printf("\n");
return 0;
}

2. Factorial of a Number

Problem: Write a C program to calculate the factorial of a non-negative integer.

Example:

●​ Input: 5
●​ Output: 120 (since 5 * 4 * 3 * 2 * 1 = 120)

Logic/Approach (Iterative):

●​ Initialize a variable factorial to 1.


●​ Handle the base case: if the number is 0, the factorial is 1.
●​ Use a for loop that runs from 1 up to the given number.
●​ In each iteration, multiply factorial by the loop counter.

C Code:

C
#include <stdio.h>

long long findFactorial(int n) {


if (n < 0) {
return -1; // Factorial is not defined for negative numbers
}
if (n == 0) {
return 1;
}

long long factorial = 1;


for (int i = 1; i <= n; i++) {
factorial = factorial * i;
}
return factorial;
}

int main() {
int num = 5;
long long result = findFactorial(num);
printf("Factorial of %d is %lld\n", num, result);
return 0;
}

3. Count Vowels and Consonants in a String

Problem: Write a C program to count the number of vowels and consonants in a given string.

Example:

●​ Input: "Hello World"


●​ Output: Vowels: 3, Consonants: 7

Logic/Approach:

●​ Iterate through each character of the string.


●​ Convert each character to lowercase to simplify the check.
●​ Check if the character is one of 'a', 'e', 'i', 'o', 'u'. If yes, increment the vowel counter.
●​ If the character is an alphabet but not a vowel, increment the consonant counter.

C Code:

C
#include <stdio.h>
#include <ctype.h> // For tolower()

void countVowelsAndConsonants(char str[]) {


int vowels = 0, consonants = 0;

for (int i = 0; str[i] != '\0'; i++) {


char ch = tolower(str[i]);

if (ch >= 'a' && ch <= 'z') {


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}
printf("Vowels: %d, Consonants: %d\n", vowels, consonants);
}

int main() {
char str[] = "Hello World";
countVowelsAndConsonants(str);
return 0;
}

4. Swap Two Numbers Without a Temporary Variable

Problem: Write a C program to swap the values of two integer variables without using a third
(temporary) variable.

Example:

●​ Input: a = 10, b = 20
●​ Output: a = 20, b = 10

Logic/Approach (using arithmetic operators):

●​ a = a + b; (a becomes 30)
●​ b = a - b; (b becomes 30 - 20 = 10)
●​ a = a - b; (a becomes 30 - 10 = 20)
●​ This can also be done using bitwise XOR (^) which is more efficient.

C Code:
C
#include <stdio.h>

int main() {
int a = 10, b = 20;

printf("Before swap: a = %d, b = %d\n", a, b);

// Swapping using arithmetic operators


a = a + b;
b = a - b;
a = a - b;

printf("After swap: a = %d, b = %d\n", a, b);

// An alternative using XOR (often preferred in interviews)


// a = a ^ b;
// b = a ^ b;
// a = a ^ b;

return 0;
}

5. Find Duplicate Elements in an Array

Problem: Write a C program to find and print the duplicate elements in an integer array.

Example:

●​ Input: [4, 2, 8, 2, 6, 4, 8]
●​ Output: Duplicates are: 4 2 8

Logic/Approach (Brute Force):

●​ Use two nested loops.


●​ The outer loop picks an element.
●​ The inner loop checks if that element is present anywhere else in the array ahead of it.
●​ If a duplicate is found, print it. (Be careful not to print the same duplicate multiple times).

C Code (A simple O(n^2) approach):


C
#include <stdio.h>

void findDuplicates(int arr[], int size) {


printf("Duplicates are: ");
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (arr[i] == arr[j]) {
printf("%d ", arr[i]);
break; // Break inner loop to avoid multiple prints for same number
}
}
}
printf("\n");
}

int main() {
int arr[] = {4, 2, 8, 2, 6, 4, 8};
int n = sizeof(arr) / sizeof(arr[0]);
findDuplicates(arr, n);
return 0;
}

6. Check if Two Strings are Anagrams

Problem: Write a C program to check if two strings are anagrams of each other (i.e., they
contain the same characters with the same frequencies).

Example:

●​ Input: "listen", "silent" -> Output: "Strings are Anagrams"


●​ Input: "hello", "world" -> Output: "Strings are not Anagrams"

Logic/Approach (Using a Counting Array):

●​ First, check if the lengths of the two strings are equal. If not, they can't be anagrams.
●​ Create a character counting array (e.g., int count[256] = {0};).
●​ Iterate through the first string and increment the count for each character in the array.
●​ Iterate through the second string and decrement the count for each character.
●​ Finally, check the count array. If all counts are zero, the strings are anagrams.
C Code:

C
#include <stdio.h>
#include <string.h>
#include <stdbool.h> // For bool type

bool areAnagrams(char* str1, char* str2) {


int len1 = strlen(str1);
int len2 = strlen(str2);

if (len1 != len2) {
return false;
}

int count[256] = {0};

for (int i = 0; i < len1; i++) {


count[str1[i]]++;
}

for (int i = 0; i < len2; i++) {


count[str2[i]]--;
}

for (int i = 0; i < 256; i++) {


if (count[i] != 0) {
return false;
}
}
return true;
}

int main() {
if (areAnagrams("listen", "silent")) {
printf("Strings are Anagrams\n");
} else {
printf("Strings are not Anagrams\n");
}
return 0;
}
7. Implement Bubble Sort

Problem: Write a C program to sort an array of integers in ascending order using the Bubble
Sort algorithm.

Example:

●​ Input: [64, 34, 25, 12, 22, 11, 90]


●​ Output: [11, 12, 22, 25, 34, 64, 90]

Logic/Approach:

●​ Use two nested loops.


●​ The outer loop runs from n-1 down to 1.
●​ The inner loop "bubbles up" the largest element to its correct position in each pass by
comparing adjacent elements and swapping them if they are in the wrong order.

C Code:

C
#include <stdio.h>

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


int i, j, temp;
for (i = 0; i < n - 1; i++) {
// Last i elements are already in place
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: ");
for (i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
return 0;
}

8. Print a Half-Pyramid Pattern using Stars

Problem: Write a C program to print a half-pyramid pattern of a specified number of rows using
the * character.

Example:

●​ Input: 5

Output:​
*
**
***
****
*****

●​

Logic/Approach:

●​ Use two nested for loops.


●​ The outer loop controls the number of rows.
●​ The inner loop controls the number of stars to print in each row. The number of stars in
row i is equal to i.

C Code:

C
#include <stdio.h>

void printPattern(int rows) {


for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
}

int main() {
int n = 5;
printPattern(n);
return 0;
}

9. Check for an Armstrong Number

Problem: Write a C program to check if a number is an Armstrong number (a number that is


equal to the sum of its own digits each raised to the power of the number of digits). For a 3-digit
number, this is the sum of the cubes of its digits.

Example:

●​ Input: 153 -> Output: "It is an Armstrong number" (1^3 + 5^3 + 3^3 = 1 + 125 + 27 =
153)
●​ Input: 370 -> Output: "It is an Armstrong number"

Logic/Approach:

●​ Store the original number in a temporary variable.


●​ Initialize a sum variable to 0.
●​ Use a while loop to extract the last digit of the number using the modulo operator (%
10).
●​ Cube this digit and add it to the sum.
●​ Remove the last digit from the number using integer division (/ 10).
●​ Repeat until the number becomes 0.
●​ Compare the sum with the original number.

C Code:

C
#include <stdio.h>

void checkArmstrong(int num) {


int originalNum = num;
int remainder, sum = 0;

while (num > 0) {


remainder = num % 10;
sum += (remainder * remainder * remainder);
num /= 10;
}

if (sum == originalNum) {
printf("%d is an Armstrong number.\n", originalNum);
} else {
printf("%d is not an Armstrong number.\n", originalNum);
}
}

int main() {
checkArmstrong(153);
checkArmstrong(123);
return 0;
}

10. Find the Sum of N Natural Numbers using Recursion

Problem: Write a C program to find the sum of the first N natural numbers using recursion.

Example:

●​ Input: 5
●​ Output: 15 (1 + 2 + 3 + 4 + 5 = 15)

Logic/Approach:

●​ The function sum(n) will return the sum.


●​ The base case is when n is 1 or 0. If n <= 1, the function returns n.
●​ The recursive step is return n + sum(n - 1);. This breaks the problem down into
smaller pieces.

C Code:

C
#include <stdio.h>

int sumOfNaturalNumbers(int n) {
// Base case
if (n <= 1) {
return n;
}
// Recursive step
return n + sumOfNaturalNumbers(n - 1);
}

int main() {
int n = 5;
printf("Sum of first %d natural numbers is %d\n", n, sumOfNaturalNumbers(n));
return 0;
}

You might also like