Chap01b - Basic Elements of C++
Chap01b - Basic Elements of C++
• 2 types of comments:
- Block comment ( /* and */ )
- Line comment ( // )
Block Comment
/* This is a block comment that
covers two lines. */
/*
This is a very common style to put the opening token
on a line by itself, followed by the documentation and
then the closing token on a separate line. Some
programmers also like to put asterisks at the
beginning of each line to clearly mark the comment.
*/
Line Comment
totalSales Yes
total_Sales Yes
pi ?
Assign values to variables
Memory:
char gender;
int year;
float price; Assign (store) gender ‘F’
double pi; values to
variables
gender = 'F'; year 2008
year = 2008;
price = 25.99;
price 25.99
pi = 3.1415926235898;
• Array of characters
• Example:
o char name[21];
o Indicates the string contains 20 characters in
length plus one terminating null character (\0)
char space = ‘ ’;
You may replace this with string space = “
”;
cout << day << space << date;
Data Type – String Class
Defined Constant
•A defined constant is a name that replaces the
constant name in the program body with the
expression associated with that constant name.
•The preprocessor command #define is used.
•Examples:
#define PI 3.14159
#define YEAR 2019
#define PET_NAME “Doggy”
#define GOOD_GRADE ‘A’
Declare / Define Constants
// EXAMPLE of Defined Constant
#include <iostream>
using namespace std;
#define GRAMS_PER_KG 1000
int main() {
double grams, kgs;
cout << kgs << “KG is equal to ” << grams << “grams” << endl;
return 0;
}
Program Statements
E.g., int a;
double x, b;
x = a + b;
High
Low
• Example 1: • Example 2:
char c = ‘A’; char c = ‘A’;
int i = 1234; int k = 65;
i = c; // value of i is c = k + 1; // value of c is
65 ‘B’
• Example 3:
char c = ‘A’;
int i = 3650;
short s = 78;
long double d = 3458.0004;
cout << i * s; // result is in int
cout << d * c; // result is in long
Explicit Type Conversion
• Cast operator is used to convert data type from
one type to another type
• Specify new type in parenthesis before the value
that need to be converted
✔ (double) number;
• E.g.
int no1, no2;
double X = (double)(no1 / no2);
double X = (double)no1 / no2;
double X = static_cast<double>(no1)/no2;
Question
• State the output of the following
int num1 = 9, num2 = 2;
2. double y = (double)(num1/num2);