Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Solutions to Tutorial Questions for Arrays, Functions and Files-1

The document provides solutions to various tutorial questions related to arrays, functions, and file handling in C programming. It includes code examples for checking prime numbers, rearranging arrays, checking value ranges, calculating sums and averages, reversing arrays, finding duplicates, matrix operations, temperature conversions, leap year checks, storing and displaying student records, and file copying. Each solution is accompanied by explanations and structured code snippets.

Uploaded by

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

Solutions to Tutorial Questions for Arrays, Functions and Files-1

The document provides solutions to various tutorial questions related to arrays, functions, and file handling in C programming. It includes code examples for checking prime numbers, rearranging arrays, checking value ranges, calculating sums and averages, reversing arrays, finding duplicates, matrix operations, temperature conversions, leap year checks, storing and displaying student records, and file copying. Each solution is accompanied by explanations and structured code snippets.

Uploaded by

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

SOLUTIONS TO TUTORIAL QUESTIONS FOR ARRAYS, FUNCTIONS, AND

FILES

1. Write a C function isprime(num) that takes an integer as an argument and returns 1 if


the number is prime, or 0 otherwise. write a C program that invokes this function to
generate prime numbers between the given ranges.

#include <stdio.h>
// Function to check if a number is prime
int isprime(int num) {
if (num <= 1){
return 0; // Numbers less than 2 are not prime
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0){
return 0; // Not prime
}
}
return 1; // Prime
}
int main() {
int start, end, i;
// Input range from the user
printf("Enter the start of the range: ");
scanf("%d", &start);
printf("Enter the end of the range: ");
scanf("%d", &end);
printf("Prime numbers between %d and %d are:\n", start, end);
for (i = start; i <= end; i++) {
if (isprime(i)) {
printf("%d ", i);
}
}
printf("\n");
return 0; }

1 out of 11 | P a g e Prepared by: mwanamapambano & allysalumu


2. Write a program that arrange the positive and negative numbers in one-dimensional
array so that all positive numbers come first and then all negative numbers come without
changing the the original sequence of the numbers.

#include <stdio.h>
// Function to rearrange the array
void rearrange(int arr[], int n) {
int temp[n], index = 0, i;
// Collect all positive numbers
for (i = 0; i < n; i++) {
if (arr[i] >= 0) {
temp[index++] = arr[i];
}
}
// Collect all negative numbers
for (i = 0; i < n; i++) {
if (arr[i] < 0) {
temp[index++] = arr[i];
}
}
// Copy back to the original array
for (i = 0; i < n; i++) {
arr[i] = temp[i];
}
}
int main() {
int n;

// Input array size


printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n], i;
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

2 out of 11 | P a g e Prepared by: mwanamapambano & allysalumu


rearrange(arr, n);
printf("Rearranged array:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

3. write a function check(x, y, n) that returns 1 if both x and y follow between 0 and n-1,
inclusive. The function should return 0 otherwise assume that x, y, and n are all of type
integers. Write a main program to test this function.

#include <stdio.h>
// Function to check if x and y are within the range [0, n-1]
int check(int x, int y, int n) {
if(x >= 0 && x < n && y >= 0 && y < ){
return 1;
}
else{
return 0;
}
}
int main() {
int x, y, n;
// Input values from the user
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Enter the values of x and y: ");
scanf("%d %d", &x, &y);
// Test the function and display the result
if (check(x, y, n)) {
printf("Both x and y are within the range [0, %d-1].\n", n);
} else {
printf("x or y is out of the range [0, %d-1].\n", n); } return 0; }

3 out of 11 | P a g e Prepared by: mwanamapambano & allysalumu


4. Write a program that accept n integers into a one-dimensional array, calculate the sum
and average of the array elements, and displays the results.

#include <stdio.h>
int main() {
int n, i;
// Input array size
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n], sum = 0;
float average;
// Input array elements
printf("Enter the elements of the array:\n");
for ( i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum += arr[i]; // Calculate the sum
}
// Calculate average
average = (float)sum / n;
// Display results
printf("Sum: %d\n", sum);
printf("Average: %.2f\n", average);

return 0;
}
5. write a program to reverse the elements of a one-dimensional array without using
another array.
#include <stdio.h>
int main() {
int n, i;
// Input array size
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
// Input array elements
printf("Enter the elements of the array:\n");
for ( i = 0; i < n; i++) {

4 out of 11 | P a g e Prepared by: mwanamapambano & allysalumu


scanf("%d", &arr[i]);
}
// Reverse the array in place
for ( i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}
// Display the reversed array
printf("Reversed array:\n");
for ( i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;}
6. Write a program to find all duplicate elements in a one-dimensional array and print
them.

#include <stdio.h>
int main() {
int n, i, j;
// Input array size
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
// Input array elements
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Find and display duplicate elements
printf("Duplicate elements are:\n");
for ( i = 0; i < n; i++) {
for ( j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
5 out of 11 | P a g e Prepared by: mwanamapambano & allysalumu
printf("%d\n", arr[i]);
break;
}
}
}

return 0;
}
7. write a program to add two 2x2 matrices and display the resultant matrix.

