Basics of Programming 1 solutions

Week 2 (09.19.)

Hi! You found your way to a simple static site for the code examples presented at one of the practical lessons for Basics of Programming 1 at BME. Task descriptions are on the portal

Task 2

#include <stdio.h>

/*
 *Write a program that draws a rectangle to the console out of ., |, − and + symbols.
 *Ask the user to enter the height and the width of the rectangle.
 */

int main(void) {
    int width, height;
    scanf("%d", &width);
    scanf("%d", &height);

//==========================
    printf("+");
    for (int i = 0; i < width-2;i++) {
        printf("-");
    }
    printf("+\n");
//==========================

    for (int i = 0; i < height-2;i++) {
        printf("|");
        for (int j = 0; j < width-2;j++) {
            printf(".");
        }
        printf("|\n");
    }
    printf("+");
    for (int i = 0; i < width-2;i++) {
        printf("-");
    }
    printf("+\n");
    return 0;
}

Task 3

#include <stdio.h>

int main() {
    int height;
    //ask for input
    printf("How tall of a triangle?\n");
    scanf("%d", &height);
    //loop through N lines
    for (int line_num = 0; line_num < height; line_num++) {
        for (int j = 0; j < height - line_num - 1; j++)
            printf(" ");
        for (int j = 0; j < 2 * line_num + 1; j++)
            printf("o");
        printf("\n");
    }

    //for line number i (starting from 0):
    //  print n-i-1 spaces
    //  print 2i+1 circles

    return 0;
}

Task 4

#include <stdio.h>
#include <stdbool.h>

bool is_prime(int n) {
    for (int i = 2; i <= n / 2; i++) {
        if (n % i == 0) return false;
    }
    return true;
}


int main() {
    int x = 42;
    while (x > 1) {
        printf("%d|", x);
        for (int i = 2; i <= x; i++) {
            if (is_prime(i) && x % i == 0) {
                printf("%d\n", i);
                x /= i;
                break;
            }
        }
    }
    printf("1|");
    return 0;
}