0% found this document useful (0 votes)
85 views3 pages

CC 101 - Basics in C++

The document defines several key concepts in C++ programming: 1) An identifier is a name used to label variables, functions, etc. and must start with a letter or underscore followed by letters, digits, or underscores. 2) A variable is a memory location that can store and change data, and must be declared with a name and data type before use. 3) Input and output in C++ is through streams, and the << operator inserts values into the output stream cout to display results.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views3 pages

CC 101 - Basics in C++

The document defines several key concepts in C++ programming: 1) An identifier is a name used to label variables, functions, etc. and must start with a letter or underscore followed by letters, digits, or underscores. 2) A variable is a memory location that can store and change data, and must be declared with a name and data type before use. 3) Input and output in C++ is through streams, and the << operator inserts values into the output stream cout to display results.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

HANDOUT IN INTRODUCTION TO COMPUTING

What is an Identifier?
 An identifier is the name to denote labels, types, variables, What is an Expression in C++?
constants or functions, in a C++ program.  An expression is a valid arrangement of variables, constants,
 C++ is a case-sensitive language. and operators.
 Work is not work  In C++, each expression can be evaluated to compute a
value of a given type
 In C++, an expression can be:
 Identifiers should be descriptive using meaningful identifiers  A variable or a constant (count, 100)
is a good programming practice  An operation (a + b, a * 2)
 Function call (getRectangleArea(2, 4))
Rules in Naming Identifiers
Assignment Operator
 Identifiers must be unique  An operator to give (assign) a value to a variable.
 Identifiers cannot be reserved words (keywords)  Denote as ‘=‘
double main return  Only variable can be on the left side.
 Identifier must start with a letter or underscore, and be  An expression is on the right side.
followed by zero or more letters (A-Z, a-z), digits (0-9), or  Variables keep their assigned values until changed by
underscores another assignment statement or by reading in a new value.
VALID
age_of_dog _taxRateY2K Assignment Operator Syntax
PrintHeading ageOfHorse
NOT VALID  Variable = Expression
age# 2000TaxRate Age-Of-Dog main  First, expression on right is evaluated.
 Then the resulting value is stored in the memory
Primitive Data Types in C++ location of Variable on left.
 Integral Types NOTE: An automatic type coercion occurs after evaluation but before
 represent whole numbers and their negatives the value is stored if the types differ for Expression and Variable
 declared as int, short, or long
 Character Types Input and Output
 represent single characters
 declared as char  C++ treats input and output as a stream of characters.
 Stored by ASCII values  stream: sequence of characters (printable or nonprintable)
 Boolean Type  The functions to allow standard I/O are in iostream header
 declared as bool file or iostream.h.
 has only 2 values true/false
 Thus, we start every program with
 will not print out directly
#include <iostream>
 Floating Types using namespace std;
 represent real numbers with a decimal point
 declared as float, or double Include Directives and Namespaces
 Scientific notation where e (or E) stand for “times 10 to
the ” (.55-e6)
 include: directive copies that file into your program
 namespace: a collection of names and their definitions.
Samples of C++ Data Values
Allows different namespaces to use the same names without
confusion
int sample values
4578 -4578 0
Insertion Operator ( << )
bool values
true false  Variable cout is predefined to denote an output stream that
goes to the standard output device (display screen).
float sample values  The insertion operator << called “put to” takes 2 operands.
95.274 95.0 .265  The left operand is a stream expression, such as cout. The
right operand is an expression of simple type or a string
char sample values constant.
‘B’ ‘d’ ‘4’ ‘?’ ‘*’
Output Statements
What is a Variable?
SYNTAX
 A variable is a memory address where data can be stored cout << Expression << Expression . . . ;
and changed.
 cout statements can be linked together using << operator.
 Declaring a variable means specifying both its name and its  These examples yield the same output:
data type. cout << “The answer is “ ;
cout << 3 * 4 ;
What Does a Variable Declaration Do?

 A declaration tells the compiler to allocate enough memory cout << “The answer is “ << 3 * 4 ;
to hold a value of this data type, and to associate the
identifier with this location. Output Statements (String constant)

