Q1.a) Write a C function to count the number of prime numbers between n1 and n2.
----------------------------------------------------------------------------------
#include <stdio.h>
int is_prime(int num) {
if (num <= 1) return 0;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return 0;
}
return 1;
}
int prime_count(int n1, int n2) {
int count = 0;
for (int i = n1; i <= n2; i++) {
if (is_prime(i)) count++;
}
return count;
}
int main() {
int n1 = 10, n2 = 50;
printf("Number of prime numbers = %d", prime_count(n1, n2));
return 0;
}
Q1.b) Difference between break and continue:
---------------------------------------------
- break: Exits the loop entirely.
- continue: Skips the current iteration and continues with the next one.
Example:
for (int i = 0; i < 5; i++) {
if (i == 2) break; // exits loop at i==2
}
for (int i = 0; i < 5; i++) {
if (i == 2) continue; // skips iteration at i==2
}
Q2) Bubble sort in descending order:
-------------------------------------
#include <stdio.h>
void bubble_sort(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;
}
}
}
}
int main() {
int arr[] = {23,56,12,78,98,8,34,72,44,69};
int n = sizeof(arr)/sizeof(arr[0]);
bubble_sort(arr, n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Q3) Dynamic memory allocation:
------------------------------
- Dynamic memory allocation allows allocating memory at runtime using malloc, calloc,
realloc, and freeing it using free().
- It is needed when memory requirements are not known in advance.
Example:
int *arr = (int*) malloc(5 * sizeof(int));
if (arr == NULL) {
printf("Memory not allocated.");
}
free(arr);
Q4.a) Structure point and distance:
-----------------------------------
#include <stdio.h>
#include <math.h>
struct Point {
int x, y;
};
int main() {
struct Point p1 = {2, 3}, p2 = {7, 8};
float dist = sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
printf("Distance = %.2f", dist);
return 0;
}
Q4.b) Difference between array and structure:
----------------------------------------------
- Array: Collection of elements of same data type.
- Structure: Collection of elements of different data types.
Q5.a) Fundamental file operations in C:
----------------------------------------
1. fopen() - Open a file
2. fclose() - Close the file
3. fprintf(), fscanf() - File I/O
4. fgetc(), fputc() - Character I/O
5. fread(), fwrite() - Binary I/O
Q5.b) Count characters and lines in a text file:
------------------------------------------------
#include <stdio.h>
int main() {
FILE *fp = fopen("file.txt", "r");
char ch;
int lines = 0, chars = 0;
if (fp == NULL) {
printf("File not found.");
return 1;
}
while ((ch = fgetc(fp)) != EOF) {
chars++;
if (ch == '\n') lines++;
}
fclose(fp);
printf("Lines: %d, Characters: %d", lines, chars);
return 0;
}