Declare Variables in C++
To declare a variable you use the syntax "type <name>;". Here are some variable declaration examples:1 2 3 | int x; char letter; float the_float; |
If you use a variable that you have not declared in your program,your program will not be compiled or run, and you will receive an error message informing you that you have made a mistake. Usually, this is called an undeclared variable.
Here is a sample program demonstrating the use of a variable:
#include <iostream.h>
void main() { int number; cout<< "Please enter a number: " ; cin>> number;
cout<< "You entered: " << number << "\n" ;
} Explanation of Above program The keyword int declares number to be an integer. The function cin>> reads a value into number; the user must press enter before the number is read by the program. Try typing in a sequence of characters or a decimal number when you run the example program; the response will vary from input to input, but in no case is it particularly pretty. Notice that when printing out a variable quotation marks are not used. Were there quotation marks, the output would be "You Entered: number." The lack of quotation marks informs the compiler that there is a variable, and therefore that the program should check the value of the variable in order to replace the variable name with the variable when executing the output function. Do not be confused by the inclusion of two separate insertion operators on one line. Including multiple insertion operators on one line is perfectly acceptable and all of the output will go to the same place. In fact, you must separate string literals (strings enclosed in quotation marks) and variables by giving each its own insertion operators (<<). Trying to put two variables together with only one << will give you an error message, do not try it. Do not forget to end functions and declarations with a semicolon.by \n control will come to next line If you forget the semicolon, the compiler will give you an error message when you attempt to compile the program. |
No comments:
Post a Comment