CS-50 problem set 1

February 13, 2018

Harry Gill
Tags: learning rust C CS50 | 2min Read

Problem set translation form C to rust. I’m using the code I had from 2014 and implementing rust equivalent as a learning exercises. the firs C program is very simple classic ‘Hello World’ followed by rust ‘hello world’.

The example below that is about parsing command line user input and printing a pyramid based on that input. Although I can think of many ways to improve the code and user interaction but I chose to just copy exactly the same functionality for new rust code.

// C
#include <stdio.h>
int main(void) {
    printf("hello, world\n");
    return 0;
}
// Rust
fn main() {
    println!("Hello World!");
}
/* pest1 mario.c */

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    /* declare height */
    int height= 0;
    do
    {
        /* get height from the user */
        printf("Height: ");
        /* using cs50 helper function */
        height = GetInt();
    } while ((height < 0) || (height > 23));
    
    /* loop through the given height */
    for (int i = 2; i < height + 2; i++)
    {
        /* print necessary space characters */
        for (int j = height - i; j >= 0; j--)
        {
            printf(" ");
        }
        /* print the pyramid with # characters */
        for (int k = 0; k < i; k++)
        {
            printf("#");
        }
        /* start a new line */
        printf("\n");

    }

    return 0;
}
use std::io;
use std::io::Write;

fn main() {
    loop {
        print!("Height: ");
        io::stdout().flush().unwrap();

        let mut height = String::new();
        io::stdin()
            .read_line(&mut height)
            .expect("Failed to read line");
        let height: u32 = match height.trim().parse() {
            Ok(num) => {
                if num < 23 {
                    num
                } else {
                    continue;
                }
            }
            Err(_) => {
                continue;
            }
        };

        print_mario_grid(height);
        break;
    }
}

fn print_mario_grid(height: u32) {
    for i in 2..height + 2 {
        let j = height - i;
        for _ in (0..j).rev() {
            print!(" ");
        }
        for _ in 0..i {
            print!("#");
        }
        print!("\n");
    }
}