Basics of Programming 1 solutions

Week 6 (10.17.)

Task descriptions are on the portal

Task 1

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void) {
    //string input;
    char input[1000];
    //read into input
    scanf("%[^\n]s", input);

    //processing
    for (size_t i = 0; i < strlen(input); i++) {
        if (islower(input[i])) input[i] = toupper(input[i]);
        //printf("%c", toupper(input[i]));
    }

    //print out the input
    printf("%s", input);
    return 0;
}

Task 3

#include <ctype.h>
#include <stdio.h>
#include <string.h>

int main(void) {
     int base, place = 1, end_result = 0;
     char input[50];
     scanf("%d", &base);
     scanf("%s", input);
     for (int i = strlen(input)-1; i >= 0; i--) {
          char current = input[i];
          int result;
          if (isdigit(current)) result = current - '0';
          else {
               result = 10 + toupper(current) - 'A';
          }
          if (result >= base) return 1;
          end_result += result * place;
          place *= base;
     }

     printf("%d %d", base, end_result);
     return 0;
}

Task 4

/*
*

Dividing the number by the base of the number system and taking the remainder gives us the last digit. For instance, 1234 % 10 = 4, the number ends with digit 4.
If we take the result of the division instead, we get the remaining part of the number (to be printed out): 1234 / 10 = 123.
Doing these steps iteratively we get all the numeric digits to print, with one flaw: in a reverse order!

*/

#include <ctype.h>
#include <stdio.h>

int main(void) {
    int input, base;
    scanf("%d", &base);
    scanf("%d", &input);
    char output[100];
    int count = 0;
    while (input > 0) {
        char converted_input;
        if (input % base < 10) {
            converted_input = '0' + input%base;
        } else {
            converted_input = 'A' + (input%base - 10);
        }
        output[count++] = converted_input;
        input /= base;
    }
    for (int i = count - 1; i>=0; i--) {
        printf("%c", output[i]);
    }
    return 0;
}