code
code
1. Write a program that allow users to enter a statement, then print that statement on the
screen in such a way that each line contains only one word.
#include <stdio.h>
#include <string.h>
int main() {
char string[100];
return 0;
}
2. Write a function to sort the names in a given list in ascending order and demonstrate the
usage
#include <stdio.h>
#include <string.h>
char name[n][50];
for (int a=0;a<n;a++) {
scanf ("%s",&name[a]);
}
sort_name (name,n);
printf("\n");
return 0;
}
3. Write a function to obtain a string entered via keyboard in the reverse order as per word, e.g.
“How Are You” change to “You Are How”. Write a program to demonstrate the usage.
#include <stdio.h>
#include <string.h>
int main() {
char string[1000];
rev(string);
}
4. Write a program to enter a sentence(or paragraph) and a word (or a string), then replace
the word (string) within the sentence (paragraph) with the equal number of "*" at all
occurring. Design and use appropriate functions to perform the task.
#include <stdio.h>
#include <string.h>
int main() {
char para[100],string[100];
replace (para,string);
}
5. Write a function that converts a string like “124” to an integer 124. Write a program to
demonstrate the usage.
#include <stdio.h>
#include <string.h>
#include <math.h>
printf ("\n%i",num);
}
int main() {
char str[1000];
int flag=0,num=0;
do {
for (int i=0;i<strlen(str);i++) {
if (str[i]<48 || str[i]>57) flag=1;
}
if (flag==1) {
flag=0;
printf ("\nPlease re-input with numbers only: ");
scanf("%s",str);
}
else break;
}
while (true);
convert (str,num);
}
6. Write a function to check whether string inputted by user is palindrome or not. Demonstrate
the usage.
#include <stdio.h>
#include <string.h>
int main () {
char str1[1000];
check_palindrome (str1);
}
7. Write a function to remove all the extra blanks in a string. Demonstrate the usage.
#include <stdio.h>
#include <string.h>
if (str[i]!=' ') {
new_str[j]=str[i];
j++;
}
new_str[j]='\0';
int main() {
char str[1000];
return 0;
}
8. Write a program to enter any string and print the frequency of each character within the
string. The character with multiple frequencies should be displayed only once in the output,
with the frequency value. Design and use appropriate functions to perform the task.
#include <stdio.h>
#include <string.h>
int len=strlen(str);
frequency(str);
}
9. Write a program to take a list of students in a programming class. The list should contain
the student id, student name and the final exam score. Write the student list to a csv file call
“ee3490E.csv” such that each line consists of student id, student name and the score. Each field
of information should be separated by a comma “,”; e.g.: 20200001, Adam Smith, 8.2. Design
and use appropriate functions and data types to perform the task.
#include <stdio.h>
#include <stdlib.h>
struct student {
int id;
char name[50];
float score;
};
fp = fopen("ee3490E.csv", "w");
fclose(fp);
}
int main() {
struct student students[MAX_STUDENTS];
int num_students;
printf("Enter the number of students in the class (up to %d): ",
MAX_STUDENTS);
scanf("%d", &num_students);
write_student_list_to_csv(students, num_students);
return 0;
}
10. Write a program to read a file which has the same format as described in problem 9.
Calculate the number of students who get A, B, C, D, and F. Design and use appropriate
functions and data types to perform the task.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int id;
char name[100];
float score;
} Student;
int main() {
FILE *fp;
char filename[100];
Student students[MAX_STUDENTS];
int num_students = 0;
int num_a = 0, num_b = 0, num_c = 0, num_d = 0, num_f = 0;
return 0;
}
11. Write a program in C to count the number of vowels and consonants in a string using a
pointer.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
char str[1000];
int numVowel=0,numConso=0;
char *strPtr=str;
int len=strlen(str);
numVowel=countVowel (strPtr,len);
numConso=countConsonant (strPtr,len);
return 0;
}
return count;
}
return count;
}
12. Write a program in C to find the frequency of all characters and/or a given character in a
sentence entered by users. Do not use standard libraries related to string. Use pointers where
possible.
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[1000];
char *strPtr=str;
int *outputPtr=NULL;
outputPtr=charFreq(strPtr);
int j=0;
for (j=0;j<128;j++) {
if (*(outputPtr+j) != 0) printf ("\nFrequency of character %c: %i",
(char) j, *(outputPtr+j));
}
free(outputPtr);
return 0;
}
j=0;
while (*(strPtr+j)!='\0') {
++*(chr + (int) *(strPtr+j));
j++;
}
return chr;
}
13. Write a program in C which allows users to provide a string then extract all the characters
in that string and print out them in alphabetic order. The function(s) designed should use a
pointer(s).
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
char str[1000];
while (str[0]=='\0') {
printf ("String null, please re-input string: ");
gets (str);
}
int i=0;
while (str[i]!='\0') {
str[i]=tolower(str[i]);
i++;
}
char *strPtr=str;
int *outputPtr=NULL;
outputPtr=charFreq(strPtr);
int j=0;
free(outputPtr);
return 0;
}
j=0;
while (*(strPtr+j)!='\0') {
++*(chr + (int) *(strPtr+j));
j++;
}
return chr;
}
14. Write a program in C which allows users to provide a string then extract all the characters
in that string and print out them in alphabetic order. The function(s) designed should use a
pointer(s).
#include <stdio.h>
#include <stdbool.h>
int main() {
double num=0;
return 0;
}
newNum= int(num);
for (int i=1;i<=newNum/2;i++) {
if ((newNum%i)==0) sum=sum+i;
}
15. Write a program in C to find the Deficient numbers (integers) between two integers using
pointer(s). A deficient number or defective number is a number n for which the sum of divisors
of n is less than 2n. E.g. the proper divisors of 8 are 1, 2, and 4, and their sum is less than 8, so
8 is deficient.
Student can try to solve this problem using dynamic memory allocation.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int main() {
double firstNum=0,secondNum=0;
int *resultArray=NULL;
resultArray=arrayOfDeficientNum(firstNum,secondNum);
return 0;
}
newNum= int(num);
newNum= int(num);
int k=0;
for (int j=0;j<((int) finalNum - firstNum + 1);j++) {
if (checkDeficient(*(iniArr+j))==0) continue;
else {
*(newArr+k)=*(iniArr+j);
k++;
}
}
return newArr;
}
16. Write a program in C to calculate the sum of numbers from 1 to n using recursion.
#include <stdio.h>
#include <stdbool.h>
int main() {
double num;
return 0;
}
if(n == 0) return 0;
else return n + sumOfNum(n-1);
}
17a. Write a program in C to count the digits of a given number using recursion.
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
int main() {
double num;
18. Write a program in C to find the first n number of prime numbers using recursion.
#include <stdio.h>
#include <stdbool.h>
int main() {
double num;
if(newNum == 0) return;
else {
if(isPrime(i, i-1)) {
printf("%d ", i);
printPrimes(newNum-1, i+1);
}
else printPrimes(newNum, i+1);
}
}
19. Write a C program to print the square of array elements using callback function. Student
can try to solve this problem using dynamic memory allocation.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
double numElement=0;
printSquaredArray(numElement);
return 0;
}
return ptrArr;
}
return;
}
20. Create a linked-list consisting of public holidays of a year and description of each day (as
string), so that:
- A new public holiday can be added to the beginning of the list -Search for the description of
the day (input argument is a date including day and month)
- Delete a public holiday at the beginning of the list
- Delete a public holiday in the middle of the list (input argument is a date including day and
month)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct holiday {
char date[11];
char description[50];
struct holiday *next;
};
void delete_first_holiday() {
if (head == NULL) {
printf("List is empty.\n");
return;
}
struct holiday *temp = head;
head = head->next;
free(temp);
}
void clear_holidays() {
struct holiday *temp = head;
while (temp != NULL) {
head = head->next;
free(temp);
temp = head;
}
}
void display_holidays() {
struct holiday *temp = head;
while (temp != NULL) {
printf("%s: %s\n", temp->date, temp->description);
temp = temp->next;
}
}
int main() {
FILE *fp = fopen("holidays.txt", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return 0;
}
char date[11], description[50];
while (fscanf(fp, "%s %[^\n]", date, description) != EOF) {
add_holiday(date, description);
}
fclose(fp);
int choice;
char date_input[11], description_input[50];
do {
printf("\n1. Add holiday\n2. Search holiday\n3. Delete first holiday\n4.
Delete holiday\n5. Clear holidays\n6. Display holidays\n7. Exit\nEnter your
choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter date (dd/mm/yyyy): ");
scanf("%s", date_input);
printf("Enter description: ");
scanf(" %[^\n]", description_input);
add_holiday(date_input, description_input);
printf("Holiday added.\n");
break;
case 2:
printf("Enter date to search (dd/mm/yyyy): ");
scanf("%s", date_input);
search_holiday(date_input);
break;
case 3:
delete_first_holiday();
printf("First holiday deleted.\n");
break;
case 4:
printf("Enter date to delete (dd/mm/yyyy): ");
scanf("%s", date_input);
delete_holiday(date_input);
break;
case 5:
clear_holidays();
printf("All holidays deleted.\n");
break;
case 6:
display_holidays();
break;
case 7:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice.\n");
}
} while (choice != 7);
fp = fopen("holidays.txt", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 0;
}
struct holiday *temp = head;
while (temp != NULL) {
fprintf(fp, "%s %s\n", temp->date, temp->description);
temp = temp->next;
}
fclose(fp);
return 0;
}
MINI PROJECT
TASK 1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
fprintf(fp, "id,time,value\n");
srand(time(NULL));
int id=1;
fclose(fp);
}
if (log_file != NULL) {
fprintf(log_file, "Error %02d: %s\n", error_code, description);
fclose(log_file);
} else {
printf("Error: could not open log file for writing\n");
}
}
}
num_sensors = atoi(argv[i+1]);
}else if (strcmp(argv[i], "-st") == 0) {
if (i+1 >= argc) {
log_error(1, "missing value for -st argument");
}
sampling_time = atoi(argv[i+1]);
}else if (strcmp(argv[i], "-si") == 0) {
if (i+1 >= argc) {
log_error(1, "missing value for -si argument");
}
measurement_duration = atoi(argv[i+1]);
} else {
log_error(1, "invalid command-line argument");
}
}
if (measurement_duration < 1) {
log_error(2, "invalid value for -si argument, must be a positive
integer greater than or equal to 1");
printf("Error: invalid value for -si argument, must be a positive
integer greater than or equal to 1\n");
}
if( (num_sensors <= 0) || (sampling_time < 1) || (measurement_duration < 1)
){
return 1;
}
//create file
FILE *fp = fopen("dust_sensor.csv", "w");
if (fp == NULL) {
log_error(3," dust_sensor.csv access denied");
return 1;
}
id,time,value
1,2023:07:07 00:00:00,84.3
2,2023:07:07 00:00:00,270.7
3,2023:07:07 00:00:00,522.0
1,2023:07:07 00:00:10,501.2
2,2023:07:07 00:00:10,60.2
3,2023:07:07 00:00:10,227.9
TASK 2.
dust_process.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//declare function
void log_error(int error_code,const char* description, int line_number);
int is_outlier(double value);
void decompose(const char *filename);
void check_wrong_intput(const char *filename);
void write_outliers(struct dust_sensor_data* data, int num_values);
//is_outlier function
int is_outlier(double concentration) {
return concentration < MIN_CONCENTRATION || concentration >
MAX_CONCENTRATION;
}
//decompse function
void decompose(const char *filename) {
FILE* input_file = fopen(filename, "r");
if (input_file == NULL) {
log_error(1, " input file not found or not accessible", 0);
printf("Error: could not open file '%s' for reading.\n", filename);
exit(1);
}
char line[MAX_LINE_LENGTH];
struct dust_sensor_data *data = NULL;
int num_values = 0;
// scan values
while (fgets(line, MAX_LINE_LENGTH, input_file) != NULL && num_values <
MAX_VALUES) {
char* token = strtok(line, ",");
if (token == NULL) {
continue;
}
data[num_values].id = atoi(token);
token = strtok(NULL, ",");
if (token == NULL) {
continue;
}
strncpy(data[num_values].timestamp, token, 20);
token = strtok(NULL, ",");
if (token == NULL) {
continue;
}
data[num_values].concentration = atof(token);
num_values++;
}
fclose(input_file);
write_outliers(data, num_values);
fclose(outlier_file);
fclose(valid_file);
return;
}
check_wrong_intput(filename);
decompose(filename);
return 0;
}
id,time,value
1,2023:07:07 00:00:50,571.4
2,2023:07:07 00:00:50,564.3
3,2023:07:07 00:01:10,587.9
dust_aqi.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
//declare function
void log_error(int error_code, const char* description);
int findMaxSensorID(const char *filename);
void processDustData(const char *input_filename, int MaxID);
typedef struct {
double sum;
int count;
} HourlyData;
fclose(file);
return MaxID;
}
fprintf(aqi_file, "id,time,value,aqi,pollution\n");
// Close files
fclose(input_file);
fclose(aqi_file);
}
if (log_file != NULL) {
fprintf(log_file, "Error %02d: %s\n", error_code, description);
fclose(log_file);
} else {
printf("Error: could not open log file for writing\n");
}
}
int MaxID=findMaxSensorID(argv[1]);
processDustData(argv[1],MaxID);
return 0;
}
id,time,value,aqi,pollution
1,2023:07:07 01:00:00,271.2,321,Hazardous
2,2023:07:07 01:00:00,251.9,301,Hazardous
3,2023:07:07 01:00:00,271.2,321,Hazardous
dust_summary.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct DateTime {
int year;
int month;
int day;
int hour;
int minute;
int second;
};
int calculateSeconds(struct DateTime dt1, struct DateTime dt2);
int daysInMonth(int month, int year);
int findMaxSensorID(const char *filename);
void generateSummary(const char *data_filename, int MaxID);
void log_error(int error_code, const char* description);
return seconds;
}
fclose(file);
return MaxID;
}
fprintf(summary_file, "id,parameter,time,value\n");
char line[256];
fgets(line, sizeof(line), data_file); // Skip header line
if (!first_timestamp_initialized) {
first_timestamp = timestamp;
first_timestamp_initialized = 1;
}
last_timestamp = timestamp;
}
fclose(data_file);
if (sensor_id == id) {
if (!first_time_initialized) {
min_time = time; // Initialize min_time with the first time
min_value = value; // Initialize min_value with the first
value
first_time_initialized = 1;
}
sum += value;
count++;
}
}
fclose(data_file);
if (count > 0) {
mean_value = sum / count;
fclose(summary_file);
printf("Summary generated successfully.\n");
}
return 1;
}*/
return 0;
}
id,parameter,time,value
1,max,2023:07:07 00:10:20,550.5
1,min,2023:07:07 08:10:50,5.0
1,mean,09:15:30,264.0
2,max,2023:07:07 07:29:20,550.5
2,min,2023:07:07 02:16:30,5.0
2,mean,09:15:30,262.5
3,max,2023:07:07 02:03:30,550.2
3,min,2023:07:07 02:07:00,5.1
3,mean,09:15:30,268.0
Dust_statistics.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_POLLUTION_LEVELS 7
typedef struct {
int id;
char pollution[20];
int duration;
} SensorData;
fclose(file);
return maxID;
}
SensorData sensorData[maxID][MAX_POLLUTION_LEVELS];
int i, j;
switch (j) {
case 0:
strcpy(sensorData[i][j].pollution, "Good");
break;
case 1:
strcpy(sensorData[i][j].pollution, "Moderate");
break;
case 2:
strcpy(sensorData[i][j].pollution, "Slightly unhealthy");
break;
case 3:
strcpy(sensorData[i][j].pollution, "Unhealthy");
break;
case 4:
strcpy(sensorData[i][j].pollution, "Very unhealthy");
break;
case 5:
strcpy(sensorData[i][j].pollution, "Hazardous");
break;
case 6:
strcpy(sensorData[i][j].pollution, "Extremely hazardous");
break;
default:
break;
}
}
}
char line[256];
while (fgets(line, sizeof(line), inputFile)) {
int id, aqi;
char pollution[20];
fclose(inputFile);
fprintf(outputFile, "id,pollution,duration\n");
fclose(outputFile);
}
if (log_file != NULL) {
fprintf(log_file, "Error %02d: %s\n", error_code, description);
fclose(log_file);
} else {
printf("Error: could not open log file for writing\n");
}
}
return 0;
}
id,pollution,duration
1,Hazardous,9
2,Hazardous,9
3,Hazardous,9
TASK 3.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
check_wrong_intput(dataFilename);
convertToHexPacket(dataFilename, hexFilename);
return 0;
}
fclose(dataFile);
fclose(hexFile);
}
sum += packet[i];
return checksum;
}
return bigEndianTimestamp;
}
// Combine the sign, exponent, and fraction fields into a 32-bit binary value
unsigned int floatBits = (sign << 31) | ((exponent + 127) << 23) | fraction;
return bigEndianFloatBits;
}
7A 0F 01 64 A7 01 20 43 87 99 9A 01 41 0B 7F
7A 0F 02 64 A7 01 20 43 7B E6 66 01 2D 06 7F
7A 0F 03 64 A7 01 20 43 87 99 9A 01 41 03 7F
7A 0F 01 64 A7 0F 30 43 7D CC CD 01 2F A0 7F
7A 0F 02 64 A7 0F 30 43 7C CC CD 01 2E 04 7F
7A 0F 03 64 A7 0F 30 43 83 80 00 01 38 A7 7F
7A 0F 01 64 A7 1D 40 43 8C 73 33 01 4A A7 7F
7A 0F 02 64 A7 1D 40 43 80 33 33 01 32 0A 7F