added weekly exercises of isp-ws25
This commit is contained in:
13
c/isp-ws25/weeklies/week01/w01ex01.c
Executable file
13
c/isp-ws25/weeklies/week01/w01ex01.c
Executable file
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
Exercise 01:
|
||||
Get familiar with coding.
|
||||
Create a program that displays "Hello World!"
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
printf("Hello World!");
|
||||
return 0;
|
||||
}
|
||||
21
c/isp-ws25/weeklies/week01/w01ex02.c
Executable file
21
c/isp-ws25/weeklies/week01/w01ex02.c
Executable file
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
Exercise 02:
|
||||
Implemente a temperature converter.
|
||||
It should convert Fahrenheit to Celsius.
|
||||
The conversion may be done with this formula: C=(F-32)*5/9
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
float temp_f = 0;
|
||||
float temp_c = 0;
|
||||
|
||||
int main()
|
||||
{
|
||||
printf("Fahrenheit: ");
|
||||
scanf("%f", &temp_f);
|
||||
temp_c = (temp_f - 32)*5/9;
|
||||
printf("Celsius: %.2f\n", temp_c);
|
||||
|
||||
return 0;
|
||||
}
|
||||
20
c/isp-ws25/weeklies/week01/w01ex03.c
Executable file
20
c/isp-ws25/weeklies/week01/w01ex03.c
Executable file
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
Exercise 03:
|
||||
Implement a ASCII-to-number converter.
|
||||
It should ask for a character, display it as a number, then the original character again.
|
||||
Insert enough spaces so that the character and number align.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
unsigned char input_char = 0;
|
||||
|
||||
int main()
|
||||
{
|
||||
printf("%-17s", "Insert character: ");
|
||||
scanf("%c", &input_char);
|
||||
printf("%-17s %d\n", "Number: ", input_char);
|
||||
printf("%-17s %c\n", "ASCII Character: ", input_char);
|
||||
|
||||
return 0;
|
||||
}
|
||||
59
c/isp-ws25/weeklies/week02/w02ex01.c
Executable file
59
c/isp-ws25/weeklies/week02/w02ex01.c
Executable file
@@ -0,0 +1,59 @@
|
||||
/* Bounding Box 2D
|
||||
- = rectangle that completely encloses the circle (whole circle lies within the rectangle or on its boundary)
|
||||
- bounding box must be smallest possible rectangle that encloses the circle (square)
|
||||
[x] ask for x of the center of the circle
|
||||
[x] ask for y of the center of the circle
|
||||
[x] ask for radius of the circle
|
||||
[x] calculate 2D bounding box for given circle
|
||||
[x] print coordinates of 4 corners
|
||||
[x] print coordinates with 2 decimals
|
||||
[x] print as "Bounding Box - <CORNER_NAME>: (<X_COORDINATE> / <Y_COORDINATE>)"
|
||||
[x] order: TL (top-left), TR (top-right), BL (bottom-left), BR (bottom-right)
|
||||
[x] circle as typedef struct
|
||||
[x] bounding box as typedef struct
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
struct _circle_
|
||||
{
|
||||
float coord_x_;
|
||||
float coord_y_;
|
||||
float radius_;
|
||||
};
|
||||
|
||||
struct _bbox_
|
||||
{
|
||||
float highest_x;
|
||||
float highest_y;
|
||||
float lowest_x;
|
||||
float lowest_y;
|
||||
};
|
||||
|
||||
typedef struct _circle_ Circle;
|
||||
typedef struct _bbox_ BoundingBox;
|
||||
|
||||
int main()
|
||||
{
|
||||
Circle newcircle;
|
||||
BoundingBox newbox;
|
||||
|
||||
printf("X-coordinate of the circle's center: ");
|
||||
scanf(" %f",&newcircle.coord_x_); //input 6
|
||||
printf("Y-coordinate of the circle's center: ");
|
||||
scanf(" %f",&newcircle.coord_y_); //input 3
|
||||
printf("Radius of the circle: ");
|
||||
scanf(" %f",&newcircle.radius_); // input 5
|
||||
|
||||
newbox.highest_x = newcircle.coord_x_ + newcircle.radius_;
|
||||
newbox.highest_y = newcircle.coord_y_ + newcircle.radius_;
|
||||
newbox.lowest_x = newcircle.coord_x_ - newcircle.radius_;
|
||||
newbox.lowest_y = newcircle.coord_y_ - newcircle.radius_;
|
||||
|
||||
printf("Bounding Box - TL: (%.2f/%.2f)\n", newbox.lowest_x, newbox.highest_y);
|
||||
printf("Bounding Box - TR: (%.2f/%.2f)\n", newbox.highest_x, newbox.highest_y);
|
||||
printf("Bounding Box - BL: (%.2f/%.2f)\n", newbox.lowest_x, newbox.lowest_y);
|
||||
printf("Bounding Box - BR: (%.2f/%.2f)\n", newbox.highest_x, newbox.lowest_y);
|
||||
|
||||
return 0;
|
||||
}
|
||||
32
c/isp-ws25/weeklies/week02/w02ex02.c
Executable file
32
c/isp-ws25/weeklies/week02/w02ex02.c
Executable file
@@ -0,0 +1,32 @@
|
||||
#include <stdio.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
int votes_windows;
|
||||
int votes_linux;
|
||||
|
||||
printf("Votes for Windows: ");
|
||||
scanf("%d", &votes_windows);
|
||||
|
||||
printf("Votes for Linux: ");
|
||||
//scanf("%c", &votes_linux);
|
||||
scanf("%d", &votes_linux);
|
||||
|
||||
// Compare the votes and announce the winner
|
||||
//if (votes_windows = votes_linux)
|
||||
if (votes_windows == votes_linux)
|
||||
{
|
||||
printf("It's a tie between Windows and Linux!\n");
|
||||
}
|
||||
//else (votes_windows < votes_linux)
|
||||
else if (votes_windows > votes_linux)
|
||||
{
|
||||
printf("Windows wins!\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Linux wins!\n");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
64
c/isp-ws25/weeklies/week02/w02ex03.c
Executable file
64
c/isp-ws25/weeklies/week02/w02ex03.c
Executable file
@@ -0,0 +1,64 @@
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
/*
|
||||
[x] Get user input as char
|
||||
[x] check if valid input ([ A- Z][ a- z])
|
||||
[x] check if valid input ([65-90][97-122])
|
||||
[x] if valid, print numerical
|
||||
[x] if valid, print ASCII
|
||||
[x] if invalid, print "[ERROR] not a valid character [A-Z] or [a-z]"
|
||||
[x] if invalid, no further output
|
||||
[x] request input repeatedly
|
||||
[x] print round number at start
|
||||
[x] if "Q" or "q", terminate
|
||||
[x] regular output when terminating
|
||||
[x] print "GOODBYE" before terminating
|
||||
*/
|
||||
|
||||
unsigned char userchar = 0;
|
||||
unsigned int counter = 1;
|
||||
|
||||
bool charcheck(unsigned char char_)
|
||||
{
|
||||
if((char_ >= 65 && char_ <= 90) || (char_ >= 97 && char_ <= 122)) // A <= %c <= Z OR a <= %c <= z
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void round_start()
|
||||
{
|
||||
printf("Round %d:\n", counter);
|
||||
counter++;
|
||||
printf("%s", "Insert character: ");
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
while(1)
|
||||
{
|
||||
round_start();
|
||||
scanf(" %c", &userchar);
|
||||
|
||||
if (charcheck(userchar) == true)
|
||||
{
|
||||
printf("%-17s %d\n", "Number:", userchar);
|
||||
printf("%-17s %c\n", "ASCII character:", userchar);
|
||||
//Q == 81, q == 113
|
||||
if (userchar == 81 || userchar == 113) {break;}
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("[ERROR] not a valid character [A-Z] or [a-z]\n");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
printf("GOODBYE\n");
|
||||
return 0;
|
||||
}
|
||||
58
c/isp-ws25/weeklies/week02/w02ex04.c
Executable file
58
c/isp-ws25/weeklies/week02/w02ex04.c
Executable file
@@ -0,0 +1,58 @@
|
||||
#include <stdio.h>
|
||||
|
||||
/*
|
||||
- find mistakes in the given source code
|
||||
|
||||
[x] ask for lower limit
|
||||
[x] ask for upper limit
|
||||
[x] calculate sum of all even numbers contained
|
||||
[x] calculate average of all even numbers contained
|
||||
[x] include lower, exclude upper
|
||||
[x] error if not lower < upper: "Upper limit must be higher than lower limit\n"
|
||||
[x] terminate on error
|
||||
*/
|
||||
|
||||
int main()
|
||||
{
|
||||
//int lower_limit = 0
|
||||
int lower_limit = 0;
|
||||
int upper_limit = 0;
|
||||
|
||||
printf("Enter lower limit: ");
|
||||
scanf("%d", &lower_limit);
|
||||
|
||||
printf("Enter upper limit: ");
|
||||
//scanf("%d", upper_limit);
|
||||
scanf("%d", &upper_limit);
|
||||
|
||||
//if (lower_limit <= upper_limit)
|
||||
if (upper_limit <= lower_limit)
|
||||
{
|
||||
printf("Upper limit must be higher than lower limit\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
//int sum;
|
||||
int sum = 0;
|
||||
//int count;
|
||||
int count = 0;
|
||||
|
||||
// Loop to find the sum of even numbers
|
||||
for (int i = lower_limit; i < upper_limit; i++)
|
||||
{
|
||||
//if ((i % 2) = 0)
|
||||
if ((i % 2) == 0)
|
||||
{
|
||||
sum = sum + i;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate the average of the even numbers
|
||||
//float average = count / sum;
|
||||
float average = sum / count;
|
||||
printf("Sum of even numbers: %d\n", sum);
|
||||
printf("Average of even numbers: %f\n", average);
|
||||
|
||||
return 0;
|
||||
}
|
||||
52
c/isp-ws25/weeklies/week03/w03ex01.c
Executable file
52
c/isp-ws25/weeklies/week03/w03ex01.c
Executable file
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
- find mistakes in the given source code
|
||||
- lines with incorrect code are commented, with the correct input below
|
||||
|
||||
[] take seconds as user input
|
||||
[] return seconds, minutes, hours as struct
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
// struct _Time_
|
||||
typedef struct _Time_
|
||||
{
|
||||
int seconds_;
|
||||
int minutes_;
|
||||
int hours_;
|
||||
//};
|
||||
} Time;
|
||||
|
||||
Time convertTime(int total_seconds);
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int total_seconds = 0;
|
||||
//Time time;
|
||||
Time time = {0, 0, 0};
|
||||
|
||||
printf("Total number of seconds: ");
|
||||
//scanf("%c", &total_seconds);
|
||||
scanf("%d", &total_seconds);
|
||||
|
||||
//time = convertTime(total_seconds)
|
||||
time = convertTime(total_seconds);
|
||||
|
||||
printf("%-8s %8d\n%-8s %8d\n%-8s %8d\n", "Hours:", time.hours_, "Minutes:", time.minutes_, "Seconds:", time.seconds_);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
//float convertTime(total_seconds)
|
||||
Time convertTime(int total_seconds)
|
||||
{
|
||||
Time result;
|
||||
|
||||
result.hours_ = total_seconds / 3600;
|
||||
total_seconds = total_seconds % 3600;
|
||||
result.minutes_ = total_seconds / 60;
|
||||
//result.seconds_ = total_seconds * 60;
|
||||
result.seconds_ = total_seconds % 60;
|
||||
|
||||
return result;
|
||||
}
|
||||
84
c/isp-ws25/weeklies/week03/w03ex02.c
Executable file
84
c/isp-ws25/weeklies/week03/w03ex02.c
Executable file
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
[] implement logTemperature()
|
||||
[x] take current loop iteration as argument
|
||||
[x] print "Enter temperature log #X:"
|
||||
[x] take temperature as int
|
||||
[x] if higher / lower than constants, print "Temperature X is impossible\n"
|
||||
[x] if higher / lower than constants, ask user again
|
||||
[x] if valid, print "Logged temperature: X degree Celsius\n"
|
||||
[x] implement calculateAbsoluteDifference()
|
||||
[x] take two int as argument
|
||||
[x] return absolute difference
|
||||
|
||||
Example:
|
||||
Welcome to the temperature logger!
|
||||
Enter temperature log #1:-300
|
||||
Temperature -300 is impossible
|
||||
Enter temperature log #1:30
|
||||
Logged temperature: 30 degree Celsius
|
||||
Enter temperature log #2:20
|
||||
Logged temperature: 20 degree Celsius
|
||||
Enter temperature log #3:50000
|
||||
Temperature 50000 is impossible
|
||||
Enter temperature log #3:25
|
||||
Logged temperature: 25 degree Celsius
|
||||
The difference of min/max values is 10
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#define LOWEST_POSSIBLE_TEMPERATURE (-273) // absolute zero
|
||||
#define HIGHEST_POSSIBLE_TEMPERATURE (6000) // approx. temperature of sun's photosphere (of course, temperatures can get higher)
|
||||
#define MAX_ITERATION 3
|
||||
|
||||
int logTemperature(int current_iteration);
|
||||
int calculateAbsoluteDifference(int minimum, int maximum);
|
||||
|
||||
int main(void)
|
||||
{
|
||||
printf("Welcome to the temperature logger!\n");
|
||||
int cur_min = HIGHEST_POSSIBLE_TEMPERATURE; // initialize with highest value to find lower values
|
||||
int cur_max = LOWEST_POSSIBLE_TEMPERATURE; // initialize with lowest value to find high values
|
||||
|
||||
for (int log_index = 0; log_index < MAX_ITERATION; ++log_index)
|
||||
{
|
||||
int temp = logTemperature(log_index + 1); // +1 to start with 1 instead of 0
|
||||
if(temp < cur_min)
|
||||
{
|
||||
cur_min = temp;
|
||||
}
|
||||
if(temp > cur_max)
|
||||
{
|
||||
cur_max = temp;
|
||||
}
|
||||
}
|
||||
|
||||
int diff = calculateAbsoluteDifference(cur_min, cur_max);
|
||||
printf("The difference of min/max values is %d\n", diff);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int calculateAbsoluteDifference(int minimum, int maximum)
|
||||
{
|
||||
return maximum - minimum;
|
||||
}
|
||||
|
||||
int logTemperature(int current_iteration)
|
||||
{
|
||||
int temperature = 0;
|
||||
|
||||
printf("Enter temperature log #%d:", current_iteration);
|
||||
scanf("%d", &temperature);
|
||||
|
||||
if(temperature > HIGHEST_POSSIBLE_TEMPERATURE || temperature < LOWEST_POSSIBLE_TEMPERATURE)
|
||||
{
|
||||
printf("Temperature %d is impossible\n", temperature);
|
||||
temperature = logTemperature(current_iteration);
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Logged temperature: %d degree Celsius\n", temperature);
|
||||
}
|
||||
|
||||
return temperature;
|
||||
}
|
||||
36
c/isp-ws25/weeklies/week03/w03ex03.c
Executable file
36
c/isp-ws25/weeklies/week03/w03ex03.c
Executable file
@@ -0,0 +1,36 @@
|
||||
#include <stdio.h>
|
||||
|
||||
int lucas(int number);
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int index_position = 0;
|
||||
int lucas_number = 0;
|
||||
|
||||
printf("Enter index position: ");
|
||||
scanf("%d", &index_position);
|
||||
|
||||
if(index_position < 0)
|
||||
{
|
||||
printf("Entered position must be a non-negative integer\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
lucas_number = lucas(index_position);
|
||||
|
||||
printf("lucas(%d) = %d\n", index_position, lucas_number);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int lucas(int number)
|
||||
{
|
||||
int result = 0;
|
||||
|
||||
if(number == 0){return 2;}
|
||||
if(number == 1){return 1;}
|
||||
|
||||
result = lucas(number - 1) + lucas(number - 2);
|
||||
|
||||
return result;
|
||||
}
|
||||
92
c/isp-ws25/weeklies/week04/w04ex01.c
Executable file
92
c/isp-ws25/weeklies/week04/w04ex01.c
Executable file
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* In this task, you should write a program that records daily temperature data for a week and perform a basic analysis. The program should do the following:
|
||||
*
|
||||
Store the temperatures of a full* week (i.e., 7 days) in an array
|
||||
Let the user define a temperature threshold for further analysis
|
||||
Calculate the average temperature of the week
|
||||
Print the number of days with a temperature above the threshold
|
||||
|
||||
Functions are already declared for these functionalities in the given code, which still need to be implemented:
|
||||
|
||||
readTemperatures(float temperatures[]): For each day of the week, this function should print Temperature for day n: (where n represents the number of the day) and the user can enter the temperature for the respective day. The input for each day should be stored in an array that is passed when called in the main() function.
|
||||
readTemperatureThreshold(): The user can enter a temperature threshold after printing Temperature threshold: . The value should be returned to the main() function.
|
||||
calculateAverageTemperature(float temperatures[]): In this function, the average temperature of all values in the array is calculated and returned.
|
||||
countDaysWithTemperatureAboveThreshold(float temperatures[], float threshold): This function should return the number of days on which the recorded temperature is above (i.e., greater than) the user-defined threshold.
|
||||
|
||||
|
||||
These functions are called in the main() function. Both the average temperature (with two decimal places) and the threshold (with two decimal places) along the days with temperature above the threshold are printed in the main() (see the example below).
|
||||
|
||||
This is an example:
|
||||
|
||||
Temperature for day 1: 24.7
|
||||
Temperature for day 2: 22.8
|
||||
Temperature for day 3: 28.3
|
||||
Temperature for day 4: 28.9
|
||||
Temperature for day 5: 30
|
||||
Temperature for day 6: 24.8
|
||||
Temperature for day 7: 23.2
|
||||
Temperature threshold: 25.5
|
||||
Average temperature: 26.10
|
||||
Days with temperature above 25.50: 3
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#define DAYS_PER_WEEK 7
|
||||
|
||||
void readTemperatures(float temperatures[]);
|
||||
float readTemperatureThreshold();
|
||||
float calculateAverageTemperature(float temperatures[]);
|
||||
int countDaysWithTemperatureAboveThreshold(float temperatures[], float threshold);
|
||||
|
||||
int main()
|
||||
{
|
||||
float temperatures[DAYS_PER_WEEK] = {0};
|
||||
float temperature_threshold = 0.0;
|
||||
float average_temperature = 0.0;
|
||||
int days_above_threshold = 0;
|
||||
|
||||
// Add your code here
|
||||
readTemperatures(temperatures);
|
||||
temperature_threshold = readTemperatureThreshold();
|
||||
average_temperature = calculateAverageTemperature(temperatures);
|
||||
printf("Average temperature: %.2f\n", average_temperature);
|
||||
days_above_threshold = countDaysWithTemperatureAboveThreshold(temperatures, temperature_threshold);
|
||||
printf("Days with temperature above %.2f: %d", temperature_threshold, days_above_threshold);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Add your code here
|
||||
void readTemperatures(float temperatures[])
|
||||
{
|
||||
for(int day = 0 ; day < DAYS_PER_WEEK ; day++)
|
||||
{
|
||||
printf("Temperature for day %d: ", (day + 1));
|
||||
scanf("%f", &temperatures[day]);
|
||||
}
|
||||
}
|
||||
float readTemperatureThreshold()
|
||||
{
|
||||
float threshold = 0;
|
||||
printf("Temperature threshold: ");
|
||||
scanf("%f", &threshold);
|
||||
return threshold;
|
||||
}
|
||||
float calculateAverageTemperature(float temperatures[])
|
||||
{
|
||||
float average_temperature = 0;
|
||||
for(int day = 0 ; day < DAYS_PER_WEEK ; day++)
|
||||
{
|
||||
average_temperature += temperatures[day];
|
||||
}
|
||||
return (average_temperature / DAYS_PER_WEEK);
|
||||
}
|
||||
int countDaysWithTemperatureAboveThreshold(float temperatures[], float threshold)
|
||||
{
|
||||
int days_above_threshold = 0;
|
||||
for(int day = 0 ; day < DAYS_PER_WEEK ; day++)
|
||||
{
|
||||
if (temperatures[day] > threshold){days_above_threshold++;}
|
||||
}
|
||||
return days_above_threshold;
|
||||
}
|
||||
91
c/isp-ws25/weeklies/week04/w04ex02.c
Executable file
91
c/isp-ws25/weeklies/week04/w04ex02.c
Executable file
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
In this task, you should write a program that checks if an array contains duplicate integer values.
|
||||
|
||||
First, the program prints Enter the number of elements to store in the array (max MAX_ARRAY_SIZE): . Then, the user can specify the size of the array (limited to the given constant MAX_ARRAY_SIZE). If the input of the user is less than 1 or greater than MAX_ARRAY_SIZE, the program should print Invalid size\n and ask the user again for the size of the array.
|
||||
|
||||
Once the size has been specified by the user, the user can enter n (i.e., n = size of the array) elements as integer values. This is done one after another by asking the user Element i: to enter the ith element.
|
||||
|
||||
After all elements have been entered by the user, the duplication check is performed. For this, implement the following function:
|
||||
|
||||
containsDuplicates(int values[], int size): This function takes the array containing the user-defined values and the size of the array as parameters. The function should return whether the array contains any duplicate values or not. The function should return the boolean value true if the array contains duplicate values, and false otherwise.
|
||||
|
||||
In the main() function, call containsDuplicates(int values[], int size) and print The array contains duplicates\n if the return value is true, and The array does not contain duplicates\n if the return value is false.
|
||||
|
||||
This is an example:
|
||||
|
||||
Enter the number of elements to store in the array (max 10): 4
|
||||
Element 1: 2
|
||||
Element 2: 9
|
||||
Element 3: -1
|
||||
Element 4: 9
|
||||
The array contains duplicates
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_ARRAY_SIZE 10
|
||||
|
||||
void getArraySize(int* array_size);
|
||||
void getArrayValues(int values[], int array_size);
|
||||
bool containsDuplicates(int values[], int array_size);
|
||||
|
||||
int main(void)
|
||||
{
|
||||
bool has_duplicates = 0;
|
||||
int array_size = 0;
|
||||
getArraySize(&array_size);
|
||||
int values_to_check[array_size];
|
||||
memset(values_to_check, 0, array_size*sizeof(int));
|
||||
getArrayValues(values_to_check, array_size);
|
||||
has_duplicates = containsDuplicates(values_to_check, array_size);
|
||||
|
||||
if (has_duplicates)
|
||||
{
|
||||
printf("The array contains duplicates\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("The array does not contain duplicates\n");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void getArraySize(int* array_size)
|
||||
{
|
||||
while (1)
|
||||
{
|
||||
printf("Enter the number of elements to store in the array (max %d): ", MAX_ARRAY_SIZE);
|
||||
scanf("%d", array_size);
|
||||
if ( 1 > *array_size || *array_size > MAX_ARRAY_SIZE )
|
||||
{
|
||||
printf("Invalid size\n");
|
||||
continue;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void getArrayValues(int values[], int array_size)
|
||||
{
|
||||
for ( int counter = 0 ; counter < array_size ; counter++ )
|
||||
{
|
||||
printf("Element %d: ", (counter + 1));
|
||||
scanf("%d", &values[counter]);
|
||||
}
|
||||
}
|
||||
|
||||
bool containsDuplicates(int values[], int array_size)
|
||||
{
|
||||
for (int counter_a = 0 ; counter_a < array_size ; counter_a++)
|
||||
{
|
||||
printf("Loop A, Position %d: %d\n", counter_a, values[counter_a]);
|
||||
for (int counter_b = counter_a + 1 ; counter_b < array_size ; counter_b++)
|
||||
{
|
||||
printf("Loop B, Position %d: %d\n", counter_b, values[counter_b]);
|
||||
if (values[counter_a] == values[counter_b]){ return true; }
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
96
c/isp-ws25/weeklies/week05/w05ex01.c
Executable file
96
c/isp-ws25/weeklies/week05/w05ex01.c
Executable file
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
In this task, you should implement three fundamental string functions yourself.
|
||||
|
||||
Your program should read two words from the user (up to 25 characters each) and then work with these two strings. Since fgets() also stores the newline character ('\n') when the user presses Enter, even an "empty" input will have a length of 1. After implementing the three functions described below, the program should print the length of each word, check whether they are equal, and print a copy of the first word.
|
||||
|
||||
int stringLength(char* string): This function should count how many characters appear in the string before the terminating '\0'. Use a loop that increments a counter until you reach the end of the string. The function should return this length as an integer but should not print anything itself. Remember that fgets() keeps the newline character ('\n') when the user presses Enter, so it will also be included in the length.
|
||||
|
||||
int stringCompare(char* first_string, char* second_string): This function should compare two strings character by character and return 0 if the strings are exactly the same. If the strings are different, it should return a negative value if the first differing character in first_string has a lower ASCII value than the corresponding character in second_string, and a positive value if it has a higher ASCII value. The comparison is case-sensitive, so uppercase and lowercase letters are treated as different. The function should not print anything. The output (Words are equal or Words are not equal) is handled in main().
|
||||
|
||||
void stringCopy(char* from, char* to): This function should copy the content of one string into another. Copy every character from from to to until the null terminator is reached, and make sure to also copy the terminating '\0'. The function does not return a value and does not print anything. The copied word is printed in main().
|
||||
|
||||
The main() function is already provided. You are not allowed to use <string.h>
|
||||
|
||||
This is an example:
|
||||
|
||||
Enter first word: Hello
|
||||
Enter second word: hello
|
||||
Length of first word: 6
|
||||
Length of second word: 6
|
||||
Words are not equal
|
||||
Copied word: Hello
|
||||
*/
|
||||
#include <stdio.h>
|
||||
|
||||
#define SIZE 26
|
||||
|
||||
int stringLength(char* string);
|
||||
int stringCompare(char* first_string, char* second_string);
|
||||
void stringCopy(char* from, char* to);
|
||||
|
||||
int main(void)
|
||||
{
|
||||
char first_word[SIZE];
|
||||
char second_word[SIZE];
|
||||
char copy[SIZE];
|
||||
|
||||
printf("Enter first word: ");
|
||||
fgets(first_word, SIZE, stdin);
|
||||
printf("Enter second word: ");
|
||||
fgets(second_word, SIZE, stdin);
|
||||
|
||||
int first_word_length = stringLength(first_word);
|
||||
int second_word_length = stringLength(second_word);
|
||||
printf("Length of first word: %d\n", first_word_length);
|
||||
printf("Length of second word: %d\n", second_word_length);
|
||||
|
||||
if (stringCompare(first_word, second_word) == 0)
|
||||
{
|
||||
printf("Words are equal\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Words are not equal\n");
|
||||
}
|
||||
|
||||
stringCopy(first_word, copy);
|
||||
printf("Copied word: %s\n", copy);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int stringLength(char* string)
|
||||
{
|
||||
int string_length = 0;
|
||||
|
||||
while (string[string_length] != '\0')
|
||||
{
|
||||
//printf("char is %c\n", string[string_length]);
|
||||
string_length++;
|
||||
}
|
||||
return string_length;
|
||||
}
|
||||
|
||||
int stringCompare(char* first_string, char* second_string)
|
||||
{
|
||||
int string_length = 0;
|
||||
|
||||
while (first_string[string_length] != '\n')
|
||||
{
|
||||
if(first_string[string_length] != second_string[string_length]) { return 1; }
|
||||
string_length++;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void stringCopy(char* from, char* to)
|
||||
{
|
||||
int string_length = 0;
|
||||
|
||||
while (from[string_length] != '\n')
|
||||
{
|
||||
to[string_length] = from[string_length];
|
||||
string_length++;
|
||||
}
|
||||
// TODO: copy the content from one string to another
|
||||
}
|
||||
72
c/isp-ws25/weeklies/week05/w05ex02.c
Executable file
72
c/isp-ws25/weeklies/week05/w05ex02.c
Executable file
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
In this task, you should write a program that analyses sentences provided by the user. In the first step, you have to implement the user input in the main using fgets (see TODO in the main function). You can assume that the user will never enter more than 200 characters. Then, you should implement two functions:
|
||||
|
||||
countVowel(char string[]): This function counts the vowels (de: Vokale) in the string and returns it as an integer. The return value (number of vowels) is then printed in the provided main() function.
|
||||
printReverse(char string[]): This function prints the provided string in reverse and adds a \n at the end. It has no return value (void). Make sure to avoid printing the string’s null terminator. If the string is empty (no characters, just the user pressing ‘Enter’/’Return’) the function should print Empty string\n and end.
|
||||
|
||||
You are allowed to use any library, including <string.h>.
|
||||
|
||||
This is an example (once the code is fixed):
|
||||
|
||||
Enter sentence (max 200 chars): Hello Students
|
||||
number of vowels: 4
|
||||
|
||||
stnedutS olleH
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
// TODO: write your functions
|
||||
int countVowel(char* string);
|
||||
void printReverse(char* string);
|
||||
|
||||
int main(void)
|
||||
{
|
||||
char my_string[200] = {0};
|
||||
printf("Enter sentence (max 200 chars): ");
|
||||
fgets(my_string,200,stdin);
|
||||
|
||||
int nr_vowel = countVowel(my_string);
|
||||
printf("number of vowels: %d\n", nr_vowel);
|
||||
printReverse(my_string);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int countVowel(char* string)
|
||||
{
|
||||
int position = 0;
|
||||
int vowels = 0;
|
||||
|
||||
while (string[position] != '\0')
|
||||
{
|
||||
if (
|
||||
string[position] == 'a' ||
|
||||
string[position] == 'e' ||
|
||||
string[position] == 'i' ||
|
||||
string[position] == 'o' ||
|
||||
string[position] == 'u' ||
|
||||
string[position] == 'A' ||
|
||||
string[position] == 'E' ||
|
||||
string[position] == 'I' ||
|
||||
string[position] == 'O' ||
|
||||
string[position] == 'U'
|
||||
) { vowels++; }
|
||||
position++;
|
||||
}
|
||||
return vowels;
|
||||
}
|
||||
|
||||
void printReverse(char* string)
|
||||
{
|
||||
int position = 0;
|
||||
while (string[position] != '\n') { position++; }
|
||||
if (position == 0) { printf("Empty string\n"); return; }
|
||||
while (position >= 0)
|
||||
{
|
||||
printf("%c",string[position]);
|
||||
position--;
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
52
c/isp-ws25/weeklies/week05/w05ex03.c
Executable file
52
c/isp-ws25/weeklies/week05/w05ex03.c
Executable file
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
In this task, you should implement a function that swaps two elements in an existing array. The main function is already predefined. Your task is:
|
||||
|
||||
Add the user input to the main function by reading the first and second index from user input and write it into the array indices-array. indices[0] should contain the first user input. indices[1] should contain the second user input. You can use scanf for this operation. The two user inputs define the indices of the two elements that should be switched in the array.
|
||||
Write a function called swapTwoNumbers(). The function takes 3 arguments: i) the array of numbers, ii) the size of the array as int, and iii) the array where the two indices to swap are stored. The function should check if the indices are valid in the current array. If one or both indices are invalid the function should return 1. Otherwise the elements in the array should be swapped and the function should return 0.
|
||||
|
||||
The provided main function prints the array or an error message, if the user enters invalid indices.
|
||||
|
||||
This is an example:
|
||||
|
||||
0
|
||||
4
|
||||
5 2 3 4 1
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#define SIZE 5
|
||||
|
||||
// TODO: add your function swapTwoNumbers()
|
||||
int swapTwoNumbers(int array[], int size, int indices[]);
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int my_array[SIZE] = {1,2,3,4,5};
|
||||
int size = sizeof(my_array) / sizeof(my_array[0]);
|
||||
|
||||
|
||||
int indices[2] = {-1, -1};
|
||||
scanf("%d",&indices[0]);
|
||||
scanf("%d",&indices[1]);
|
||||
|
||||
int failed = swapTwoNumbers(my_array, size, indices);
|
||||
if (failed)
|
||||
{
|
||||
printf("Indices out of range\n");
|
||||
return 0;
|
||||
}
|
||||
for (int i = 0; i < SIZE; i++)
|
||||
{
|
||||
printf("%d ", my_array[i]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int swapTwoNumbers(int array[], int size, int indices[])
|
||||
{
|
||||
if (indices[1] >= size){return 1;}
|
||||
int placeholder = array[indices[0]];
|
||||
array[indices[0]] = array[indices[1]];
|
||||
array[indices[1]] = placeholder;
|
||||
return 0;
|
||||
}
|
||||
89
c/isp-ws25/weeklies/week07/w07ex01.c
Executable file
89
c/isp-ws25/weeklies/week07/w07ex01.c
Executable file
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
In this task, you should get familiar with malloc() and free().
|
||||
In addition, you should implement the functions
|
||||
- fillArray(int size, int base_number)
|
||||
- printArray(int* numbers, int size).
|
||||
|
||||
main:
|
||||
- user can enter the size of the integer array
|
||||
- user can enter the base number that is used to fill the array
|
||||
- print "Memory allocation failed\n" if memory allocation in fillArray failed
|
||||
- immediately return exit code 1
|
||||
- free the allocated memory using free() at the end.
|
||||
|
||||
call createAndFillArray(int size, int base_number)
|
||||
- create array by allocating enough memory for it on the heap using malloc()
|
||||
- if memory allocation is not successful, return NULL
|
||||
- After allocating fill the array with integer values
|
||||
with multiples of base_number using pointer arithmetic
|
||||
- Return pointer to array at the end of the function
|
||||
|
||||
call printArray(int* numbers, int size)
|
||||
- print the array using pointer arithmetic
|
||||
|
||||
Examples:
|
||||
|
||||
Size: 5
|
||||
Fill numbers array with multiples of: 3
|
||||
3 6 9 12 15
|
||||
|
||||
Size: 4
|
||||
Fill numbers array with multiples of: 5
|
||||
5 10 15 20
|
||||
|
||||
Size: 12
|
||||
Fill numbers array with multiples of: 100
|
||||
100 200 300 400 500 600 700 800 900 1000 1100 1200
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h> // TODO: Include the required header file
|
||||
|
||||
int* createAndFillArray(int size, int base_number)
|
||||
{
|
||||
// TODO: Allocate memory
|
||||
int *numbers = (int*) malloc( size * sizeof(int) );
|
||||
// TODO: Check if memory could be allocated
|
||||
if ( numbers == NULL ) return NULL;
|
||||
|
||||
// TODO: Fill the array with multiples of base_number using pointer arithmetic and return it
|
||||
for ( int position = 0 ; position < size; position++ )
|
||||
{
|
||||
*(numbers + position) = base_number * ( position + 1 );
|
||||
}
|
||||
|
||||
return numbers;
|
||||
}
|
||||
|
||||
void printArray(int* numbers, int size)
|
||||
{
|
||||
for (int position = 0; position < size; position++)
|
||||
{
|
||||
printf("%d ", *(numbers + position));
|
||||
}
|
||||
// TODO: Print the array using pointer arithmetic
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int size = 0;
|
||||
printf("Size: ");
|
||||
scanf("%d", &size);
|
||||
|
||||
int base_number = 0;
|
||||
printf("Fill numbers array with multiples of: ");
|
||||
scanf("%d", &base_number);
|
||||
|
||||
int* numbers = createAndFillArray(size, base_number);
|
||||
if ( numbers == NULL )
|
||||
{
|
||||
printf("Memory allocation failed\n");
|
||||
return 1; // TODO: Return 1 if the memory allocation was not successful
|
||||
}
|
||||
|
||||
printArray(numbers, size);
|
||||
|
||||
free(numbers); // TODO: Free the allocated memory
|
||||
|
||||
return 0;
|
||||
}
|
||||
119
c/isp-ws25/weeklies/week07/w07ex02.c
Executable file
119
c/isp-ws25/weeklies/week07/w07ex02.c
Executable file
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
In this task, you should get familiar with calloc() and free().
|
||||
The program tracks the attendance of students.
|
||||
The user can enter the number of students and then mark certain students as present.
|
||||
|
||||
Use calloc() to allocate memory on the heap for the required number of students.
|
||||
All students are marked as absent by default since calloc() initializes by default with 0.
|
||||
If the memory allocation is not successful, print Memory allocation failed\n and immediately return the exit code 1.
|
||||
|
||||
After allocating the memory, the user can enter student numbers (1-based, not 0-based) to mark them as present.
|
||||
When a student number is entered, the program should mark the corresponding student as present.
|
||||
Any student numbers that are not within the range of all student numbers
|
||||
(i.e., 1 to the entered number of students) should be ignored.
|
||||
If the user enters 0, the attendance check is done and the program prints the attendance record.
|
||||
For each student, print if the student is present or absent.
|
||||
|
||||
Don’t forget to free the allocated memory using free() at the end of the main() function.
|
||||
|
||||
Examples:
|
||||
|
||||
Number of students: 12
|
||||
Enter student numbers to mark as present (1 to 12, 0 to end):
|
||||
1
|
||||
8
|
||||
4
|
||||
5
|
||||
3
|
||||
0
|
||||
Attendance record:
|
||||
Student 1: Present
|
||||
Student 2: Absent
|
||||
Student 3: Present
|
||||
Student 4: Present
|
||||
Student 5: Present
|
||||
Student 6: Absent
|
||||
Student 7: Absent
|
||||
Student 8: Present
|
||||
Student 9: Absent
|
||||
Student 10: Absent
|
||||
Student 11: Absent
|
||||
Student 12: Absent
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h> // TODO: Include the required header file
|
||||
#include <stdbool.h>
|
||||
|
||||
#define ganzzahl int
|
||||
#define gleitkomma float
|
||||
#define leere void
|
||||
#define NICHTS ((void*)0)
|
||||
#define schreibf printf
|
||||
#define liesf scanf
|
||||
#define falls if
|
||||
#define fuer for
|
||||
#define solange while
|
||||
#define mach do
|
||||
#define mach_weiter continue
|
||||
#define gib_zurueck return
|
||||
#define haupt main
|
||||
#define befreie free
|
||||
#define unsigniert unsigned
|
||||
|
||||
|
||||
ganzzahl* erstelleFeld ( ganzzahl anzahl_an_schuelern )
|
||||
{
|
||||
ganzzahl *studenten = (ganzzahl*) calloc(anzahl_an_schuelern,sizeof(ganzzahl));
|
||||
falls(studenten == NICHTS) gib_zurueck NICHTS;
|
||||
gib_zurueck studenten;
|
||||
}
|
||||
|
||||
leere liesAnwesenheit ( ganzzahl* anwesenheit_der_studenten, ganzzahl anzahl_an_schuelern)
|
||||
{
|
||||
ganzzahl schueler = 0;
|
||||
schreibf("Enter student numbers to mark as present (1 to %d, 0 to end):\n", anzahl_an_schuelern); // TODO: Mark students as present
|
||||
ganzzahl benutzereingabe = 0;
|
||||
mach
|
||||
{
|
||||
liesf("%d", &benutzereingabe);
|
||||
schueler++;
|
||||
falls(benutzereingabe == 0) gib_zurueck;
|
||||
falls(benutzereingabe < 0) mach_weiter;
|
||||
falls(benutzereingabe > anzahl_an_schuelern - 1) mach_weiter;
|
||||
anwesenheit_der_studenten[benutzereingabe-1] = 1;
|
||||
}solange(benutzereingabe != 0 && schueler < anzahl_an_schuelern);
|
||||
}
|
||||
|
||||
leere schreibAnwesenheit ( ganzzahl* anwesenheit_der_studenten, ganzzahl anzahl_an_schuelern )
|
||||
{
|
||||
schreibf("Attendance record:\n");
|
||||
|
||||
fuer(ganzzahl schueler = 1; schueler <= anzahl_an_schuelern; schueler++)
|
||||
{
|
||||
schreibf("Student %d: %s\n", schueler, anwesenheit_der_studenten[schueler-1] == 0 ? "Absent" : "Present");
|
||||
}
|
||||
// TODO: Print the attendance record
|
||||
}
|
||||
|
||||
ganzzahl haupt(leere)
|
||||
{
|
||||
ganzzahl anzahl_an_schuelern = 0;
|
||||
|
||||
schreibf("Number of students: ");
|
||||
liesf("%d", &anzahl_an_schuelern);
|
||||
|
||||
ganzzahl* anwesenheit = erstelleFeld(anzahl_an_schuelern); // TODO: Allocate memory
|
||||
falls ( anwesenheit == NICHTS ) { // TODO: Check if memory could be allocated
|
||||
schreibf("Memory allocation failed\n");
|
||||
gib_zurueck 1;
|
||||
}
|
||||
|
||||
liesAnwesenheit(anwesenheit, anzahl_an_schuelern);
|
||||
|
||||
schreibAnwesenheit(anwesenheit, anzahl_an_schuelern);
|
||||
|
||||
befreie(anwesenheit); // TODO: Free the allocated memory
|
||||
|
||||
gib_zurueck 0;
|
||||
}
|
||||
106
c/isp-ws25/weeklies/week08/w08ex01.c
Executable file
106
c/isp-ws25/weeklies/week08/w08ex01.c
Executable file
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
In this task, you should implement a basketball score
|
||||
logger using malloc()/calloc()/realloc() and free():
|
||||
|
||||
- Declare struct Player
|
||||
- integer jersey_number_
|
||||
- integer points_
|
||||
- print: "Number of players on the team: "
|
||||
- user input: number of players as int
|
||||
- Allocate memory on heap
|
||||
- all players of a team can be stored
|
||||
- check if memory could be allocated
|
||||
after each malloc()/calloc()/realloc()
|
||||
- If mem-alloc NOK:
|
||||
"Memory allocation failed\n"
|
||||
return 1
|
||||
- print: "Jersey number and points for player x: "
|
||||
- user input: jersey number & points for each player
|
||||
- first = jersey number
|
||||
- second = points
|
||||
- values separated by space (or any whitespace)
|
||||
- show team scoring summary
|
||||
- print list of athletes and their points
|
||||
- free allocated memory using free().
|
||||
|
||||
Example:
|
||||
|
||||
Welcome to the Basketball Score Logger!
|
||||
|
||||
Number of players on the team: 6
|
||||
Jersey number and points for player 1: 30 37
|
||||
Jersey number and points for player 2: 23 29
|
||||
Jersey number and points for player 3: 35 7
|
||||
Jersey number and points for player 4: 1 20
|
||||
Jersey number and points for player 5: 19 41
|
||||
Jersey number and points for player 6: 34 12
|
||||
|
||||
Team Scoring Summary:
|
||||
#30: 37 points
|
||||
#23: 29 points
|
||||
#35: 7 points
|
||||
#1: 20 points
|
||||
#19: 41 points
|
||||
#34: 12 points
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define fire free
|
||||
|
||||
typedef struct _Player_{
|
||||
int jersey_number_;
|
||||
int points_;
|
||||
} Player;
|
||||
|
||||
Player* initializeTeam(int team_size)
|
||||
{
|
||||
Player* new_team = calloc(team_size, sizeof(Player));
|
||||
if ( new_team == NULL ) return NULL;
|
||||
|
||||
return new_team;
|
||||
}
|
||||
|
||||
void getPlayerStats(Player* team, int team_size)
|
||||
{
|
||||
for ( int player = 0; player < team_size; player++ )
|
||||
{
|
||||
printf("Jersey number and points for player %d: ", player + 1);
|
||||
scanf("%d %d", &(team + player)->jersey_number_, &(team + player)->points_);
|
||||
}
|
||||
}
|
||||
|
||||
void printPlayerStats(Player* team, int team_size)
|
||||
{
|
||||
printf("\nTeam Scoring Summary:\n");
|
||||
|
||||
for ( int player = 0; player < team_size; player++ )
|
||||
{
|
||||
printf("#%d: %d points\n", (team + player)->jersey_number_, (team + player)->points_);
|
||||
}
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
printf("Welcome to the Basketball Score Logger!\n\n");
|
||||
|
||||
printf("Number of players on the team: ");
|
||||
int team_size = 0;
|
||||
scanf(" %d", &team_size);
|
||||
|
||||
Player* team = initializeTeam(team_size);
|
||||
if ( team == NULL )
|
||||
{
|
||||
printf("Memory allocation failed\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
getPlayerStats(team, team_size);
|
||||
|
||||
printPlayerStats(team, team_size);
|
||||
|
||||
fire(team);
|
||||
|
||||
return 0;
|
||||
}
|
||||
70
c/isp-ws25/weeklies/week08/w08ex02.c
Executable file
70
c/isp-ws25/weeklies/week08/w08ex02.c
Executable file
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
In this task, you should get familiar with
|
||||
malloc(), realloc() and free().
|
||||
|
||||
- user input: sequence of characters
|
||||
- store in array of characters
|
||||
- dynamically increase memory on heap for array
|
||||
- temporary pointer for return value of realloc()
|
||||
- add All characters to array until Q is entered
|
||||
- check if mem-alloc OK after each malloc() / realloc()
|
||||
- If mem-alloc NOK
|
||||
- print: "Memory allocation failed\n"
|
||||
- return 1
|
||||
- free allocated memory at the end of main()
|
||||
|
||||
Examples:
|
||||
|
||||
awe s o m e !Q
|
||||
Entered characters: a w e s o m e !
|
||||
|
||||
IS P ! :) Q
|
||||
Entered characters: I S P ! : )
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h> // TODO: Include the required header file
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int capacity = 2;
|
||||
int count = 0;
|
||||
char *characters = NULL;
|
||||
|
||||
characters = (char *)calloc(capacity, sizeof(char)); // TODO: Allocate memory (make use of the variable capacity)
|
||||
if (characters == NULL)
|
||||
{
|
||||
printf("Memory allocation failed\n");
|
||||
return 1;
|
||||
} // TODO: Check if memory could be allocated
|
||||
|
||||
char value = 0;
|
||||
while (scanf(" %c", &value) && value != 'Q')
|
||||
{
|
||||
if (count == capacity) // TODO: Check capacitiy and use realloc() to not run out of memory on the heap
|
||||
{
|
||||
capacity = capacity * count;
|
||||
char *temp_chars = (char*)realloc(characters, sizeof(char) * capacity);
|
||||
if (temp_chars == NULL)
|
||||
{
|
||||
printf("Memory allocation failed\n");
|
||||
return 1;
|
||||
}
|
||||
characters = temp_chars;
|
||||
} // TODO: Check if memory could be allocated
|
||||
characters[count] = value;
|
||||
count++;
|
||||
// TODO: Add the entered value to the characters array
|
||||
}
|
||||
|
||||
printf("Entered characters:");
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
printf(" %c", characters[i]);
|
||||
}
|
||||
printf("\n");
|
||||
|
||||
free(characters); // TODO: Free the allocated memory
|
||||
|
||||
return 0;
|
||||
}
|
||||
79
c/isp-ws25/weeklies/week08/w08ex03.c
Executable file
79
c/isp-ws25/weeklies/week08/w08ex03.c
Executable file
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
This program manages a list of product prices.
|
||||
The user can enter a product price and then decide,
|
||||
whether to continue or to to stop adding new product prices.
|
||||
After adding product prices, the average price is calculated and printed.
|
||||
|
||||
Unfortunately, there are some errors in the code.
|
||||
The compiler finds a few of them, others are logical
|
||||
errors and are not detected by the compiler.
|
||||
|
||||
This is an example:
|
||||
|
||||
Price for product 1: 6.50
|
||||
Add another price? (1 = yes, 0 = no): 1
|
||||
Price for product 2: 2.80
|
||||
Add another price? (1 = yes, 0 = no): 1
|
||||
Price for product 3: 9.90
|
||||
Add another price? (1 = yes, 0 = no): 1
|
||||
Price for product 4: 450
|
||||
Add another price? (1 = yes, 0 = no): 0
|
||||
Average price: 117.30
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
void addPrice(float** prices, int* count, int* capacity)
|
||||
{
|
||||
if (*count >= *capacity)
|
||||
{
|
||||
*capacity *= 2;
|
||||
float *new_prices = realloc(*prices, *capacity * sizeof(float));
|
||||
if (new_prices == NULL)
|
||||
{
|
||||
printf("Memory allocation failed\n");
|
||||
return;
|
||||
}
|
||||
*prices = new_prices;
|
||||
}
|
||||
|
||||
printf("Price for product %d: ", *count + 1);
|
||||
scanf("%f", &(*prices)[*count]);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int capacity = 2;
|
||||
int count = 0;
|
||||
float* prices = (float*) calloc(capacity, sizeof(float));
|
||||
if (prices == NULL)
|
||||
{
|
||||
printf("Memory allocation failed\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
int additional_price = 0;
|
||||
do
|
||||
{
|
||||
addPrice(&prices, &count, &capacity);
|
||||
count++;
|
||||
if (prices == NULL)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("Add another price? (1 = yes, 0 = no): ");
|
||||
scanf("%d", &additional_price);
|
||||
} while (additional_price);
|
||||
|
||||
float total = 0;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
total += prices[i];
|
||||
}
|
||||
printf("Average price: %.2f\n", total / count);
|
||||
|
||||
free(prices);
|
||||
return 0;
|
||||
}
|
||||
1
c/isp-ws25/weeklies/week09/quote.txt
Executable file
1
c/isp-ws25/weeklies/week09/quote.txt
Executable file
@@ -0,0 +1 @@
|
||||
The first 90 minutes are the most important
|
||||
1
c/isp-ws25/weeklies/week09/quote_copy.txt
Executable file
1
c/isp-ws25/weeklies/week09/quote_copy.txt
Executable file
@@ -0,0 +1 @@
|
||||
The first 90 minutes are the most important
|
||||
22
c/isp-ws25/weeklies/week09/sentences.txt
Executable file
22
c/isp-ws25/weeklies/week09/sentences.txt
Executable file
@@ -0,0 +1,22 @@
|
||||
A forked purple lightning bolt, on black field speckled with four-pointed stars.
|
||||
Can a man still be brave if he's afraid?
|
||||
That is the only time a man can be brave.
|
||||
What is dead may never die.
|
||||
Our Sun Shines Bright.
|
||||
As High as Honor.
|
||||
The North remembers.
|
||||
It is rare to meet a Lannister who shares my enthusiasm for dead Lannisters.
|
||||
A good act does not wash out the bad, nor a bad act the good.
|
||||
Each should have its own reward.
|
||||
Winter is coming.
|
||||
What is dead may never die.
|
||||
What is dead may never die.
|
||||
When you play the game of thrones, you win or you die.
|
||||
A good act does not wash out the bad, nor a bad act the good.
|
||||
Each should have its own reward.
|
||||
More pigeon pie, please.
|
||||
A forked purple lightning bolt, on black field speckled with four-pointed stars.
|
||||
Words are like wind.
|
||||
The wolf and the lion.
|
||||
The winds of Winter.
|
||||
It is rare to meet a Lannister who shares my enthusiasm for dead Lannisters.
|
||||
104
c/isp-ws25/weeklies/week09/w09ex01.c
Executable file
104
c/isp-ws25/weeklies/week09/w09ex01.c
Executable file
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
In this task, you should get familiar with file I/O operations in C
|
||||
by writing a program that reads the text file sentences.txt and counts
|
||||
both the number of words and the number of characters (excluding line breaks).
|
||||
|
||||
Tasks:
|
||||
- Open "sentences.txt" using fopen.
|
||||
- if open fails (i.e., fopen returns NULL):
|
||||
- Print the error message "Could not open file\n"
|
||||
- return 1
|
||||
- User Input: line number that should be analyzed
|
||||
- Line numbers are 1-based (if user enters "1", analyze first line)
|
||||
- Read file (e.g., using fgetc)
|
||||
- analyze correct line
|
||||
- Count words separated by whitespace.
|
||||
- Count characters (excluding line break).
|
||||
- Close file properly after processing.
|
||||
- Print word count and character count according to example output below.
|
||||
- If entered line number is not in range line numbers of file:
|
||||
- print "Could not analyze line\n".
|
||||
|
||||
Examples:
|
||||
|
||||
Line number to analyze: 5
|
||||
Word Count: 4
|
||||
Character Count: 22
|
||||
|
||||
Line number to analyze: 1
|
||||
Word Count: 12
|
||||
Character Count: 80
|
||||
|
||||
Line number to analyze: 22
|
||||
Word Count: 14
|
||||
Character Count: 76
|
||||
*/
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
printf("Line number to analyze: ");
|
||||
int line_number;
|
||||
scanf("%d", &line_number);
|
||||
if (line_number < 1)
|
||||
{
|
||||
printf("Could not analyze line\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
FILE *file = fopen("sentences.txt", "r");
|
||||
if (file == NULL)
|
||||
{
|
||||
printf("Could not open file\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
int current_line = 1;
|
||||
int word_count = 0;
|
||||
int char_count = 0;
|
||||
int character = 0;
|
||||
|
||||
int saw_char = 0;
|
||||
|
||||
while ((character = fgetc(file)) != EOF)
|
||||
{
|
||||
if(current_line != line_number && character != '\n') continue;
|
||||
if (character == '\n')
|
||||
{
|
||||
if (current_line == line_number) break;
|
||||
current_line++;
|
||||
continue;
|
||||
}
|
||||
if (current_line == line_number)
|
||||
{
|
||||
if (character != '\n') char_count++;
|
||||
//It is rare to meet a Lannister who shares my enthusiasm for dead Lannisters.
|
||||
if (isspace(character))
|
||||
{
|
||||
saw_char = 0;
|
||||
}
|
||||
else if (isgraph(character) && !saw_char)
|
||||
{
|
||||
word_count++;
|
||||
saw_char = 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (current_line < line_number)
|
||||
{
|
||||
printf("Could not analyze line\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Word Count: %d\n", word_count);
|
||||
printf("Character Count: %d\n", char_count);
|
||||
}
|
||||
|
||||
fclose(file);
|
||||
return 0;
|
||||
}
|
||||
77
c/isp-ws25/weeklies/week09/w09ex02.c
Executable file
77
c/isp-ws25/weeklies/week09/w09ex02.c
Executable file
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
In this task, you should get familiar with file manipulation in C
|
||||
by performing operations like reading the file content,
|
||||
moving the file cursor, and writing the predefined string
|
||||
"Halftime is for the real fans" to a specific position in a file.
|
||||
|
||||
Your tasks are:
|
||||
- Open file quote.txt in read/write mode
|
||||
if fopen == NULL
|
||||
- Print "Could not open file\n"
|
||||
- return 1
|
||||
- Print original content of file to console
|
||||
- Ask user to enter a position to insert a predefined string
|
||||
- move cursor to the specified position
|
||||
if cannot be moved
|
||||
- Print "Could not move the file cursor\n"
|
||||
- return 1
|
||||
- overwrite existing content (i.e. use fseek to move the cursor)
|
||||
- Write the predefined string into the file using fputs
|
||||
- Rewind the file to the beginning and print the updated content of the file to the console
|
||||
- Close the file properly after processing.
|
||||
|
||||
Examples:
|
||||
|
||||
Original file content: The first 90 minutes are the most important
|
||||
Position to insert the string: 4
|
||||
Updated file content: The Halftime is for the real fans important
|
||||
|
||||
Original file content: The first 90 minutes are the most important
|
||||
Position to insert the string: -5
|
||||
Could not move the file cursor
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
FILE *file = fopen("quote.txt", "r+");
|
||||
if (NULL == file) {
|
||||
printf("Could not open file\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("Original file content: ");
|
||||
int character = 0;
|
||||
while ((character = fgetc(file)) != EOF)
|
||||
{
|
||||
printf("%c", character);
|
||||
}
|
||||
printf("\n");
|
||||
rewind(file);
|
||||
|
||||
long insert_position = 0;
|
||||
printf("Position to insert the string: ");
|
||||
scanf("%ld", &insert_position);
|
||||
|
||||
if (fseek(file, insert_position, SEEK_CUR))
|
||||
{
|
||||
printf("Could not move the file cursor\n");
|
||||
fclose(file);
|
||||
return 1;
|
||||
}
|
||||
|
||||
char* text_to_insert = "Halftime is for the real fans";
|
||||
fputs(text_to_insert, file);
|
||||
rewind(file);
|
||||
|
||||
printf("Updated file content: ");
|
||||
while ((character = fgetc(file)) != EOF)
|
||||
{
|
||||
printf("%c", character);
|
||||
}
|
||||
printf("\n");
|
||||
|
||||
fclose(file);
|
||||
return 0;
|
||||
}
|
||||
136
c/isp-ws25/weeklies/week09/w09ex03.c
Executable file
136
c/isp-ws25/weeklies/week09/w09ex03.c
Executable file
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
In this task, you should get familiar with enum.
|
||||
The program allows the user to enter ratings for a movie
|
||||
using integers that should correspond to an enum.
|
||||
Only ratings between 1 and 5 are considered.
|
||||
|
||||
The program processes the ratings,
|
||||
prints the average rating using stars (i.e., *) and
|
||||
prints a recommendation based on the average ratings.
|
||||
|
||||
Your task is:
|
||||
|
||||
- Declare a typedef’d enum for the 5 categories of the rating system
|
||||
- 1 == worst rating
|
||||
- 5 == best rating
|
||||
- all ratings are entered by the user
|
||||
- calculate average rating using total_ratings and weighted_ratings
|
||||
- total_ratings == total number of ratings entered by the user
|
||||
- weighted_ratings == ratings weighted by their category
|
||||
- ratings in 1st category: weighted with 1
|
||||
- ratings in 2nd category: weighted with 3
|
||||
|
||||
This is necessary to calculate the average rating by dividing weighted_ratings by total_ratings
|
||||
Use your typedef’d enum as data type of the variable in which you store the average ratings
|
||||
Use an integer division to calculate the average rating
|
||||
(e.g., an average rating of 3.84 corresponds to the 3rd category).
|
||||
|
||||
Print the average rating using stars.
|
||||
For instance, if the average rating of the movie is in the
|
||||
3rd category of the rating system, then print Average rating: ***.
|
||||
|
||||
Print a recommendation based on the rating category of the movie’s average rating:
|
||||
- 1st category: The movie is terrible, do not watch it
|
||||
- 2nd category: The movie is bad and not worth watching
|
||||
- 3rd category: The movie is average, neither especially good nor bad
|
||||
- 4th category: The movie is good and worth watching
|
||||
- 5th category: The movie is excellent and a must-see
|
||||
- Print "Invalid rating for the movie" if none of the above cases apply.
|
||||
|
||||
|
||||
Examples:
|
||||
|
||||
Enter movie ratings (1 = TERRIBLE, 2 = BAD, 3 = AVERAGE, 4 = GOOD, 5 = EXCELLENT). End with -1:
|
||||
3 4 3 3 2 3 5 4 4 3 3 -1
|
||||
Average rating: ***
|
||||
Recommendation: The movie is average, neither especially good nor bad
|
||||
|
||||
|
||||
Enter movie ratings (1 = TERRIBLE, 2 = BAD, 3 = AVERAGE, 4 = GOOD, 5 = EXCELLENT). End with -1:
|
||||
5 4 3 4 5 4 3 4 5 4 3 5 5 5 5 5 3 3 3 -1
|
||||
Average rating: ****
|
||||
Recommendation: The movie is good and worth watching
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#define MAX_RATING 5
|
||||
|
||||
// TODO: Declare a (typedef'd) enum for a movie rating scale that consists of 5 categories
|
||||
|
||||
typedef enum _Ratings_ {
|
||||
TERRIBLE = 1,
|
||||
BAD,
|
||||
AVERAGE,
|
||||
GOOD,
|
||||
EXCELLENT
|
||||
} Ratings;
|
||||
|
||||
void giveRecommendation(Ratings rating)
|
||||
{
|
||||
printf("Recommendation: ");
|
||||
switch (rating) {
|
||||
case TERRIBLE:
|
||||
printf("The movie is terrible, do not watch it\n");
|
||||
break;
|
||||
case BAD:
|
||||
printf("The movie is bad and not worth watching\n");
|
||||
break;
|
||||
case AVERAGE:
|
||||
printf("The movie is average, neither especially good nor bad\n");
|
||||
break;
|
||||
case GOOD:
|
||||
printf("The movie is good and worth watching\n");
|
||||
break;
|
||||
case EXCELLENT:
|
||||
printf("The movie is excellent and a must-see\n");
|
||||
break;
|
||||
default:
|
||||
printf("Invalid rating for the movie\n");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
printf("Enter movie ratings (1 = TERRIBLE, 2 = BAD, 3 = AVERAGE, 4 = GOOD, 5 = EXCELLENT). End with -1:\n");
|
||||
|
||||
int input = 0;
|
||||
int ratings[MAX_RATING] = {0};
|
||||
while (1)
|
||||
{
|
||||
scanf("%d", &input);
|
||||
if (input == -1) break;
|
||||
|
||||
if (input > 0 && input <= MAX_RATING)
|
||||
{
|
||||
ratings[--input]++;
|
||||
}
|
||||
}
|
||||
|
||||
int total_ratings = 0;
|
||||
int weighted_ratings = 0;
|
||||
for (int i = 0; i < sizeof(ratings)/sizeof(ratings[0]); i++)
|
||||
{
|
||||
total_ratings += ratings[i];
|
||||
weighted_ratings += (ratings[i] * (i+1));
|
||||
}
|
||||
|
||||
if (total_ratings == 0)
|
||||
{
|
||||
printf("No ratings entered\n");
|
||||
return 1;
|
||||
}
|
||||
// TODO: Store the average rating in a variable. The data type of the variable should be your typedef'd enum
|
||||
Ratings average_rating = weighted_ratings / total_ratings;
|
||||
|
||||
// TODO: Print the average rating by displaying stars
|
||||
printf("Average rating: ");
|
||||
for(int i = 0; i < average_rating; i++) printf("%c", '*');
|
||||
printf("\n");
|
||||
|
||||
// TODO: Print the recommendation
|
||||
giveRecommendation(average_rating);
|
||||
|
||||
return 0;
|
||||
}
|
||||
65
c/isp-ws25/weeklies/week10/w10ex01.c
Executable file
65
c/isp-ws25/weeklies/week10/w10ex01.c
Executable file
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
In this task, you should find mistakes in the given source code.
|
||||
The idea is to represent multiple characters as words stored as linked lists.
|
||||
The code creates five elements of the struct Character.
|
||||
|
||||
Each element has a member content_ (the actual character) and
|
||||
a pointer to the next character in the word (next_).
|
||||
|
||||
The printAll-function should correctly print all the elements inside the linked list.
|
||||
|
||||
Unfortunately, there are some errors in the code.
|
||||
The compiler finds a few of them, others are logical errors and are not detected by the compiler.
|
||||
|
||||
Zum Beispiel:
|
||||
Resultat
|
||||
hello
|
||||
*/
|
||||
|
||||
//#include "stdio.h"
|
||||
#include <stdio.h> // General libraries should always be included with <>
|
||||
// including with "" searches in compile directory first
|
||||
|
||||
typedef struct _Character_
|
||||
{
|
||||
char content_;
|
||||
//Character* next_;
|
||||
struct _Character_ *next_;
|
||||
} Character;
|
||||
|
||||
void printAll(Character* head)
|
||||
{
|
||||
//if (head = NULL)
|
||||
if (head == NULL)
|
||||
return;
|
||||
|
||||
Character* it = head;
|
||||
while (it != NULL)
|
||||
{
|
||||
printf("%c", it->content_);
|
||||
it = it->next_;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
If you want a recursive printAll call:
|
||||
|
||||
void printAll(Character *head)
|
||||
{
|
||||
if (head == NULL) return; // guard against empty list
|
||||
putchar(head->content_); // if here, prints first -> last
|
||||
printAll(head->next_);
|
||||
putchar(head->content_); // if here, prints last -> first
|
||||
}
|
||||
*/
|
||||
|
||||
int main(void)
|
||||
{
|
||||
Character e = {'o', NULL};
|
||||
Character d = {'l', &e};
|
||||
Character c = {'l', &d};
|
||||
Character b = {'e', &c};
|
||||
Character a = {'h', &b};
|
||||
|
||||
printAll(&a);
|
||||
}
|
||||
124
c/isp-ws25/weeklies/week10/w10ex02.c
Executable file
124
c/isp-ws25/weeklies/week10/w10ex02.c
Executable file
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
In this task, you should extend the playlist program from the last lecture.
|
||||
The playlist is implemented as a linked list of songs,
|
||||
where each song has an artist, a title, a length,
|
||||
and a pointer to the next element in the linked list.
|
||||
For details about the implementation have a look at the corresponding lecture.
|
||||
|
||||
The given code already covers creating and printing the linked list.
|
||||
Your task is to implement the function deleteSong(),
|
||||
which takes the head of the linked list and the index that should be removed.
|
||||
|
||||
Removing an element from a linked list is efficient but requires careful implementation.
|
||||
Before coding, it's helpful to visualize the process with a diagram.
|
||||
To keep the code snippet short, you can assume that
|
||||
- malloc will always succeed (i.e., it will never return NULL) and
|
||||
- the user will always provide a valid index to remove an element from the linked list.
|
||||
|
||||
This is an example: The yellow-marked content represents a user input.
|
||||
|
||||
0: Bob Dylan - Like A Rolling Stone (369)
|
||||
1: AJR - Humpty Dumpty (217)
|
||||
2: Wham! - Last Christmas (322)
|
||||
3: Eminem - Lose Yourself (401)
|
||||
Which element do you want to remove? 1
|
||||
0: Bob Dylan - Like A Rolling Stone (369)
|
||||
1: Wham! - Last Christmas (322)
|
||||
2: Eminem - Lose Yourself (401)
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct _Song_
|
||||
{
|
||||
char artist_[50];
|
||||
char title_[50];
|
||||
short length_;
|
||||
struct _Song_* next_;
|
||||
} Song;
|
||||
|
||||
void printSong(Song* head)
|
||||
{
|
||||
Song* current = head;
|
||||
int index = 0;
|
||||
while(current != NULL)
|
||||
{
|
||||
printf("%d: %s - %s (%d)\n", index++, current->artist_, current->title_, current->length_);
|
||||
current = current->next_;
|
||||
}
|
||||
}
|
||||
|
||||
Song* createAndAddSong(Song* head, char* artist, char* title, short len)
|
||||
{
|
||||
Song* new_song = malloc(sizeof(Song)); // usually you should check for NULL here and react accordingly
|
||||
strcpy(new_song->artist_, artist);
|
||||
strcpy(new_song->title_, title);
|
||||
new_song->length_ = len;
|
||||
new_song->next_ = NULL;
|
||||
|
||||
if(head == NULL)
|
||||
{
|
||||
head = new_song;
|
||||
return head;
|
||||
}
|
||||
|
||||
Song* current = head;
|
||||
while(current->next_ != NULL)
|
||||
{
|
||||
current = current->next_;
|
||||
}
|
||||
current->next_ = new_song;
|
||||
return head;
|
||||
}
|
||||
|
||||
void deleteSong(Song** head, int index_to_remove)
|
||||
{
|
||||
if (head == NULL || *head == NULL) return; // nothing to remove
|
||||
if (index_to_remove < 0) return; // invalid index
|
||||
|
||||
if (index_to_remove == 0)
|
||||
{
|
||||
Song *free_head = *head;
|
||||
*head = free_head->next_;
|
||||
free(free_head);
|
||||
return;
|
||||
}
|
||||
|
||||
Song *previous = *head;
|
||||
Song *song_to_remove = *head;
|
||||
|
||||
for (int index = 0; index < index_to_remove; index++)
|
||||
{
|
||||
if (song_to_remove == NULL) return; // index out of range
|
||||
previous = song_to_remove;
|
||||
song_to_remove = song_to_remove->next_;
|
||||
}
|
||||
|
||||
if (song_to_remove == NULL) return; // index out of range
|
||||
|
||||
previous->next_ = song_to_remove->next_;
|
||||
free(song_to_remove);
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
// usually you should check for NULL at each call and react accordingly
|
||||
Song* head = createAndAddSong(NULL, "Bob Dylan", "Like A Rolling Stone", 369);
|
||||
head = createAndAddSong(head, "AJR", "Humpty Dumpty", 217);
|
||||
head = createAndAddSong(head, "Wham!", "Last Christmas", 322);
|
||||
head = createAndAddSong(head, "Eminem", "Lose Yourself", 401);
|
||||
printSong(head);
|
||||
|
||||
int nr_to_remove = 0;
|
||||
printf("Which element do you want to remove? ");
|
||||
scanf("%d", &nr_to_remove);
|
||||
|
||||
deleteSong(&head, nr_to_remove);
|
||||
|
||||
printSong(head);
|
||||
// you also should free the linked list
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user