Assignment 4
Computer Programing I (COSE101.02)
(1) Define a `struct` for complex numbers and a function for the addition of complex numbers, and then
print the results as specified. (복소수를 위한 struct와 복소수의 덧셈 연산을 위한 함수를 정의하고,
그 결과를 예시와 같이 출력하라.)
#include <stdio.h>
// Define the Complex struct
typedef struct { // (0.5 Points)
double real;
double imag;
} Complex;
// Function to add two complex numbers
Complex add(Complex a, Complex b) {
Complex result;
result.real = a.real + b.real;
result.imag = a.imag + b.imag;
return result;
}
int main() {
// Define two complex numbers
Complex c1 = { 3.0, 2.0 };
Complex c2 = { 1.0, -7.0 };
// Perform operations
Complex sum = add(c1, c2);
printf("(%.2f + %.2fi) ", c1.real, c1.imag); // (0.5 Points)
printf("+ (%.2f + %.2fi) ", c2.real, c2.imag);
printf("= (%.2f + %.2fi)\n", sum.real, sum.imag);
}
(3.00 +2.00i) + (1.00 -7.00i) = (4.00 -5.00i)
1
(2) Write a C program to use function pointers in C to calculate the numerical derivative of a function at
a specific point using the central difference method. (함수의 포인터를 사용하여 central difference
method를 이용한 특정 점에서의 수치적 미분하는 C 프로그램을 작성하라.)
#include <stdio.h>
// Define a function pointer type for functions that take a double and return a double
typedef double (*func_ptr)(double);
// Example function: f(x) = x^2
double example_function(double x) {
return x * x;
}
// Numerical derivative function
double numerical_derivative(func_ptr f, double x, double h) { // (0.5 Points)
return (f(x + h) - f(x - h)) / (2 * h);
}
int main() {
// Define the function to be differentiated
func_ptr f = example_function;
// Define the point at which to differentiate and the step size
double x = 2.0;
double h = 1e-5;
// Calculate the derivative
double derivative = numerical_derivative(f, x, h); // (0.5 Points)
// Print the result
printf("The numerical derivative of f(x) at x = %.2f is %.5f\n", x, derivative);
return 0;
}
The numerical derivative of f(x) at x = 2.00 is 4.00000
2
(3) Write a C program that uses command-line arguments to convert miles to kilometers. The program
takes the number of miles as an input argument and outputs the equivalent distance in kilometers.
(Command-line arguments를 사용하여 mile에서 km로 변환하는 C 프로그램을 작성하라. 이
프로그램은 입력 인수로 마일 수를 받아 이를 킬로미터로 변환하여 출력한다.)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) { // (0.5 Points)
// Check if the correct number of arguments is provided
if (argc != 2) {
fprintf(stderr, "Usage: %s <miles>\n", argv[0]);
return 1;
}
// Convert the command-line argument to a double
double miles = atof(argv[1]); // (0.5 Points)
if (miles <= 0) {
fprintf(stderr, "Please provide a positive number for miles.\n");
return 1;
}
// Convert miles to kilometers
double kilometers = miles * 1.60934;
// Print the result
printf("%.2f miles is equal to %.2f kilometers\n", miles, kilometers);
return 0;
}
Project2.exe 2.5
2.50 miles is equal to 4.02 kilometers
3
(4) Write a C program that dynamically allocate memory for a 2D array, initialize it with values, print the
values, and then free the allocated memory. (2차원 배열을 위한 동적 메모리를 할당하고, 값을
초기화하고, 값을 출력하고, 그리고 할당된 메모리를 해제하라.)
#include <stdio.h>
#include <stdlib.h>
void main()
{
int rows = 3;
int cols = 4;
// Allocate memory for a 2D array
int** array = (int**)malloc(rows * sizeof(int*)); // (0.5 Points)
if (array == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(1);
}
for (int i = 0; i < rows; i++) {
array[i] =(int*)malloc(cols * sizeof(int)); // (0.5 Points)
if (array[i] == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(1);
}
}
// Initialize the 2D array
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
array[i][j] = i + j;
}
}
// Print the 2D array
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
// Free the 2D array
for (int i = 0; i < rows; i++) {
free(array[i]);
}
free(array);
}
0 1 2 3
1 2 3 4
2 3 4 5
4
(5) Write a C program that writes data to a test file and then reads and prints the data from that file.
(테스트 파일에 데이터를 쓰고, 그 데이터를 읽어 출력하는 C프로그램을 작성하라.)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* fp;
char filename[] = "example.txt";
char data[] = "Hello, world!\nThis is a file I/O example in C.";
char buffer[100];
// File Write
fp = fopen(filename, "w"); // (0.5 Points)
if (fp == NULL) {
fprintf(stderr, "Failed to open file for writing\n");
exit(1);
}
fprintf(fp, "%s", data); // (0.5 Points)
fclose(fp);
// File Read
fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "Failed to open file for reading\n");
exit(1);
}
printf("File content:\n");
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
fclose(fp);
return 0;
}
File content:
Hello, world!
This is a file I/O example in C.
Thank you!!!