
Declaration, Comments, Numbers, and Variables in C++ Programming
Explore the fundamentals of declaration, comments, numeric values, and variables in C++ programming, including examples and explanations to enhance your understanding. Dive deep into the concept of integer values and learn why variable declaration is crucial for memory management in C++.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Lecture Two Declaration, Comments, Numbers, Variables, I/O data (cout, cin). Thursday, March 20, 2025 C++ Programming Language 1
Lecture Outlines Numeric values Variables Declarations Assignment Identifiers Reserved words Thursday, March 20, 2025 C++ Programming Language 2
Numeric Values Integer Values Integers are whole numbers, which means they have no fractional parts, and an integer can be positive, negative, or zero. Examples of integers include 4, 19, 0, and 1005. In contrast, 4.5 is not an integer, since it is not a whole number. It is easy to write a C++ program that prints the number four, as Listing shows. #include <iostream> int main() { cout<<4<<"\n"; } Thursday, March 20, 2025 C++ Programming Language 3
Numeric Values #include <iostream> int main() { cout<< "4\n"; } Both programs behave identically, but the first program prints the value of the number four, while the second one prints a message containing the digit four. The statement cout<< 4 << \n ; Sometimes, a statement such as the following: cout<< 4 <<endl; This statement on the surface behaves exactly like the following statement: cout<< 4 << endl; but the two expressions endl and '\n' do not mean exactly the same thing. The endl expression does involve a newline character, but it also performs some additional work that normally is not necessary. Thursday, March 20, 2025 C++ Programming Language 4
Numeric Values In mathematics, integers are unbounded; said another way, the set of mathematical integers is infinite. In C++ the range of integers is limited because all computers have a finite amount of memory. The exact range of integers supported depends on the computer system and particular C++ compiler. C++ on most 32-bit computer systems can represent integers in the range 2,147,483,648 to +2,147,483,647. #include <iostream> int main() { cout<< -3000000000 << \n ;} Negative three billion is too large for 32-bit integers, however, and the program s output is obviously wrong: 1294967296 C++ Programming Language 5 Thursday, March 20, 2025
Why do we need variable declaration? Answer: memory Here is how C++ deals with memory Imagine the system memory as a nice, flat stretch of beach You want a variable, you need to dig a hole in the sand and dump the value in How big a hole? Thursday, March 20, 2025 C++ Programming Language 6
Declare variable before use Declare a variable to be of type integer, the compiler allocates a memory location for that variable. The size of this memory location depends on the type of the compiler. When you declare a variable, you are telling the compiler the size of value the variable may hold (its type) You cannot change the type of value a variable can hold once declared. Thursday, March 20, 2025 C++ Programming Language 7
Must declare before use Every variable must be declared before it can be used (its type must be indicated) Syntax: <variable_type> <variable_name> [ =<initial_value> ]; Example: int length, width = 5, height = 10; Thursday, March 20, 2025 Data Structure 8
Common types, regular C int : an integer, usually 4 bytes float: float, usually 4 bytes double : float, usually 8 bytes char : single char, value in single quotes Thursday, March 20, 2025 C++ Programming Language 9
Variables and Assignment In algebra, variables are used to represent numbers. The same is true in C++, except C++ variables also can represent values other than numbers. #include<iostream> int main() { int x; x = 10; cout<< x << '\n';} C++ supports types other than integers, and some types require more or less space in the computer s memory. The compiler uses the declaration to reserve the proper amount of memory to store the variable s value. The declaration enables the compiler to verify the programmer is using the variable properly within the program. C++ Programming Language 10 Thursday, March 20, 2025
Variables and Assignment x = 10; This is an assignment statement. An assignment statement associates a value with a variable. The key to an assignment statement is the symbol = which is known as the assignment operator. We need not be concerned about where the variable is stored in memory; the compiler takes care of that detail. After we declare a variable we may assign and reassign it as often as necessary. cout<< x << '\n'; In C++, the statement 5 = x; attempts to reassign the value of the literal integer value 5, but this cannot be done, because 5 is always 5 and cannot be changed. Such a statement will produce a compiler error: left operand must be l-value Thursday, March 20, 2025 C++ Programming Language 11
Variables and Assignment Variables can be reassigned different values as needed. #include <iostream> int main() { int x; x = 10; cout<< x << '\n'; x = 20; cout<< x << '\n'; x = 30; out<< x << '\n';} #include <iostream> int main() { int x = 10; cout<< x << '\n'; } This combined declaration and immediate assignment is called initialization. Multiple variables of the same type can be declared and, if desired, initialized in a single statement. The following statements declare three variables in one declaration statement: int x, y, z; Thursday, March 20, 2025 C++ Programming Language 12
Identifiers While mathematicians are content with giving their variables one- letter names like x, programmers should use longer, more descriptive variable names. Names such as altitude, sum, and user_name are much better than the equally permissible a, s, and u. A variable s name should be related to its purpose within the program. Good variable names make programs more readable by humans. Since programs often contain many variables, well-chosen variable names can render an otherwise obscure collection of symbols more understandable. Thursday, March 20, 2025 C++ Programming Language 13
Identifiers C++ has strict rules for variable names. A variable name is one example of an identifier. An identifier is a word used to name things. One of the things an identifier can name is a variable. Identifiers have the following form: 1. Identifiers must contain at least one character: the first character must be an alphabetic letter (upper or lower case) or the underscore ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_. The remaining characters (if any) may be alphabetic characters (upper or lower case), the underscore, or a digit. ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123 456789 2. No other characters (including spaces) are permitted in identifiers. 3. A reserved word cannot be used as an identifier. Examples of valid and invalid identifiers: All of the following words are valid identifiers and so qualify as variable names: x, x2, total, port_22, and FLAG. None of the following words are valid identifiers: sub-total (dash is not a legal symbol in an identifier), first entry (space is not a legal symbol in an identifier), 4all (begins with a digit), #2 (hash sign is not a legal symbol in an identifier), and class (class is a reserved word). Thursday, March 20, 2025 C++ Programming Language 14
Identifiers The following table lists all the C++ reserved words. If you accidentally attempt to use one of the reserved words in a program as a variable name, the compiler will issue an error. C++ is a case-sensitive language. This means that capitalization matters. If is a reserved word, but none of If, IF, or iF are reserved words. Identifiers are case sensitive also; the variable called Name is different from the variable called name. Thursday, March 20, 2025 C++ Programming Language 15
Identifiers alignas alignof and and_eq asm auto bitand bitor bool break case catch char char16_t char32_t class compl const constexpr const_cast continue decltype default delete double do dynamic_cast else enum explicit export extern false float for friend goto if inline int long mutable namespace new noexcept not not_eq nullptr operator or or_eq private protected public register reinterpret_cast return short signed sizeof static static_assert static_cast struct switch template this thread_local throw true try typedef typeid typename union unsigned using virtual void volatile wchar_t while xor xor_eq Thursday, March 20, 2025 C++ Programming Language 16
Additional Integer Types C++ supports several other integer types. The type short int, which may be written as just short, represents integers that may occupy fewer bytes of memory than the int type The long int type, which may be written as just long, may occupy more storage than the int type and thus be able to represent a larger range of values. The long long int type, or just longlong, may be larger than a long. The C++ standard guarantees the following relative ranges of values hold: short int long int C++ provides integer-like types that exclude negative numbers. These types include the word unsigned in their names, meaning they do not allow a negative sign. The C++ standard guarantees the following relative ranges of unsigned values: unsigned short unsigned unsigned long long int long int long unsigned long Thursday, March 20, 2025 C++ Programming Language 17
Additional Integer Types Type Name Short Name Storage Smallest Magnitude Largest Magnitude short int short 2 bytes 32; 768 32; 767 int int 4 bytes 2; 147; 483; 648 2; 147; 483; 647 long int long 4 bytes 2; 147; 483; 648 2; 147; 483; 647 9; 223; 372; 036; 854; 775; 808 9; 223; 372; 036; 854; 775; 807 long longint long long 8 bytes unsigned short unsigned short 2 bytes 0 65; 535 unsigned int unsigned 4 bytes 0 4; 294; 967; 295 unsigned long int unsigned long 4 bytes 0 4; 294; 967; 295 18; 446; 744; 073; 709; 551; 615 unsigned long longint unsigned long long 8 bytes 0 Thursday, March 20, 2025 C++ Programming Language 18
Floating-point Types Many computational tasks require numbers that have fractional parts. For example, the formula from mathematics to compute the area of a circle given the circle s radius, involves the value p, which is approximately 3.14159. C++ supports such non-integer numbers, and they are called floating-point numbers. The float type represents single-precision floating-point values that are less precise. Table 3.3 provides some information about floating- point values as commonly implemented on 32-bit computer systems. Floating point numbers can be both positive and negative. #include <iostream> int main() { double pi = 3.14159; cout<< "Pi = " << pi << '\n'; cout<< "or " << 3.14 << " for short" << '\n';} Thursday, March 20, 2025 C++ Programming Language 19
Additional Integer Types Type Storage Smallest Magnitude Largest Magnitude Minimum Precision float 4 bytes 1:17549 10 38 3:40282 10+38 6 digits double 8 bytes 2:22507 10 308 1:79769 10+308 15 digits long double 8 bytes 2:22507 10 308 1:79769 10+308 15 digits Characteristics of Floating-point Numbers on 32-bit Computer Systems Thursday, March 20, 2025 C++ Programming Language 20
Floating-point Types We can express floating-point numbers in scientific notation. Since most programming editors do not provide superscripting and special symbols like , C++ slightly alters the normal scientific notation. The number 6.022x1023 is written 6.022e23. The number to the left of the e (we can use capital E as well) is the mantissa, and the number to the right of the e is the exponent of 10. #include <iostream> int main() { double avogadros_number = 6.022e23, c = 2.998e8; cout<< "Avogadro's number = " <<avogadros_number<< '\n'; cout<< "Speed of light = " << c << '\n'; } Thursday, March 20, 2025 C++ Programming Language 21
Constants C++ supports named constants. Constants are declared like variables with the addition of the const keyword: const double PI = 3.14159; Once declared and initialized, a constant can be used like a variable in all but one way a constant may not be reassigned. It is illegal for a constant to appear on the left side of the assignment operator (=) outside its declaration statement. A subsequent statement like PI = 2.5; would cause the compiler to issue an error message: PI : you cannot assign to a variable that is const and fail to compile the program. Thursday, March 20, 2025 C++ Programming Language 22
Strings A string is a sequence of characters that is treated as a single data item. A string variable is a variable that stores a string constant. characters surrounded by double quotation marks. format specified for output converts the internal representation of data to readable characters.( %f ) for example, City tax is 450.000000 dollars. backslash character can be used as a continuation character: cout<< THIS PROGRAM COMPUTES \ CITY INCOME TAX ; Thursday, March 20, 2025 C++ Programming Language 23
Strings how to declare string variables. Begin the declaration with the keyword char, Char report_header [41] To initialize a string variable at complie char report_header [41] = Annual Report time, Thursday, March 20, 2025 C++ Programming Language 24
Statements A statement is a specification of an action to be taken by the computer as the program executes. Compound Statements: is a list of statements enclosed in braces, { } Thursday, March 20, 2025 C++ Programming Language 25
C++ Keywords Keywords are predefined reserved identifiers that have special meanings. They cannot be used as identifiers in your program. C reserved words must be typed fully in lowercase. The reserved words of C++ may be conveniently placed into several groups. In the first group we put those that were also present in the C programming language and have been carried over into C++. There are 32 of these, and here they are: Thursday, March 20, 2025 C++ Programming Language 26
C++ Keywords auto const double float int short struct unsigned break continue else for long signed switch void case default enum goto register sizeof typedef volatile char do extern if return static union while Thursday, March 20, 2025 C++ Programming Language 27
C++ Keywords There are another 30 reserved words that were not in C, are therefore new to C++, and here they are: asm dynamic_cast reinterpret_cast try new static_ cast typeid catch false operator template typename class friend private this using const_cast inline public throw virtual delete mutable protected true wchar_t namespace bool explicit Thursday, March 20, 2025 C++ Programming Language 28
cout, more detail Thursday, March 20, 2025 C++ Programming Language 29
Many descriptors %s string %d decimal %e floating point exponent %f floating point decimal %u unsigned integer and others Thursday, March 20, 2025 C++ Programming Language 30
Full Format string The format string contains a set of format descriptors that describe how an object is to be printed % -#0 12 .4 h d Conversion Type (d for decimal) size modifier (h for short int) start specification Width Precision Flags Thursday, March 20, 2025 C++ Programming Language 31
Examples cout<< %f\n ,M_PI; 3.141593 cout<< %.4f\n ,M_PI; 3.1416 (4 decimal points of precision, with rounding) cout<< %10.2f\n ,M_PI; 3.14 (10 spaces in total including the number and the decimal point) cout<< %10.2f is PI\n ,M_PI; 3.14 is PI Thursday, March 20, 2025 C++ Programming Language 32
cin cout<< Please enter the yards of pipe used: ; cin>> %f ,&yardsOfPipe; cin is an input routine useful for reading in string input and doing conversion to the correct type, all at once syntax is kind of like cout beware the use of the & operator!!! Thursday, March 20, 2025 C++ Programming Language 33
Basic form To understand input, it is probably better to start with an example. Cin>> %d, %f , &myInt, &myFloat; is waiting for input of the exact form 25, 3.14159 Thursday, March 20, 2025 C++ Programming Language 34
Arithmetic Expression Thursday, March 20, 2025 C++ Programming Language 35
Types determine results For integers: +,-,*,/ all yield integers. Thus division can lead to truncation (2/3 has value 0). % gives the remainder For floats: +,-,*,/ all work as advertised. No remainder. Thursday, March 20, 2025 C++ Programming Language 36
Mixed computation As with most languages, C++ expects to work with like types. 1 + 1, 3.14. + 4.56 When mixing, usually errors except where C++ can help It will promote a value to a more detailed type when required 1 + 3.14 yields a float (1 promoted to 1.0) Thursday, March 20, 2025 C++ Programming Language 37
coercion, cast Explicit type conversion: (double) 3 convert int 3 to double 3.0. Note the parens! (int) 3.14 convert 3.14 to int. No rounding! Makes a new value, does not affect the old one! Thursday, March 20, 2025 C++ Programming Language 38
Example #include <stdio.h> int main(){ // const means the variable value cannot be changed from this initial setting const int A = 3, B = 4, C = 7; const double X = 6.5, Y = 3.5; cout<< n*** Integer computations ***\n\n"); cout<< %d + %d equals %d\n",A,B,A+B; cout<<"%d - %d equals %d\n",A,B,A-B; cout<<"%d * %d equals %d\n",A,B,A*B; cout<<"%d / %d equals %d with remainder %d\n",A,B,A/B,A%B; cout<<"\n"; cout<<"\n*** Real computations ***\n\n"; cout<<"%f + %f equals %f\n",X,Y,X+Y; cout<<"%f - %f equals %f\n",X,Y,X-Y cout<<"%f * %f equals %f\n",X,Y,X*Y; cout<<"%f / %f equals %f\n",X,Y,X/Y; Thursday, March 20, 2025 C++ Programming Language 39
Example cout<<"\n*** Mixed-type computations ***\n\n"); cout<<"%f + %d equals %f\n",X,A,X+A; cout<<"%f - %d equals %f\n",X,A,X-A; cout<<"%f * %d equals %f\n",X,A,X*A; cout<<"%f / %d equals %f\n",X,A,X/A; cout<<"\n*** Compound computations ***\n\n"; cout<<"%d + %d / %d equals %d\n",C,B,A,C+B/A; cout<<"(%d + %d) / %d equals %d\n",C,B,A,(C+B)/A; cout<<"\n"; cout<<"%d / %d * %d equals %d\n",C,B,A,C/B*A; cout<<"%d / (%d * %d) equals %d\n",C,B,A,C/(B*A); cout<<"\n*** Type conversions ***\n\n"; cout<<"Value of A: %d\n",A; cout<<"Value of (double)A: %f\n",(double)A; cout<<"Value of X: %f\n",X; cout<<"Value of (int)X: %d\n",(int)X; return 0; } Thursday, March 20, 2025 C++ Programming Language 40
Example // Addition program #include <iostream.h> int main() { int integer1, integer2, sum; /*declaration */ cout<<"Enter first integer\n ; /* prompt */ sin>>"%d", &integer1; /* read an integer */ cout<<"Enter second integer\n ; /* prompt */ cin>>"%d", &integer2; /* read an integer */ sum = integer1 + integer2; /* assignment of sum */ cout<<"Sum is %d\n", sum ; /* print sum */ return 0; /* indicate that program ended successfully */ } Thursday, March 20, 2025 C++ Programming Language 41
Example #include <iostream.h> int main (void) { double number; cout<< Enter a number : ; cin<< %lf , &number; Inverse = 1.0 / number ; cout<< Inverse of %f is %f << number, inverse; } Thursday, March 20, 2025 C++ Programming Language 42 42