Unit-II Conditional Branching and Loops:
1. Assign a letter grade (A-F) based on percentage using an if-else ladder.
C Code:
#include <stdio.h>
int main() {
float percentage; printf("Enter percentage: ");
scanf("%f",&percentage);
if (percentage >= 90)
printf("Grade: A\n");
else if (percentage >= 80)
printf("Grade: B\n");
else if (percentage >= 70)
printf("Grade: C\n");
else if (percentage >= 60)
printf("Grade: D\n");
else if (percentage >= 50)
printf("Grade: E\n");
else
printf("Grade: F\n");
return 0;
}
Output:
Enter percentage: 20
Grade: F
Python Code:
percentage = float(input("Enter percentage: "))
if percentage >= 90:
print("Grade: A")
elif percentage >= 80:
print("Grade: B")
elif percentage >= 70:
print("Grade: C")
elif percentage >= 60:
print("Grade: D")
elif percentage >= 50:
print("Grade: E")
else:
print("Grade: F")
Output:
Enter percentage: 20
Grade: F
2. Build a menu-driven calculator with add/sub/mul/div using switch-case.
C Code:
#include <stdio.h>
int main() {
int choice;
float a, b;
printf("Enter two numbers: ");
scanf("%f %f", &a, &b);
printf("Choose operation:\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\n");
scanf("%d", &choice);
switch(choice) {
case 1: printf("Result: %.2f\n", a + b); break; case
2: printf("Result: %.2f\n", a - b); break; case 3:
printf("Result: %.2f\n", a * b); break; case 4:
if (b != 0)
printf("Result: %.2f\n", a / b);
else
printf("Division by zero error\n"); break;
default: printf("Invalid choice\n");
}
return 0;
}
Output:
Enter two numbers: 10
20
Choose operation:
1. Add
2. Subtract
3. Multiply
4. Divide
1
Result: 30.00
Python Code:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Choose operation:\n1. Add\n2. Subtract\n3. Multiply\n4. Divide") choice =
int(input("Enter choice: "))
if choice == 1:
print("Result:", a + b)
elif choice == 2:
print("Result:", a - b)
elif choice == 3:
print("Result:", a * b)
elif choice == 4:
if b != 0:
print("Result:", a / b)
else:
print("Division by zero error")
else:
print("Invalid choice")
Output:
Enter two numbers: 10
20
Choose operation:
1. Add
2. Subtract
3. Multiply
4. Divide
1
Result: 30.00
3. Use goto to break out of nested loops (demonstration only).
C Code:
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++) { if (i == 2 && j == 2)
goto end;
printf("i=%d j=%d\n", i, j);
}
}
end:
printf("Exited from nested loops\n"); return 0;
}
Output:
i=1 j=1
i=1 j=2
i=1 j=3
i=2 j=1
Python Code:
for i in range(1, 4):
for j in range(1, 4):
if i == 2 and j == 2:
print("Exited from nestedloops")
exit()
print(f"i={i} j={j}")
Output:
i=1 j=1
i=1 j=2
i=1 j=3
i=2 j=1
4. Sum all even numbers between 1 and N using a for loop.
C Code:
#include <stdio.h>
int main() {
int N, sum = 0;
printf("Enter the value of N: ");
scanf("%d", &N);
for (int i = 2; i <= N; i += 2) {
sum += i;
}
printf("Sum of even numbers from 1 to %d is %d\n", N, sum);
return 0;
}
Output:
Enter the value of N: 29
Sum of even numbers from 1 to 29 is 210
Python Code:
N = int(input("Enter the value of N: "))
sum_even = 0
for i in range(2, N + 1, 2):
sum_even += i
print(f"Sum of even numbers from 1 to {N} is {sum_even}")
Output:
Enter the value of N: 29
Sum of even numbers from 1 to 29 is 210
5. Print multiplication tables 1–10 using nested loops
C Code:
#include <stdio.h>
int main()
{
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
printf("%d x %d = %d\t", i, j, i * j);
}
printf("\n");
}
return 0;
}
Output:
1 x 1 = 1, 1 x 2 = 2, 1 x 3 = 3, 1 x 4 = 4, 1 x 5 = 5, 1 x 6 = 6, 1 x 7 = 7, 1 x 8 = 8, 1 x 9 = 9, 1 x 10 = 10,
2 x 1 = 2, 2 x 2 = 4, 2 x 3 = 6, 2 x 4 = 8, 2 x 5 = 10, 2 x 6 = 12, 2 x 7 = 14, 2 x 8 = 16, 2 x 9 = 18, 2 x 10 = 20,
3 x 1 = 3, 3 x 2 = 6, 3 x 3 = 9, 3 x 4 = 12, 3 x 5 = 15, 3 x 6 = 18, 3 x 7 = 21, 3 x 8 = 24, 3 x 9 = 27, 3 x 10 = 30,
4 x 1 = 4, 4 x 2 = 8, 4 x 3 = 12, 4 x 4 = 16, 4 x 5 = 20, 4 x 6 = 24, 4 x 7 = 28, 4 x 8 = 32, 4 x 9 = 36, 4 x 10 = 40,
5 x 1 = 5, 5 x 2 = 10, 5 x 3 = 15, 5 x 4 = 20, 5 x 5 = 25, 5 x 6 = 30, 5 x 7 = 35, 5 x 8 = 40, 5 x 9 = 45, 5 x 10 = 50,
6 x 1 = 6, 6 x 2 = 12, 6 x 3 = 18, 6 x 4 = 24, 6 x 5 = 30, 6 x 6 = 36, 6 x 7 = 42, 6 x 8 = 48, 6 x 9 = 54, 6 x 10 = 60,
7 x 1 = 7, 7 x 2 = 14, 7 x 3 = 21, 7 x 4 = 28, 7 x 5 = 35, 7 x 6 = 42, 7 x 7 = 49, 7 x 8 = 56, 7 x 9 = 63, 7 x 10 = 70,
8 x 1 = 8, 8 x 2 = 16, 8 x 3 = 24, 8 x 4 = 32, 8 x 5 = 40, 8 x 6 = 48, 8 x 7 = 56, 8 x 8 = 64, 8 x 9 = 72, 8 x 10 = 80,
9 x 1 = 9, 9 x 2 = 18, 9 x 3 = 27, 9 x 4 = 36, 9 x 5 = 45, 9 x 6 = 54, 9 x 7 = 63, 9 x 8 = 72, 9 x 9 = 81, 9 x 10 = 90,
10 x 1 = 10, 10 x 2 = 20, 10 x 3 = 30, 10 x 4 = 40, 10 x 5 = 50, 10 x 6 = 60, 10 x 7 = 70, 10 x 8 = 80, 10 x 9 = 90,
10 x 10 = 100,
Python Code:
for i in range(1, 11):
for j in range(1, 11):
print(f"{i} x {j} = {i*j}", end="\t")
print()
Output:
1 x 1 = 1, 1 x 2 = 2, 1 x 3 = 3, 1 x 4 = 4, 1 x 5 = 5, 1 x 6 = 6, 1 x 7 = 7, 1 x 8 = 8, 1 x 9 = 9, 1 x 10 = 10,
2 x 1 = 2, 2 x 2 = 4, 2 x 3 = 6, 2 x 4 = 8, 2 x 5 = 10, 2 x 6 = 12, 2 x 7 = 14, 2 x 8 = 16, 2 x 9 = 18, 2 x 10 = 20,
3 x 1 = 3, 3 x 2 = 6, 3 x 3 = 9, 3 x 4 = 12, 3 x 5 = 15, 3 x 6 = 18, 3 x 7 = 21, 3 x 8 = 24, 3 x 9 = 27, 3 x 10 = 30,
4 x 1 = 4, 4 x 2 = 8, 4 x 3 = 12, 4 x 4 = 16, 4 x 5 = 20, 4 x 6 = 24, 4 x 7 = 28, 4 x 8 = 32, 4 x 9 = 36, 4 x 10 = 40,
5 x 1 = 5, 5 x 2 = 10, 5 x 3 = 15, 5 x 4 = 20, 5 x 5 = 25, 5 x 6 = 30, 5 x 7 = 35, 5 x 8 = 40, 5 x 9 = 45, 5 x 10 = 50,
6 x 1 = 6, 6 x 2 = 12, 6 x 3 = 18, 6 x 4 = 24, 6 x 5 = 30, 6 x 6 = 36, 6 x 7 = 42, 6 x 8 = 48, 6 x 9 = 54, 6 x 10 = 60,
7 x 1 = 7, 7 x 2 = 14, 7 x 3 = 21, 7 x 4 = 28, 7 x 5 = 35, 7 x 6 = 42, 7 x 7 = 49, 7 x 8 = 56, 7 x 9 = 63, 7 x 10 = 70,
8 x 1 = 8, 8 x 2 = 16, 8 x 3 = 24, 8 x 4 = 32, 8 x 5 = 40, 8 x 6 = 48, 8 x 7 = 56, 8 x 8 = 64, 8 x 9 = 72, 8 x 10 = 80,
9 x 1 = 9, 9 x 2 = 18, 9 x 3 = 27, 9 x 4 = 36, 9 x 5 = 45, 9 x 6 = 54, 9 x 7 = 63, 9 x 8 = 72, 9 x 9 = 81, 9 x 10 = 90,
10 x 1 = 10, 10 x 2 = 20, 10 x 3 = 30, 10 x 4 = 40, 10 x 5 = 50, 10 x 6 = 60, 10 x 7 = 70, 10 x 8 = 80, 10 x 9 = 90,
10 x 10 = 100,
6. Reverse a one-dimensional array in-place.
C Code:
#include <stdio.h>
int main() {
int arr[100], n, temp;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter elements:\n");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
for (int i = 0; i < n / 2; i++) {
temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
printf("Reversed array:\n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output:
Enter number of elements: 5
Enter elements:
1
2
3
5
4
Reversed array:
45321
Python Code:
arr = list(map(int, input("Enter array elements separated by space: ").split()))
n = len(arr)
for i in range(n // 2):
arr[i], arr[n - 1 - i] = arr[n - 1 - i], arr[i]
print("Reversed array:", arr)
Output:
Enter number of elements: 5
Enter elements:
1
2
3
5
4
Reversed array:
45321
7. Find the second-largest element in an array.
C Code:
#include <stdio.h>
int main() {
int arr[100], n, largest, second;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter elements:\n");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
largest = second = -2147483648;
for (int i = 0; i < n; i++) {
if (arr[i] > largest) {
second = largest;
largest = arr[i];
} else if (arr[i] > second && arr[i] != largest) {
second = arr[i];
}
}
if (second == -2147483648)
printf("No second largest element\n");
else
printf("Second largest element is %d\n", second);
return 0;
}
Output:
Enter number of elements: 4
Enter elements:
1
55
44
3
Second largest element is 44
Python Code:
arr = list(map(int, input("Enter array elements separated by space: ").split()))
unique = list(set(arr))
if len(unique) < 2:
print("No second largest element")
else:
[Link](reverse=True)
print("Second largest element is", unique[1])
Output:
Enter number of elements: 4
Enter elements:
1
55
44
3
Second largest element is 44
8. Linearly search an element in an array and report its index.
C Code:
#include <stdio.h>
int main() {
int arr[100], n, key, found = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter elements:\n");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Enter element to search: ");
scanf("%d", &key);
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
printf("Element found at index %d\n", i);
found = 1;
break;
}
}
if (!found)
printf("Element not found\n");
return 0;
}
Output:
Enter number of elements: 4
Enter elements:
4
2
5
6
Enter element to search: 3
Element not found
Python Code:
arr = list(map(int, input("Enter array elements separated by space: ).split()))
key = int(input("Enter element to search: "))
if key in arr:
print(f"Element found at index {[Link](key)}")
else:
print("Element not found")
Output:
Enter number of elements: 4
Enter elements:
4
2
5
6
Enter element to search: 3
Element not found
9. Merge two already-sorted arrays into one sorted array.
C Code:
#include <stdio.h>
int main() {
int a[100], b[100], c[200], m, n, i = 0, j = 0, k = 0;
printf("Enter number of elements in first sorted array: ");
scanf("%d", &m);
printf("Enter elements of first array (sorted):\n");
for (int x = 0; x < m; x++) scanf("%d", &a[x]);
printf("Enter number of elements in second sorted array: ");
scanf("%d", &n);
printf("Enter elements of second array (sorted):\n");
for (int x = 0; x < n; x++) scanf("%d", &b[x]);
// Merge
while (i < m && j < n) {
if (a[i] < b[j])
c[k++] = a[i++];
else
c[k++] = b[j++];
}
while (i < m) c[k++] = a[i++];
while (j < n) c[k++] = b[j++];
printf("Merged sorted array:\n");
for (int x = 0; x < k; x++) printf("%d ", c[x]);
return 0;
}
Output:
Enter number of elements in first sorted array: 3
Enter elements of first array (sorted):
1
5
7
Enter number of elements in second sorted array: 2
Enter elements of second array (sorted):
2
4
Merged sorted array:
12457
Python Code:
a = list(map(int, input("Enter first sorted array: ").split()))
b = list(map(int, input("Enter second sorted array: ").split()))
# Merge and sort
c = sorted(a + b)
print("Merged sorted array:", c)
Output:
Enter number of elements in first sorted array: 3
Enter elements of first array (sorted):
1
5
7
Enter number of elements in second sorted array: 2
Enter elements of second array (sorted):
2
4
Merged sorted array:
12457
10. Rotate an array left by k positions
C Code:
#include <stdio.h>
int main() {
int arr[100], n, k;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
printf("Enter number of positions to rotate left: ");
scanf("%d", &k);
k = k % n; // handle cases where k > n
// Rotate using temporary array
int temp[100];
int index = 0;
for (int i = k; i < n; i++) temp[index++] = arr[i];
for (int i = 0; i < k; i++) temp[index++] = arr[i];
printf("Array after left rotation:\n");
for (int i = 0; i < n; i++) printf("%d ", temp[i]);
return 0;
}
Output:
Enter number of elements: 3
Enter array elements:
1
2
3
Enter number of positions to rotate left: 4
Array after left rotation:
231
Python Code:
arr = list(map(int, input("Enter array elements: ").split()))
k = int(input("Enter number of positions to rotate left: "))
n = len(arr)
k = k % n # Handle k > n
rotated = arr[k:] + arr[:k]
print("Array after left rotation:", rotated)
Output:
Enter number of elements: 3
Enter array elements:
1
2
3
Enter number of positions to rotate left: 4
Array after left rotation:
231
11. Count vowels, consonants, digits and spaces in a string.
C Code:
#include <stdio.h>
#include <ctype.h>
int main() {
char str[200];
int vowels = 0, consonants = 0, digits = 0, spaces = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
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++;
} else if (ch >= '0' && ch <= '9') {
digits++;
} else if (ch == ' ') {
spaces++;
}
}
printf("Vowels: %d\nConsonants: %d\nDigits: %d\nSpaces: %d\n", vowels,
consonants, digits, spaces);
return 0;
}
Output:
Enter a string: gcc Testing.c
Vowels: 2
Consonants: 9
Digits: 0
Spaces: 1
Python Code:
s = input("Enter a string: ")
vowels = consonants = digits = spaces = 0
for ch in [Link]():
if ch in 'aeiou':
vowels += 1
elif [Link]():
consonants += 1
elif [Link]():
digits += 1
elif [Link]():
spaces += 1
print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
print(f"Digits: {digits}")
print(f"Spaces: {spaces}")
Output:
Enter a string: gcc Testing.c
Vowels: 2
Consonants: 9
Digits: 0
Spaces: 1
12. Test whether a string is a palindrome (ignore case).
C Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[100];
int i, j, isPalindrome = 1;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = 0; // remove newline
int len = strlen(str);
for (i = 0, j = len - 1; i < j; i++, j--) {
while (!isalnum(str[i]) && i < j) i++;
while (!isalnum(str[j]) && i < j) j--;
if (tolower(str[i]) != tolower(str[j])) {
isPalindrome = 0;
break;
}
}
if (isPalindrome)
printf("The string is a palindrome.\n");
else
printf("The string is not a palindrome.\n");
return 0;
}
Output:
Enter a string: Amma
The string is a palindrome.
Python Code:
s = input("Enter a string: ")
# Normalize: remove non-alphanumeric and convert to lowercase
normalized = ''.join([Link]() for ch in s if [Link]())
if normalized == normalized[::-1]:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Output:
Enter a string: Amma
The string is a palindrome.
13. Implement your own strcmp without using <string.h>.
C Code:
#include <stdio.h>
int my_strcmp(const char *s1, const char *s2) {
while (*s1 && (*s1 == *s2)) {
s1++;
s2++;
}
return *(unsigned char *)s1 - *(unsigned char *)s2;
}
int main() {
char str1[100], str2[100];
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);
int result = my_strcmp(str1, str2);
if (result == 0)
printf("Strings are equal.\n");
else if (result < 0)
printf("First string is less than second.\n");
else
printf("First string is greater than second.\n");
return 0;
}
Output:
Enter first string: Upendra
Enter second string: Upendr
First string is greater than second.
Python Code:
def my_strcmp(s1, s2):
min_len = min(len(s1), len(s2))
for i in range(min_len):
if s1[i] != s2[i]:
return ord(s1[i]) - ord(s2[i])
return len(s1) - len(s2)
s1 = input("Enter first string: ")
s2 = input("Enter second string: ")
result = my_strcmp(s1, s2)
if result == 0:
print("Strings are equal.")
elif result < 0:
print("First string is less than second.")
else:
print("First string is greater than second.")
Output:
Enter first string: Upendra
Enter second string: Upendr
First string is greater than second.
14. Convert a string to Title Case (capitalize every word).
C Code:
#include <stdio.h>
#include <ctype.h>
int main() {
char str[200];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
int i = 0;
int capitalize = 1;
while (str[i]) {
if (isspace(str[i])) {
capitalize = 1;
} else if (capitalize && isalpha(str[i])) {
str[i] = toupper(str[i]);
capitalize = 0;
} else {
str[i] = tolower(str[i]);
}
i++;
}
printf("Title Case: %s", str);
return 0;
}
Output:
Enter a string: mallareddy engineering college for women
Title Case: Mallareddy Engineering College For Women
Python Code:
s = input("Enter a string: ")
title_case = ' '.join([Link]() for word in [Link]())
print("Title Case:", title_case)
Output:
Enter a string: mallareddy engineering college for women
Title Case: Mallareddy Engineering College For Women
15. Find the longest word in a sentence.
C Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[200], word[50], longest[50];
int i = 0, j = 0, maxLen = 0;
printf("Enter a sentence: ");
fgets(str, sizeof(str), stdin);
while (1) {
if (str[i] != ' ' && str[i] != '\n' && str[i] != '\0') {
word[j++] = str[i];
} else {
word[j] = '\0';
if (j > maxLen) {
maxLen = j;
strcpy(longest, word);
}
j = 0;
if (str[i] == '\0')
break;
}
i++;
}
printf("Longest word: %s\n", longest);
return 0;
}
Output:
Enter a sentence: Perseverance Is The Ket To Success
Longest word: Perseverance
Python Code:
sentence = input("Enter a sentence: ")
words = [Link]()
longest = max(words, key=len)
print("Longest word:", longest)
Output:
Enter a sentence: Perseverance Is The Ket To Success
Longest word: Perseverance
16. Sort an array of strings alphabetically.
C Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[10][50], temp[50];
int n;
printf("Enter number of strings: ");
scanf("%d", &n);
getchar(); // consume newline
printf("Enter strings:\n");
for (int i = 0; i < n; i++) {
fgets(str[i], sizeof(str[i]), stdin);
str[i][strcspn(str[i], "\n")] = 0; // remove newline
}
// Bubble sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (strcmp(str[j], str[j + 1]) > 0) {
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
}
printf("Sorted strings:\n");
for (int i = 0; i < n; i++)
printf("%s\n", str[i]);
return 0;
}
Output:
Enter number of strings: 3
Enter strings:
Mallreddy
Engineering College
for women
Sorted strings:
Engineering College
Mallreddy
for women
Python Code:
n = int(input("Enter number of strings: "))
strings = [input("Enter string: ") for _ in range(n)]
[Link]()
print("Sorted strings:")
for s in strings:
print(s)
Output:
Enter number of strings: 3
Enter strings:
Mallreddy
Engineering College
for women
Sorted strings:
Engineering College
Mallreddy
for women
17. Count frequency of each integer in an array.
C Code:
#include <stdio.h>
int main() {
int arr[100], freq[100], n, i, j, count;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
freq[i] = -1;
}
for (i = 0; i < n; i++) {
if (freq[i] == -1) {
count = 1;
for (j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
freq[j] = 0;
}
}
freq[i] = count;
}
}
printf("Element - Frequency\n");
for (i = 0; i < n; i++) {
if (freq[i] != 0)
printf("%d - %d\n", arr[i], freq[i]);
}
return 0;
}
Output:
Enter number of elements: 5
Enter array elements:
1
2
3
1
2
Element - Frequency
1-2
2-2
3-1
Python Code:
arr = list(map(int, input("Enter array elements: ").split()))
freq = {}
for num in arr:
freq[num] = [Link](num, 0) + 1
print("Element - Frequency")
for key, value in [Link]():
print(f"{key} - {value}")
Output:
Enter number of elements: 5
Enter array elements:
1
2
3
1
2
Element - Frequency
1-2
2-2
3-1
18. Add two 2x2 matrices stored in 2-D arrays.
C Code:
#include <stdio.h>
int main() {
int a[2][2], b[2][2], sum[2][2];
printf("Enter elements of first 2x2 matrix:\n");
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
scanf("%d", &a[i][j]);
printf("Enter elements of second 2x2 matrix:\n");
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
scanf("%d", &b[i][j]);
// Add matrices
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
sum[i][j] = a[i][j] + b[i][j];
printf("Sum of matrices:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
printf("%d ", sum[i][j]);
printf("\n");
}
return 0;
}
Output:
Enter elements of first 2x2 matrix:
2
4
3
5
Enter elements of second 2x2 matrix:
1
4
2
3
Sum of matrices:
38
58
Python Code:
print("Enter elements for first 2x2 matrix:")
a = [[int(input(f"a[{i}][{j}]: ")) for j in range(2)] for i in range(2)]
print("Enter elements for second 2x2 matrix:")
b = [[int(input(f"b[{i}][{j}]: ")) for j in range(2)] for i in range(2)]
# Add matrices
sum_matrix = [[a[i][j] + b[i][j] for j in range(2)] for i in range(2)]
print("Sum of matrices:")
for row in sum_matrix:
print(*row)
Output:
Enter elements of first 2x2 matrix:
2
4
3
5
Enter elements of second 2x2 matrix:
1
4
2
3
Sum of matrices:
38
58
18. Store student (name, marks) in a struct array; list those above 75%.
C Code:
#include <stdio.h>
#include <string.h>
struct Student {
char name[50];
float marks;
};
int main() {
struct Student students[100];
int n;
printf("Enter number of students: ");
scanf("%d", &n);
getchar(); // Consume newline
for (int i = 0; i < n; i++) {
printf("Enter name of student %d: ", i + 1);
fgets(students[i].name, sizeof(students[i].name), stdin);
students[i].name[strcspn(students[i].name, "\n")] = 0; // Remove newline
printf("Enter marks of %s: ", students[i].name);
scanf("%f", &students[i].marks);
getchar(); // Consume newline
}
printf("\nStudents with marks > 75%%:\n");
for (int i = 0; i < n; i++) {
if (students[i].marks > 75) {
printf("%s - %.2f%%\n", students[i].name, students[i].marks);
}
}
return 0;
}
Output:
Enter number of students: 3
Enter name of student 1: Chandana
Enter marks of Chandana: 90
Enter name of student 2: Laxmi Prasanna
Enter marks of Laxmi Prasanna: 73
Enter name of student 3: Akshitha
Enter marks of Akshitha : 65
Students with marks > 75%:
Chandana - 90.00%
Python Code:
n = int(input("Enter number of students: "))
students = []
for _ in range(n):
name = input("Enter name: ")
marks = float(input(f"Enter marks for {name}: "))
[Link]({'name': name, 'marks': marks})
print("\nStudents with marks > 75%:")
for s in students:
if s['marks'] > 75:
print(f"{s['name']} - {s['marks']}%")
Output:
Enter number of students: 3
Enter name of student 1: Chandana
Enter marks of Chandana: 90
Enter name of student 2: Laxmi Prasanna
Enter marks of Laxmi Prasanna: 73
Enter name of student 3: Akshitha
Enter marks of Akshitha : 65
Students with marks > 75%:
Chandana - 90.00%
20. Demonstrate pointer arithmetic by printing addresses & values of an int
array.
C Code:
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
printf("Pointer Arithmetic Demonstration:\n");
for (int i = 0; i < 5; i++) {
printf("Address: %p, Value: %d\n", (ptr + i), *(ptr + i));
}
return 0;
}
Output:
Pointer Arithmetic Demonstration:
Address: 00000037E41FFC10, Value: 10
Address: 00000037E41FFC14, Value: 20
Address: 00000037E41FFC18, Value: 30
Address: 00000037E41FFC1C, Value: 40
Address: 00000037E41FFC20, Value: 50
Python Code:
arr = [10, 20, 30, 40, 50]
print("Pointer Arithmetic Demonstration (simulated in Python):")
for i in range(len(arr)):
print(f"Index: {i}, Address (id): {id(arr[i])}, Value: {arr[i]}")
Output:
Pointer Arithmetic Demonstration (simulated in Python):
Index: 0, Address (id): 140727904185048, Value: 10
Index: 1, Address (id): 140727904185368, Value: 20
Index: 2, Address (id): 140727904185688, Value: 30
Index: 3, Address (id): 140727904186008, Value: 40
Index: 4, Address (id): 140727904186328, Value: 50