#include <stdio.h>
int main() {
int mat1[2][2], mat2[2][2], result[2][2], i, j;
// Input first matrix
printf("Enter elements of the first 2x2 matrix:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &mat1[i][j]);
}
}

// Input second matrix


printf("Enter elements of the second 2x2 matrix:\n");
for ( i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &mat2[i][j]);
}
}
// Add the matrices
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
// Display the result
printf("Resultant matrix after addition:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

6 out of 11 | P a g e Prepared by: mwanamapambano & allysalumu


8. Write a program to subtract one 2x2 matrix from another and display the resultant
matrix.

#include <stdio.h>
int main() {
int mat1[2][2], mat2[2][2], result[2][2], i, j;
// Input first matrix
printf("Enter elements of the first 2x2 matrix:\n");
for ( i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &mat1[i][j]);
}
}
// Input second matrix
printf("Enter elements of the second 2x2 matrix:\n");
for ( i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &mat2[i][j]);
}
}
// Subtract the matrices
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
result[i][j] = mat1[i][j] - mat2[i][j];
}
}
// Display the result
printf("Resultant matrix after subtraction:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}

7 out of 11 | P a g e Prepared by: mwanamapambano & allysalumu


9. Write the functions: one to convert Fahrenheit to Celsius and another for convert
Celsius to Fahrenheit. Test both functions in a program.

#include <stdio.h>
// Function to convert Fahrenheit to Celsius
float fahrenheitToCelsius(float fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
// Function to convert Celsius to Fahrenheit
float celsiusToFahrenheit(float celsius) {
return (celsius * 9 / 5) + 32;
}
int main() {
float temp;
// Test Fahrenheit to Celsius
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &temp);
printf("Temperature in Celsius: %.2f\n", fahrenheitToCelsius(temp));
// Test Celsius to Fahrenheit
printf("Enter temperature in Celsius: ");
scanf("%f", &temp);
printf("Temperature in Fahrenheit: %.2f\n", celsiusToFahrenheit(temp));
return 0;
}
10. Write a function isLeapYear(int year) that checks whether a given year is a leap year.
Use it to display all leap years in a given range.

#include <stdio.h>
// Function to check if a year is a leap year
int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return 1;
}
return 0;
}

int main() {
int start, end, i;
// Input range from the user
printf("Enter the start year: ");
scanf("%d", &start);
printf("Enter the end year: ");
scanf("%d", &end);

8 out of 11 | P a g e Prepared by: mwanamapambano & allysalumu


printf("Leap years between %d and %d are:\n", start, end);
for (i = start; i<= end; i++) {
if (isLeapYear(i)) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
11. write a program to store student records (name, ID, and marks) in a file. Then, read
data and display it in a formatted way.
#include <stdio.h>

struct Student {

char name[50];

int id;

float marks;

};

int main() {

FILE *file;

struct Student s;

int n, i;

//prompt a user to enter the number of student to store data

printf("Enter number of students to store their data: ");

scanf("%d", &n);

// Open file to write student records

file = fopen("students.txt", "w");

if (file == NULL) {

printf("Error opening file for writing");

// Input and write records

for (i = 0; i < n; i++) {

printf("Enter name, ID, and marks for student %d:\n", i + 1);


9 out of 11 | P a g e Prepared by: mwanamapambano & allysalumu
scanf("%s %d %f", s.name, &s.id, &s.marks);

fprintf(file, "%s %d %.2f\n", s.name, s.id, s.marks);

fclose(file);

// Open file to read and display records

file = fopen("students.txt", "r");

if (file == NULL) {

printf("Error opening file for reading or no such file");

printf("\nStudent Records:\n");

while (fscanf(file, "%s %d %f", s.name, &s.id, &s.marks) != EOF) {

printf("Name: %s, ID: %d, Marks: %.2f\n", s.name, s.id, s.marks);

fclose(file);

return 0;}

12. Write a program to read the content of a text file and copy it into another file.

#include <stdio.h>
int main() {
FILE *source, *destination;
char ch;
// Open source file for reading
source = fopen("source.txt", "r");
if (source == NULL) {
printf("Error opening source file or no such file\n");
}
// Open destination file for writing
destination = fopen("destination.txt", "w");
if (destination == NULL) {
10 out of 11 | P a g e Prepared by: mwanamapambano & allysalumu
printf("Error opening destination file or no such file");
fclose(source);
}
// Copy contents from source to destination
while ((ch = fgetc(source)) != EOF) {
fputc(ch, destination);
}
printf("File copied successfully.\n");
fclose(source);
fclose(destination);
return 0;}

NOTE: you are free to edit or change any code as more as you can in order to meet your
needs

THANK YOU FOR READING.

11 out of 11 | P a g e Prepared by: mwanamapambano & allysalumu

You might also like