C++ Identifiers for beginners
Example
int secondsPerMinutes = 60;
// OK, but not so easy to understand what s actually is or represent in this code.
int s = 60;
When naming variables, there are general rules to follow:
- Names can consist of letters, digits, and underscores.
- Names must start with a letter or an underscore.
- Names are case-sensitive, meaning "myVar" and "myvar" are considered different variables in C++ because letters are case sensitive.
- Names should not include whitespaces or special characters like !, #, %, etc.
- Reserved words, such as C++ keywords like "int," cannot be used as variable names.
Constants in C++
C++ Constants
Example
myNum = 10; // error: assignment of read-only variable 'myNum'
It is advisable to declare variables as constant when you have values that are unlikely to change. By declaring a variable as constant, you indicate that its value should remain unchanged throughout the program execution. This helps improve code clarity and can prevent accidental modifications to the variable's value.
Example
const int minutesPerHour = 60;
const float PI = 3.14;
User Input in C++
cout
is used to output (print) values while cin is used to get user input. cin is a predefined variable that reads data from the keyboard using >> operator. In the example, the user inputs a number, which is stored in variable x, and then we print the value of x. If you haven't learn the introduction to C++ kindly click C++ Tutorials For Complete Beginners and follow the step by step examples.Example on User input in C++
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
cout, pronounced 'see-out,' is used for output and utilizes the insertion operator (<<). It is used to display values. On the other hand, cin, pronounced 'see-in,' is used for input and employs the extraction operator (>>). It is used to obtain user input e.g a user typing in his or her user name, date of birth, conversion of number etc.
Creating a Calculator in C++
Example
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
Congratulations You just built a Calculator in C++!
PREVIOUS <<< C++ Tutorials For Complete Beginners - Output (Print Text) in C++
Stay Tuned on this page it will be updated shortly...
0 Comments