본문 바로가기
College Computer Science/Algorithm

[알고리즘] Assignment 2

by 2den 2022. 1. 28.
728x90

Submit a word, hwp or pdf file to the e-class that contains (1) your answers for the following exercises, and (2) your codes written in the C programming language and their results for programming exercises (screenshots okay).

 

1. (programming) Write a program that takes a number n and displays the largest k satisfying the following equations: 2^k <= n. Display the results for three different n's: 10, 50, and 1025.

 

#include <stdio.h>
#define MAX 100

int main()
{
	int n, k, temp, cnt;
    int i;
    
    printf("Enter a number : ");
    scanf_s("%d", &n);
    
    for (i=0; i<MAX; i++) {
    	cnt = 0;
        temp = 1;
        if (i != 0) {
        	while (cnt<i) {
            	temp *= 2;
                cnt++;
            }
        }
        if (temp>n) {
            k = i-1; break;
        }   
    }
    
    printf("k : %d", k);
    
    return 0;
}

 

 

2. (programming) Palindrome refers to words that have the same results when we read from the beginning and read from the end, such as level, bob, and radar. Write a function that determines if the given word is palindrome or not. Display the results when you put two different words (one is palindrome and the other is not).

 

#include <stdio.h>
#include <string.h>
#define MAX 20

int main()
{
    char word[MAX];
    
    printf("Enter a word : ");
    scanf_s("%s", word, sizeof(word));
    
    int l = strlen(word) / 2 - 1;
    int r;
    if (strlen(word) % 2 == 0) {
        r = l + 1;
    } else {
        r = l + 2;
    }
    
    for (l; l>=0; l--) {
    	if (word[l] != word[r]) {
            printf("The word is not palindrome. \n"); break;
        }
        else {
        	if (l == 0) printf("The word is palindrome. \n");
        }
        r++;
    }
}

 

 

3. What is the output of the following code? (The code shows the partial lines in a complete program.)

int x=3, y=2, z=5;
printf("%d\n", ((x > y) ? x : y) > z ? ((y > x) ? x : y) : z);

The output is "5"

 

 

 

4. Use the Binary Search algorithm to search for the integer 120 in the following list (array) of integers. Show the actions step by step (by hand).

 

12 34 37 45 57 82 99 120 134

returns "7"

728x90

댓글