Midterm2 Lifesaver

With the second midterm gradually approaching, it is necessary to make an exam Lifesaver, so as to get through the knowledged we've just learned and to get prepare for the exam.

A. Sample exam:

  1. (20 points) Write a C program (please name it as P1.c) to accept user of two nonnegative integers a and b, then calculate and output the bth power of a, that is, ab. For example, if a = 3, b = 2, then the output should be 9. Here we assume 0^0 = 1. The intput and output should be handled with the following codes: Input: scanf("%d%d", &a, &b); // a and b are the two nonnegative integers; Output: printf("%d", result); // where result = ab.
1
2
3
4
5
6
7
8
9
#include <stdio.h>
#include <math.h> //do not forget math.h when using pow()
int main(){
int a,b;
scanf("%d%d", &a, &b);
int result = pow(a,b);
printf("%d\n", result);
return 0;
}
  1. (20 points) Write a C program (please name it as P2.c) to accept user input of a character string (less than 255 characters), which contains only letters and digits, then calculate and output the sum of all digits contained in the string. For example, given the user input of "vg101vg101", the output should be 4 because 1 + 0 + 1 + 1 + 0 + 1 = 4. The input and output should be handled with the following codes: Input: scanf("%s", str); // where str is define as char str[256]; Output: printf("%d", sum); // where sum is the result
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
#include <string.h>
int main(){
char str[256];
scanf("%s", str); // where str is define as char str[256];
int len=strlen(str);
int sum=0;
for(int i=0;i<len;i++){
if(str[i]>='0'&&str[i]<='9'){
sum += str[i]-'0';
}
}
printf("%d\n", sum); // where sum is the result
}
  1. (20 points) Write a C program (please name it as P3.c) to accept user input of a character string (less than 255 characters), which contains only letters a, b, c, ..., z, then output the letters and the corresponding number of occurrence of the letters in the string, where the letters are ordered according to the dictionary order. For example, for the user input of the string "cbefababc", the output should be a: 2 b: 3 c: 2 e: 1 f: 1 The input should be handled with the following codes: scanf("%s", str); // where str is define as char str[256]; And each line of the output should be handled with the following codes: printf("%c: %d", ch, occur); // where ch is the character and occur is the number of its occurrence.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <string.h>
