Assignment For C Language
Assignment For C Language
Assignment For C Language
(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>
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);
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);
int main() {
// Define the function to be differentiated
func_ptr f = example_function;
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>
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;
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!!!