C Programming Test Answer Key
C Programming Test Answer Key
Example Code:
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output: 1 2 3 4 5
Steps:
Compare the first two elements.
Swap them if the first is larger than the second.
Move to the next element and repeat until the end of the array.
Repeat the entire process until no swaps are needed.
Example Code:
#include <stdio.h>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
3. Write counting from 1-20 using while, do-while, and for loop (10
marks)
To count from 1 to 20, the while, do-while, and for loops can be used.
While Loop:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 20) {
printf("%d ", i);
i++;
}
return 0;
}
Do-While Loop:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 20);
return 0;
}
For Loop:
#include <stdio.h>
int main() {
for (int i = 1; i <= 20; i++) {
printf("%d ", i);
}
return 0;
}
4. What is a pointer? Write the syntax of malloc() (5 marks)
Syntax of malloc():
ptr = (castType*) malloc(size_in_bytes);
Example:
int* ptr = (int*) malloc(5 * sizeof(int));
5. Get the sum of these two numbers (15 and 10) using a function (5
marks)
In this task, we create a function that takes two integers as input and
returns their sum.
Example Code:
#include <stdio.h>
int getSum(int a, int b) {
return a + b;
}
int main() {
int a = 15, b = 10;
int sum = getSum(a, b);
printf("Sum: %d", sum);
return 0;
}
int main() {
char str[100], rev[100];
int len, i, j;
len = strlen(str);