//不动脑暴力解法:
int main(){
char alphabet[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char input[256];
int count[26] = {0};
scanf("%s",input);
int len = strlen(input);

for(int i=0;i<len;i++){
for(int j=0;j<26;j++){
if(input[i] == alphabet[j])
count[j]++;
}
}

for(int i=0;i<26;i++){
if(count[i]!=0)
printf("%c: %d\n",alphabet[i],count[i]);
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
int main(){
int count;
int len;
char prev;
char input[256];

scanf("%s",input);
len = strlen(input);
//排序
for (int i = 0; i < len; i++){
for (int j = 0; j < len - i; j++)
{
if (input[j] > input[j+1])
{
char temp3 = input[j];
input[j] = input[j + 1];
input[j + 1] = temp3;
}
}
}

prev = input[1];
count = 1;
for (int i = 2; i <= len; i++)
{
if (input[i] == prev) {
count++;
}
else {
printf("%c: %d\n", prev, count);
prev = input[i];//类似于迭代的思路
count = 1;
}
}
// Printing the last element
printf("%c: %d ", prev, count);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
char str[256];
int occ[26] = { 0 };

int i = 0;
scanf("%s", str);

while(str[i] != '\0')
{
occ[str[i]-'a']++; //str[i]-'a' 字符表示index
i++;
}

for(i = 0; i < 26; i++)
{
if(occ[i] > 0)
printf("%c: %d\n", i+'a', occ[i]); //i+'a' index表示实际对应字符
}

return 0;
}

4. (20 points) Write a C program (please name it as P4.c) to disintegrate and reassemble an input positive integer which doesn’t contain the digit 0. Given an input integer a (a > 0), the program should output an integer that has the same digits as a, while the digits are sorted in descending order. For example, given the user input integer of 3294, the output should be 9432. You can use any sorting algorithms, including the selection sort discussed in the class. The input and output should be handled with the following codes:

Input: scanf("%d", &a); Output: printf("%d\n", b); // where b is the output integer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int main(){
int a;
scanf("%d", &a);
char input[256];
sprintf(input,"%d",a);
int len=0;
len = (int)((ceil(log10(a))+1)*sizeof(char))-1;
// printf("%s\n%d\n",input,len);
for (int i = 0; i < len; i++){
for (int j = 0; j < len - i; j++){
if (input[j] < input[j+1]){
char temp;
temp = input[j];
input[j]=input[j+1];
input[j+1]=temp;
}
}
}
int b;
b = strtol(input,NULL,10);
printf("%d\n", b); // where b is the output integer
// printf("%s",input);
return 0;
}
  1. (20 points) Write a C program (please name it as P5.c) to read the provided file (P5.txt) which contains many numbers, one in a row, then output the mean value and the median value of the numbers. Please note that we may use a different input file to test your program where the numbers and number of rows could be different. Hint: in scanf, %f and %lf are for float and double type, respectively. The output should be handled with the following codes:

Output: printf("mean = %f\tmedian = %f\n", mean, median); // where mean and median are the calculated results.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

int main(){
double number;
FILE * pFile;
double input[256]={0.0};
pFile = fopen ("P5.txt", "r");
rewind (pFile); // sets the position to the beginning of the file
int l=0;
while (fscanf(pFile, "%lf", &number) == 1 ){
input[l++] = number; //store the data into a double input.
}
fclose (pFile);

double sum=0;
for(int i=0;i<l;i++){
sum+=input[i];
}
double mean=0;
mean = (double)sum/(double)l;

for (int i = 0; i < l;i++){
for (int j = 0; j < l - i; j++){
if (input[j] > input[j+1]){
double temp = input[j];
input[j] = input[j + 1];
input[j + 1] = temp;
}
}
}

double median = 0.0;
if(l%2!=0)
median = input[(l+1)/2];
if(l%2==0)
median = (input[l/2]+input[l/2+1])/2;

printf("mean = %f\tmedian = %f\n", mean, median); // where mean and median are the calculated results.
return 0;
}

B. My Functions:

1. Sorting:

1
2
3
4
5
6
7
8
9
10
11
void sort(int/char/double array[], int size){
for (int i = 0; i < size i++){
for (int j = 0; j < size - i; j++){
if (array[j] > array[j+1]){
int/char/double temp = array[j]; //dataType of temp consists with dataType of array.
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}

2. Searching:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
//Goal: find x in the array
// Linear search
int LinearSearch(int arr[], int sz, int x)
{
for (int i = 0; i < sz; ++i)
if (arr[i] == x) return i;
return -1;
}

// Binary search
// arr is an array with ascending order
// return the index of x if found, otherwise return -1
int BinarySearch(int arr[], int sz, int x)
{
int left = 0, right = sz-1; // search range of the array [left...right]
int mid;

while (left <= right)
{
mid = (left + right) / 2;
if (arr[mid] == x) return mid;
else if (arr[mid] < x) left = mid + 1;
else right = mid - 1;
}

return -1;//not found.
}

3. Useful Operation

1
2
3
4
5
6
7
8
9
10
11
void ReverseString(char *str)
{
int i, n = strlen(str);
char tmp;
for(i=0; i<n/2; i++)
{
tmp = str[i];
str[i] = str[n-1-i];
str[n-1-i] = tmp;
}
}

4. Datatype Transfer

4.1 str --> (long)int/double

1
2
3
 // Base is 10 because we are converting to integer.
integer = strtol(string, NULL, 10);
double_decimal = strtod(string, NULL, 10);

4.2 int --> str

1
2
3
4
char str[MAX_LENGTH];
sprintf(str, "%d", integer);
//the size of the str can be calculated as following:
len = (int)((ceil(log10(a))+1)*sizeof(char))-1;

​ 4.3 Read Files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
//using fscanf to get simple numbers.
double number;
FILE * pFile;
double input[256]={0.0};
pFile = fopen ("myfile.txt", "r");
rewind (pFile); // sets the position to the beginning of the file.
int i=0;

while (fscanf(pFile, "%lf", &number) == 1 ){
input[i++] = number;
}
fclose (pFile);

for(int j=0;j<i;j++){
printf("%f\n",input[j]);
}

//Using fets to get strings.
typedef struct{
char name[256];
}Name;

Name names[256];
int line = 0;
char infix[256][256];
FILE *file;
file = fopen("P5.txt", "r");
while (!feof(file))
{
if (fgets(infix[line], 256, file) != NULL)
line++;
}
fclose(file);
for(int i=0;i<line;i++){\
sprintf(names[i].name,infix[i],"abc");
}

printf("%s\n",names[0].name);

return 0;
}