0% found this document useful (0 votes)
18 views

Code

The document contains C code examples for various programming tasks: 1) A program that inputs student ratings of cafeteria food on a scale of 1-10, calculates the total and average rating, and prints a summary. 2) A program that inputs a string and prints it in reverse order. 3) A program that inputs 10 strings representing floating-point values, converts them to doubles, sums the values, and prints the total. 4) A linear search function that searches an array for a key and returns the index if found. 5) A program that defines a struct for BMI, calculates BMI from input height and weight, and determines if the person is overweight. 6) A program that

Uploaded by

Hoàng Lâm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Code

The document contains C code examples for various programming tasks: 1) A program that inputs student ratings of cafeteria food on a scale of 1-10, calculates the total and average rating, and prints a summary. 2) A program that inputs a string and prints it in reverse order. 3) A program that inputs 10 strings representing floating-point values, converts them to doubles, sums the values, and prints the total. 4) A linear search function that searches an array for a key and returns the index if found. 5) A program that defines a struct for BMI, calculates BMI from input height and weight, and determines if the person is overweight. 6) A program that

Uploaded by

Hoàng Lâm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Code

1/ Forty students were asked to rate the quality of the food in the student cafeteria on a scale of 1 to 10 (1 means awful and 10 means excellent).

Place the 40 responses in an integer array and summarize the results of the poll.

#include <stdio.h>