Variable Declaration  String constants (in double quotes) are to be printed as is,
without the quotes.
 All variables must declared before use. cout<<“Enter the number of candy bars ”;
 At the top of the program OUTPUT: Enter the number of candy bars
 Just before use.  “Enter the number of candy bars ” is called a prompt.
 Commas are used to separate identifiers of the same type.  All user inputs must be preceded by a prompt to tell the user
 int count, age; what is expected.
 Variables can be initialized to a starting value when they are  You must insert spaces inside the quotes if you want them in
declared the output.
 int count = 0;  Do not put a string in quotes on multiple lines.
 int age, count = 0;
Output Statements (Expression)
 All expressions are computed and then outputted.
cout << “The answer is ” << 3 * 4 ;
OUTPUT: The answer is 12  Mixed type expressions: Both must be int to return int,
Escape Sequences otherwise float.
Type compatibilities (Implicit Conversion)
 The backslash is called the escape character.
 It tells the compiler that the next character is “escaping” its  The compiler tries to be value-preserving.
typical definition and is using its secondary definition.  General rule: promote up to the first type that can contain the
 Examples: value of the expression.
 new line: \n  Note that representation doesn’t change but values can be
 horizontal tab: \t altered .
 backslash: \\  Promotes to the smallest type that can hold both values.
 double quote \”  If assign float to int will truncate

Newline int_variable = 2.99; // results in 2 being stored in int_variable


 cout<<“\n” and cout<<endl both are used to insert a blank
line.  If assign int to float will promote to double:
 Advances the cursor to the start of the next line rather than
to the next space. double dvar = 2; // results in 2.0 being stored in dvar
 Always end the output of all programs with this statement.
Type compatibilities (Explicit Conversion)
Extraction Operator (>>)  Casting - forcing conversion by putting (type) in front of
variable or expression. Used to insure that result is of
 Variable cin is predefined to denote an input stream from the desired type.
standard input device (the keyboard)  Example: If you want to divide two integers and get a real
 The extraction operator >> called “get from” takes 2 result you must cast one to double so that a real divide
operands. The left operand is a stream expression, such as occurs and store the result in a double.
cin--the right operand is a variable of simple type.
 Operator >> attempts to extract the next item from the input int x=5, y=2; double z; z = static_cast <double>(x)/y; // 2.5
stream and store its value in the right operand variable. int x=5, y=2; double z; z = (double)x/y; //
2.5
Input Statements int x=5, y=2; double z; z = static_cast <double>(x/y) ; // 2.0

SYNTAX  converts x to double and then does mixed division, not


integer divide
cin >> Variable >> Variable . . . ;  static_cast<int> (z) - will truncate z
 static_cast <int> (x + 0.5) - will round positive x {use () to
 cin statements can be linked together using >> operator. cast complete expression)
 These examples yield the same output:  Cast division of integers to give real result:

cin >> x; int x=5, y=2; double z; z = static_cast <double>(x/y) ; // 2.0


cin >> y;
Arithmetic Operators
cin >> x >> y;
 Operators: +, -, * /
How Extraction Operator works?  For floating numbers, the result as same as Math operations.
 Note on integer division: the result is an integer. 7/2 is 3.
 Input is not entered until user presses <ENTER> key.  % (remainder or modulo) is the special operator just for
 Allows backspacing to correct. integer. It yields an integer as the result. 7%2 is 1.
 Skips whitespaces (space, tabs, etc.)  Both / and % can only be used for positive integers.
 Multiple inputs are stored in the order entered:  Precedence rule is similar to Math.

cin>>num1>>num2; Arithmetic Expressions

User inputs: 3 4  Arithmetic operations can be used to express the


Assigns num1 = 3 and num2 = 4 mathematic expression in C++:

Numeric Input b 2  4ac b*b  4*a *c


 Leading blanks for numbers are ignored. x( y  z )
1
x * ( y  z)
 If the type is double, it will convert integer to double.
 Keeps reading until blank or <ENTER>. x2  x  3 1 /( x * x  x  3)
 Remember to prompt for inputs ab
cd
(a  b) /( c  d )
C++ Data Type String
Simple Flow of Control
 A string is a sequence of characters enclosed in double
quotes  Three processes a computer can do:
 string sample values  Sequential
“Hello” “Year 2000” “1234”  expressions, insertion and extraction operations
 The empty string (null string) contains no displayed  Selection (Branching)
characters and is written as “ ”.  if statement, switch statement
 string is not a built-in (standard) type  Repetition/Iteration (Loop)
 it is a programmer-defined data type  while loop, do-while loop, for loop
 it is provided in the C++ standard library
 Need to include the following two lines: bool Data Type
