DEV Community

Matthew Cullen
Matthew Cullen

Posted on

My first C++ program

Github

Most of my experience in programming is in Ruby and JavaScript. C++ was the first language I have had to compile. Compiling means turning high-level language (the code we wrote) into low-level language (also called assembly language) that a computer can understand. The assembly language is then turned into machine code by an assembler. The result is an intermediary file called an object file. The object file contains all of the machine-level instructions for that file. During the compilation process any errors that prevent the code from compiling will be displayed in the terminal and the compiling process will be stop.

The first program I made was a simple game where you guess a sequence of numbers after being given their product and sum.
Picture of the game

In c++ there is a main function called at start-up that acts as an entry point to the rest of the program.

int main() 
{
  PlayGame();

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

The function must be named main. Adding int before main indicates that this function returns an integer. The return value of this function is considered the exit status of the program. By returning a 0 after our PlayGame() function has ran we are telling the computer to exit the program with no errors.

Some C++ basics

~specify the type a value is before assigning it.
~add const if you don't intend for that value to ever be changed.

int NumberA = 1;
const bool LikesCats = true;
Enter fullscreen mode Exit fullscreen mode

~use the following syntax to include files from outside your program

#include <name of file>
Enter fullscreen mode Exit fullscreen mode

~console output
~ \n or std::endl will produce a new line

string greeting = "Hello";
std::cout << "you can print a string\n"; // prints ~ you can print a string
std::cout << greeting << std::endl; //prints ~ Hello
Enter fullscreen mode Exit fullscreen mode

~getting user input

string InputFromUser;
std::cin >> InputFromUser; //stores what the user types
std::cout << InputFromUser; //prints what the user typed in
Enter fullscreen mode Exit fullscreen mode

~if/else/while

if (condition)
{
  //execute this code if condition met
}
else
{
  //do this if it's not
}
while (condition)
{
  //do this while the condition is true
}
Enter fullscreen mode Exit fullscreen mode

I will continue to write more as I learn. My goal is to start playing around with the Unreal 4 engine.

Top comments (1)

Collapse
 
sinrock profile image
Michael R.

This is really neat!! I don't know C++ yet, just getting Ruby learned, but when I do get to C++ I'll remember your tips and info! 👏