Basic C++ Intro
C++ is now considered a low-level programming language, compared to python, swift and other modern languages. Below is a basic program that prints the words Hello, World! to the console.
#include <stdio.h>
int main(void)
{
printf("Hello, World!\n");
}
The #include calls a library to be used in the program, main() and printf() are both functions in the case of printf() it takes a parameter and prints it to the console. Notice there is a semicolon at the end of each argument.
#include <stdio.h>
#include <cs50.h> //library to use strings
int main(void)
{
//declarations
string userName = ""; //creates a variable type string
//get user input
userName = get_string("what is your name? "); //get_string function request input from user and assigns the input to the varible userName
//calculation
//output
printf("Hello %s!\n", userName); //prints to screen the user input along with greeting
}
This program contains interaction with the user, the program calls two libraries the stdio.h and the cs50.h, the second library allows the program to use strings and the first is the standard input and output library.
The program is divided into four parts, this is just my programming style. // double slash is used to make a comment, the program ignores the text following the // signs. The sections are:
- declarations, in this part all variables are declared.
- get user input, most programs need input from the user to work.
- calculation, this section is where all the computation is done, functions, loops, etc.
- output, information is passed to the user or another program.
In the first part of the program, a variable is declared, in this case, userName. The second part prints “what is your name?” on the screen and waits for the user to enter his/her name. Once the name is entered the program stores the name into the userName variable, and in the final part of the program the printf() function is called and inside the function, the variable userName is added or concatenated to the word “Hello”, %s is a placeholder which tells the program to expect a variable of type string.