#include <string>
using namespace std;  Type bool is a built-in type consisting of just 2 values, the
 string operations include constants true and false
 comparing 2 string values  We can declare variables of type bool
 searching a string for a particular character bool hasFever; // true if has high temperature
 joining one string to another (concatenation) bool isSenior; // true if age is at least 55
 The value 0 represents false
Type compatibilities  ANY non-zero value represents true

 Warning: If you store values of one type in variable of Boolean Expression


another type the results can be inconsistent:
 Can store integers in floating point or in char (assumes  Expression that yields bool result
ASCII value)  Include:
 bool can be stored as int: (true = nonzero, false = 0)  6 Relational Operators
 Implicit promotion: integers are promoted to doubles < <= > >= == !=
double var = 2; // results in var = 2.0  3 Logical Operators
 On integer and doubles together: ! && ||
 Separate processes with blank lines
 Blank lines are also ignored and are used to increase
readability.
Relational Operators  indent statements within statements (loop body)
 Comments:
 are used in boolean expressions of form:  // tells the computer to ignore this line.
ExpressionA Operator ExpressionB  for internal documentation. This is done for program
temperature > humidity clarity and to facilitate program maintenance.
B * B - 4.0 * A * C > 0.0
abs (number) == 35 General rules for Comments
initial != ‘Q’
Notes:  Place a comment at the beginning of every file with the file
 == (equivalency) is NOT = (assignment) name, version number, a brief program description,
 characters are compared alphabetically. However, programmer’s name.
lowercase letters are higher ASCII value.  Place a descriptive comment after each variable declared.
 An integer variable can be assigned the result of a logical  Use a blank line before and after variable declarations
expression  Place a descriptive comment and a blank line before each
 You cannot string inequalities together: subtask.
 Bad Code: 4<x<6 Good Code: (x > 4) &&(x < 6)
Constants
int x, y ;
x = 4;  Syntax: const type identifier = value;
y = 6;  Ex: const double TAX_RATE = 0.08;
EXPRESSION VALUE  Convention: use upper case for constant ID.
x<y true
x+2<y false Why use constants?
x != y true
x + 3 >= y true
 Clarity: Tells the user the significance of the number. There
y == x false
may be the number 0.08 elsewhere in the program, but you
y == x+2 true
know that it doesn’t stand for TAXRATE.
y=x+3 7
 Maintainability. Allows the program to be modified easily.
y=x<3 0
 Ex: Program tax compute has const double
y=x>3 1
TAXRATE=0.0725. If taxes rise to 8%, programmer
only has to change the one line to const double
Logical Operators
TAXRATE=0.08
 Safety: Cannot be altered during program execution
 are used in boolean expressions of form:
 Notes:
Increment and Decrement Operators
 Highest precedence for NOT, AND and OR are low
precedence.
 Denoted as ++ or --
 Associate left to right with low precedence. Use parenthesis
to override priority or for clarification  Mean increase or decrease by 1
o x && y || z will evaluate “x && y ” first  Pre increment/decrement: ++a, --a
o x && (y || z) will evaluate “y || z” first  Increase/decrease by 1 before use.
 Post increment/decrement: a++, a--
 Increase/decrease by 1 after use.
int age ;
bool isSenior, hasFever ;  Pre and Post increment/decrement yield different results
float temperature ; when combining with another operation.
age = 20;
temperature = 102.0 ;
isSenior = (age >= 55) ; // isSenior is false
hasFever = (temperature > 98.6) ; // hasFever is true

EXPRESSION VALUE
isSenior && hasFever false
isSenior || hasFever true
!isSenior true
!hasFever false

Precedence Chart

Highest
++, --, !, - (unary minus), + (unary plus)
*, /, %
+ (addition), - (subtraction)
<<, >>
<, <=, >, >=
==, !=
&&
||
=
Lowest

Boolean Expression (examples)

 taxRate is over 25% and income is less than $20000


(taxRate > .25) && (income < 20000)

 temperature is less than or equal to 75 or humidity is less


than 70%
(temperature <= 75) || (humidity < .70)

 age is between 21 and 60


(age >= 21) && (age <= 60)
 age is 21 or 22
(age == 21) || (age == 22)

Program Style

 Indenting:

You might also like