Problem Set 1 - Hello ๐Ÿ‘‹

Problem Set 1 - Hello ๐Ÿ‘‹

C - Week 1 of CS50x 2022 โœจ

ยท

2 min read

We are now introduced to the world of C. C is a programming language that has all the features of Scratch, but is a lot less friendly and is purely text. This might seem intimidating at first, but with practice comes improvement!

In Hello, we are tasked to get the name of the user and print it with "Hello, ". To start from the beginning, we would first need to include two libraries in C which are the Standard I/O and CS50 libraries. We would add these to the top of our code like this:

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

The Standard I/O library includes all the basic functionalities like printf() which prints formatted strings to the console. Similarly, the CS50 library includes additional functionalities like get_string() which takes in a string input from the user.

And now, we would type in int main(void) with two curly braces, and inside those braces, we would type in our code.

int main(void)
{
    string name = get_string("What's your name? ");
    printf("hello, %s\n", name);
}

C is a statically typed language, which means it is designed to optimize hardware efficiency and that the data types must be declared and considered at all times. With that in mind, we declare a string variable and give it a name that we can call later on and it would look like string name. We would then initialize it by adding an = sign and then storing whatever we'd like in that variable. In our case, we would type in get_string("What's your name? "); so we could store the user's name and call it later. Don't ever forget to put a semicolon to end the line! And now, to greet the user hello, we would add printf("hello, %s\n", name);. The \n would indicate that we would like a new line. We will use a format code which is the %s, then outside the quotation marks, a comma, and the variable we would like to call! We then compile and run it.

hello/ $ make hello
hello/ $ ./hello
hello/ $ What's your name? Hoakin
hello/ $ hello, hoakin
hello/ $

Thank you for reading and that is hello for you!

ย