int main() {

const int numStudents = 40;

int ratings[numStudents];

int total = 0;

double average;

// Input ratings

printf("Enter the ratings of the food (on a scale of 1 to 10) for 40 students:\n");

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

do {

printf("Student %d rating: ", i + 1);

scanf("%d", &ratings[i]);

// Validate the input rating is within the scale (1 to 10)

if (ratings[i] < 1 || ratings[i] > 10) {

printf("Invalid rating! Please enter a rating between 1 and 10.\n");

} while (ratings[i] < 1 || ratings[i] > 10);

// Update total

total += ratings[i];

// Calculate average

average = (double)total / numStudents;

// Display summary

printf("\nSummary of the Poll:\n");

printf("Total number of students: %d\n", numStudents);

printf("Average rating: %.2lf\n", average);

return 0;

2/Write a program to input a string and print it in reversed order of characters.

#include <stdio.h>

#include <string.h>

#define MAX_LENGTH 100

int main() {

char inputString[MAX_LENGTH];

// Input string
printf("Enter a string: ");

fgets(inputString, MAX_LENGTH, stdin);

// Remove newline character from the input

inputString[strcspn(inputString, "\n")] = '\0';

// Print the string in reversed order

printf("Reversed string: ");

for (int i = strlen(inputString) - 1; i >= 0; --i) {

printf("%c", inputString[i]);

printf("\n");

return 0;

3/Write a program that inputs 10 strings that represent floating-point values, converts the strings to double values, sums the values, and prints the
total. Using an array of strings.

#include <stdio.h>

#include <stdlib.h>

#define MAX_STR_LENGTH 100

int main() {

char inputStrings[10][MAX_STR_LENGTH];

double sum = 0.0;

// Input 10 strings

printf("Enter 10 strings representing floating-point values:\n");

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

printf("Enter string %d: ", i + 1);

scanf("%s", inputStrings[i]);

// Convert strings to double and sum the values

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

double value = atof(inputStrings[i]);

sum += value;

// Print the total

printf("Total: %.2lf\n", sum);

return 0;

4/Linear search algorithm finds a key (number) in an array of integers. It searches from the first element to the last element.

Write a linear-search function to receive an array, length of the array, and key as arguments. It returns the index of the first found element?

#include <stdio.h>
int linearSearch(const int array[], int length, int key) {

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

if (array[i] == key) {

return i; // Return the index if key is found

return -1; // Return -1 if key is not found in the array

int main() {

int array[] = {10, 5, 8, 12, 3, 7, 15, 20, 1, 25};

int length = sizeof(array) / sizeof(array[0]);

int key;

printf("Enter the key to search: ");

scanf("%d", &key);

int index = linearSearch(array, length, key);

if (index != -1) {

printf("Key %d found at index %d.\n", key, index);

} else {

printf("Key %d not found in the array.\n", key);

return 0;

5/Create a struct BMI including 2 variables: person’s height and weight in doubles of a student. Print the Body mass index (BMI) value (BMI =
weight/height2, unit is kg/m2) and determine if a person is overweight or not? (For most adults 18-65 years, a BMI of 25.0 or more is overweight,
while the healthy range is 18.5 to 24.9.)

#include <stdio.h>

// Define the BMI struct

struct BMI {

double height; // in meters

double weight; // in kilograms

};

// Function to calculate BMI

double calculateBMI(struct BMI person) {

return person.weight / (person.height * person.height);

// Function to determine if a person is overweight

int isOverweight(double bmi) {


return (bmi >= 25.0);

int main() {

// Create a BMI struct for a student

struct BMI student;

// Input height and weight

printf("Enter height (in meters): ");

scanf("%lf", &student.height);

printf("Enter weight (in kilograms): ");

scanf("%lf", &student.weight);

// Calculate BMI

double bmi = calculateBMI(student);

// Print BMI value

printf("BMI: %.2lf\n", bmi);

// Determine if the person is overweight

if (isOverweight(bmi)) {

printf("The person is overweight.\n");

} else {

printf("The person is not overweight.\n");

return 0;

6/Write a program that uses the sizeof operator to determine the sizes in bytes of the various data types on your computer system. Write the
results to the file "datasize.dat" so you may print the results later. The format for the results in the file should be as follows (the type sizes on your
computer might be different from those shown in the sample output):

#include <stdio.h>

int main() {

// Open the file for writing

FILE *file = fopen("datasize.dat", "w");

if (file == NULL) {

fprintf(stderr, "Error opening file for writing.\n");

return 1; // Return an error code

// Write data type sizes to the file

fprintf(file, "Size of char: %lu bytes\n", sizeof(char));

fprintf(file, "Size of short: %lu bytes\n", sizeof(short));

fprintf(file, "Size of int: %lu bytes\n", sizeof(int));

fprintf(file, "Size of long: %lu bytes\n", sizeof(long));

fprintf(file, "Size of float: %lu bytes\n", sizeof(float));


fprintf(file, "Size of double: %lu bytes\n", sizeof(double));

fprintf(file, "Size of long double: %lu bytes\n", sizeof(long double));

// Close the file

fclose(file);

printf("Data sizes written to datasize.dat.\n");

return 0;

7/Create a struct Rectangle including 2 variables: width and height in doubles. Print the area and perimeter of the rectangle?

#include <stdio.h>

// Define the Rectangle struct

struct Rectangle {

double width;

double height;

};

// Function to calculate the area of a rectangle

double calculateArea(struct Rectangle rectangle) {

return rectangle.width * rectangle.height;

// Function to calculate the perimeter of a rectangle

double calculatePerimeter(struct Rectangle rectangle) {

return 2 * (rectangle.width + rectangle.height);

int main() {

// Create a Rectangle struct

struct Rectangle myRectangle;

// Input width and height

printf("Enter the width of the rectangle: ");

scanf("%lf", &myRectangle.width);

printf("Enter the height of the rectangle: ");

scanf("%lf", &myRectangle.height);

// Calculate and print the area

double area = calculateArea(myRectangle);

printf("Area of the rectangle: %.2lf square units\n", area);

// Calculate and print the perimeter

double perimeter = calculatePerimeter(myRectangle);

printf("Perimeter of the rectangle: %.2lf units\n", perimeter);


return 0;

Structure

Min Max

#include <stdio.h>

#define MAX_SIZE 100

typedef struct MinMax {

int min;

int max;

}MinMax;

MinMax getMinMax(int *arr, int len);

int main()

int arr[MAX_SIZE] = {10, -1, 0, 4, 2, 100, 15, -20, 24, -5};

int len = 10;

MinMax arrayMinMax;

arrayMinMax = getMinMax(arr,

len);

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

printf("%d ", arr[i]);

printf("\nMin: %d\n", arrayMinMax.min);

printf("Max: %d\n", arrayMinMax.max);

return 0;

MinMax getMinMax(int *arr, int len) {

int min = *arr;

int max = *arr;

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

if (arr[i] > max) {

max = arr[i];

else if (arr[i] < min) {

min = arr[i];

MinMax arrayMinMax;

arrayMinMax.min = min;
arrayMinMax.max = max;

return arrayMinMax;

1/Write a program that reads three nonzero integer values and determines and prints whether they could represent the sides of a triangle.

#include <stdio.h>

int main() {

int side1, side2, side3;

// Input three nonzero integer values

printf("Enter the first side: ");

scanf("%d", &side1);

printf("Enter the second side: ");

scanf("%d", &side2);

printf("Enter the third side: ");

scanf("%d", &side3);

// Check if the sides form a triangle

if (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1) {

printf("The given sides can form a triangle.\n");

} else {

printf("The given sides cannot form a triangle.\n");

return 0;

Function

1/Write a function that returns the largest of four floating-point numbers.

#include <stdio.h>

// Function to find the largest of four floating-point numbers

float findLargest(float a, float b, float c, float d) {

float max = a;

if (b > max) {

max = b;

if (c > max) {

max = c;

if (d > max) {

max = d;
}

return max;

int main() {

float num1, num2, num3, num4;

// Input four floating-point numbers

printf("Enter the first number: ");

scanf("%f", &num1);

printf("Enter the second number: ");

scanf("%f", &num2);

printf("Enter the third number: ");

scanf("%f", &num3);

printf("Enter the fourth number: ");

scanf("%f", &num4);

// Call the function to find the largest number

float largest = findLargest(num1, num2, num3, num4);

// Print the result

printf("The largest number is: %.2f\n", largest);

return 0;

2/Write a function that takes an integer and returns the sum of its digits

#include <stdio.h>

// Function to calculate the sum of digits of an integer

int sumOfDigits(int num) {

int sum = 0;

// Take the absolute value to handle negative numbers

num = (num < 0) ? -num : num;

// Calculate the sum of digits

while (num > 0) {

sum += num % 10; // Add the last digit to the sum

num /= 10; // Remove the last digit

return sum;

int main() {

int number;

// Input an integer
printf("Enter an integer: ");

scanf("%d", &number);

// Call the function to find the sum of digits

int digitSum = sumOfDigits(number);

// Print the result

printf("Sum of digits: %d\n", digitSum);

return 0;

Array

1/ Sort in array

int input_array[SIZE];

int input_size;

printf("Enter array size: ");

scanf("%d", &input_size);

for (int i = 0; i <

input_size; i++) {

printf("Enter

number: ");

int num;

scanf("%d", &num);

input_array[i] = num;

int even_array[SIZE];

int even_size = 0;

int even_list[SIZE];

int odd_array[SIZE];

int odd_size = 0;

int odd_list[SIZE];

int even_count = 0;

int odd_count = 0;

for (int i = 0; i <

input_size; i++) {

if (input_array[i] % 2

== 0) {

even_array[even_size] =

input_array[i];

even_size++;
even_list[even_count] = i;

even_count++;

else {

odd_array[odd_size] =

input_array[i];

odd_size++;

odd_list[odd_count] = i;

odd_count++;

insertion_sort(even_array, even_size, true);

insertion_sort(odd_array, odd_size, false);

for (int i = 0; i < even_size;

i++){

input_array[even_list[i]] =

even_array[i];

for (int i = 0; i < odd_size;

i++){

input_array[odd_list[i]] = odd_array[i];

printf("result = ");

for (int i = 0; i <

input_size; i++) {

printf("%d ",

input_array[i]);

printf("");

2/An two-dimensional matrix can be multiplied by another matrix to give a matrix whose elements are the sum of the products of the elements
within a row from the first matrix and the associated elements of a column of the second matrix. Both matrices should either be square matrices,
or the number of columns of the first matrix should equal the number of rows of the second matrix. To calculate each element of the resultant
matrix, multiply the first element of a given row from the first matrix and the first element of a given column in the second matrix, add that to the
product of the second element of the same row and the second element of the same column, and keep doing so until the last elements of the row
and column have been multiplied and added to the sum. Write a program to calculate the product of 2 matrices and store the result in a third
matrix.

#include <stdio.h>

#define MAX_SIZE 10

// Function to multiply two matrices and store the result in a third matrix

void multiplyMatrices(int mat1[MAX_SIZE][MAX_SIZE], int mat2[MAX_SIZE][MAX_SIZE], int result[MAX_SIZE][MAX_SIZE], int


rows1, int cols1, int rows2, int cols2) {
if (cols1 != rows2) {

printf("Error: Number of columns in the first matrix must be equal to the number of rows in the second matrix for multiplication.\n");

return;

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

for (int j = 0; j < cols2; ++j) {

result[i][j] = 0;

for (int k = 0; k < cols1; ++k) {

result[i][j] += mat1[i][k] * mat2[k][j];

// Function to display a matrix

void displayMatrix(int mat[MAX_SIZE][MAX_SIZE], int rows, int cols) {

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

for (int j = 0; j < cols; ++j) {

printf("%d\t", mat[i][j]);

printf("\n");

int main() {

int mat1[MAX_SIZE][MAX_SIZE], mat2[MAX_SIZE][MAX_SIZE], result[MAX_SIZE][MAX_SIZE];

int rows1, cols1, rows2, cols2;

// Input dimensions of the first matrix

printf("Enter the dimensions of the first matrix (rows columns): ");

scanf("%d %d", &rows1, &cols1);

// Input elements of the first matrix

printf("Enter the elements of the first matrix:\n");

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

for (int j = 0; j < cols1; ++j) {

printf("Enter element at position (%d, %d): ", i + 1, j + 1);

scanf("%d", &mat1[i][j]);

// Input dimensions of the second matrix


printf("Enter the dimensions of the second matrix (rows columns): ");

scanf("%d %d", &rows2, &cols2);

// Input elements of the second matrix

printf("Enter the elements of the second matrix:\n");

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

for (int j = 0; j < cols2; ++j) {

printf("Enter element at position (%d, %d): ", i + 1, j + 1);

scanf("%d", &mat2[i][j]);

// Check if the matrices can be multiplied

if (cols1 != rows2) {

printf("Error: Number of columns in the first matrix must be equal to the number of rows in the second matrix for multiplication.\n");

return 1; // Return an error code

// Multiply the matrices

multiplyMatrices(mat1, mat2, result, rows1, cols1, rows2, cols2);

// Display the matrices and their product

printf("\nMatrix 1:\n");

displayMatrix(mat1, rows1, cols1);

printf("\nMatrix 2:\n");

displayMatrix(mat2, rows2, cols2);

printf("\nProduct Matrix:\n");

displayMatrix(result, rows1, cols2);

return 0;

Pointer

Write a function mazeGenerator that takes as an argument a two-dimensional 12-by-12 character array and randomly produces a maze. The
function should also provide the starting and ending locations of the maze.

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#define SIZE 12

// Function to generate a random maze

void mazeGenerator(char maze[SIZE][SIZE], int *startX, int *startY, int *endX, int *endY) {

// Initialize the maze with walls

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


for (int j = 0; j < SIZE; ++j) {

maze[i][j] = '#';

// Set random seed based on current time

srand(time(NULL));

// Randomly select starting and ending locations

*startX = rand() % SIZE;

*startY = rand() % SIZE;

*endX = rand() % SIZE;

*endY = rand() % SIZE;

// Set starting and ending locations in the maze

maze[*startX][*startY] = 'S'; // 'S' represents the starting point

maze[*endX][*endY] = 'E'; // 'E' represents the ending point

// Create random paths in the maze

for (int i = 0; i < SIZE * SIZE / 2; ++i) {

int randomX = rand() % SIZE;

int randomY = rand() % SIZE;

maze[randomX][randomY] = ' ';

// Function to display the maze

void displayMaze(char maze[SIZE][SIZE]) {

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

for (int j = 0; j < SIZE; ++j) {

printf("%c ", maze[i][j]);

printf("\n");

int main() {

char maze[SIZE][SIZE];

int startX, startY, endX, endY;

// Generate the maze

mazeGenerator(maze, &startX, &startY, &endX, &endY);

// Display the maze

printf("Maze:\n");

displayMaze(maze);
// Display the starting and ending locations

printf("\nStarting location: (%d, %d)\n", startX, startY);

printf("Ending location: (%d, %d)\n", endX, endY);

return 0;

Strings and Characters

1/ Write a program that inputs six strings that represent floating-point values, converts the strings to double values, stores the values into a double
array and calculates the sum, and average of the values.

#include <stdio.h>

#include <stdlib.h>

#define ARRAY_SIZE 6

int main() {

char inputStrings[ARRAY_SIZE][100];

double values[ARRAY_SIZE];

double sum = 0.0;

// Input six strings representing floating-point values

printf("Enter six strings representing floating-point values:\n");

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

printf("Enter string %d: ", i + 1);

scanf("%s", inputStrings[i]);

// Convert string to double and store in the array

values[i] = atof(inputStrings[i]);

// Update sum

sum += values[i];

// Calculate average

double average = sum / ARRAY_SIZE;

// Display the entered values

printf("\nEntered values:\n");

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

printf("%lf\n", values[i]);

// Display the sum and average

printf("\nSum of the values: %lf\n", sum);

printf("Average of the values: %lf\n", average);

return 0;

2/Write a program that inputs a line of text and counts the total numbers of vowels, consonants, digits and white spaces in the given line of text
#include <stdio.h>

#include <ctype.h>

int main() {

char line[100];

int vowels = 0, consonants = 0, digits = 0, spaces = 0;

// Input a line of text

printf("Enter a line of text: ");

fgets(line, sizeof(line), stdin);

// Iterate through each character in the line

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

char currentChar = line[i];

// Check if the current character is a vowel

if (tolower(currentChar) == 'a' || tolower(currentChar) == 'e' || tolower(currentChar) == 'i' ||

tolower(currentChar) == 'o' || tolower(currentChar) == 'u') {

vowels++;

// Check if the current character is a consonant

else if ((currentChar >= 'a' && currentChar <= 'z') || (currentChar >= 'A' && currentChar <= 'Z')) {

consonants++;

// Check if the current character is a digit

else if (isdigit(currentChar)) {

digits++;

// Check if the current character is a white space

else if (isspace(currentChar)) {

spaces++;

// Display the results

printf("\nResults:\n");

printf("Vowels: %d\n", vowels);

printf("Consonants: %d\n", consonants);


printf("Digits: %d\n", digits);

printf("White Spaces: %d\n", spaces);

return 0;

File processing

#include <stdio.h>

int main() {

FILE *file = fopen("datasize.dat", "w");

if (file == NULL) {

fprintf(stderr, "Error opening file for writing.\n");

return 1; // Return an error code

// Write data type sizes to the file

fprintf(file, "Size of char: %lu bytes\n", sizeof(char));

fprintf(file, "Size of short: %lu bytes\n", sizeof(short));

fprintf(file, "Size of int: %lu bytes\n", sizeof(int));

fprintf(file, "Size of long: %lu bytes\n", sizeof(long));

fprintf(file, "Size of float: %lu bytes\n", sizeof(float));

fprintf(file, "Size of double: %lu bytes\n", sizeof(double));

fprintf(file, "Size of long double: %lu bytes\n", sizeof(long double));

// Close the file

fclose(file)

printf("Data sizes written to datasize.dat.\n");

return 0;

You might also like