Unit1 CIntro
Unit1 CIntro
C/C++ Basics
Mark Redekopp
2
Announcements
• Ensure you can gain access to Vocareum.com
Software Process
Std C++ & Other
Libraries
#include <iostream>
using namespace std;
int main() 1110 0010 0101 1001
0110 1011 0000 1100
{ int x = 5; 0100 1101 0111 1111 Load &
cout << "Hello" g++ 1010 1100 0010 1011 Execute
<< endl; 0001 0110 0011 1000
cout << "x=" << x;
return 0;
Compiler Executable
}
Binary Image
C++ file(s) ("test")
(test.cpp)
1 Edit & write 2 Compile & fix compiler 3 Load & run the
code errors executable program
6
Software Process
Std C++ & Other
Libraries
#include <iostream>
using namespace std;
int main() 1110 0010 0101 1001
0110 1011 0000 1100
{ int x = 5; 0100 1101 0111 1111 Load &
cout << "Hello" g++ 1010 1100 0010 1011 Execute
<< endl; 0001 0110 0011 1000
cout << "x=" << x;
return 0;
Compiler Executable
}
Binary Image
C++ file(s) -g = Enable Debugging ("test")
(test.cpp) -Wall =Show all warnings
-o test = Specify Output executable name
1 Edit & write 2 Compile & fix compiler 3 Load & run the
code errors executable program
7
MODULE 1:
DATA REPRESENTATION AND TYPES
8
Memory
• Recall all information in a computer is
stored in memory Address Data
• Memory consists of cells that each store a 0 11010010
group of bits (usually, 1 byte = 8 bits) 1 01001011
5
3
4
2 F
stored 5 Memory
Device
9
sequences of bits?
– Let's learn about number systems
0101110 11010001 10110101 01110111
A word
10
Binary Numbers
• To represent numbers, there is an implicit weight or
place value for each 1 or 0
• The weights are the powers of 2
– 20, 21, 22, 23, …
• The value of the number is the sum of the weights in
which there is a 1
0 1 1 0 0 1 1 1 = ______
128 64 32 16 8 4 2 1
1 0 0 1 1 0 0 1 = ______
128 64 32 16 8 4 2 1
12
Combinations
• Because we have a finite 0 00 000 0000
number of bits, we can only 1 01 001 0001
10 010 0010
make a finite set of numbers 1-bit
(2 #s) 11 011 0011
• How many numbers 2-bits 100 0100
(combinations) can we make (4 #s) 101 0101
110 0110
with n bits? 111 0111
– ________ 3-bits 1000
(8 #s) 1001
– Use the examples on the right to
1010
induce the relationship of how
1011
many #s can be formed with n-bits 1100
1101
1110
1111
4-bit
(16 #s)
13
Sign
• Is there any limitation if we only use the powers of
some base as our weights?
– Can't make negative numbers
• What if we change things
– How do humans represent negative numbers?
– Can we do something similar?
Text
• Text characters are usually represented with
some kind of binary code (mapping of
character to a binary number such as 'a' =
01100001 bin = 97 dec)
• ASCII = Traditionally an 8-bit code
– How many combinations (i.e. characters)?
– English only
• UNICODE = 16-bit code
– How many combinations?
– Most languages w/ an alphabet
• In C/C++ a single printing/text character
must appear between single-quotes (')
– Example: 'a', '!', 'Z'
http://www.theasciicode.com.ar/
17
01000001 = ?
Unsigned
Binary system ASCII
system
6510 ‘A’ASCII
18
MODULE 2:
CONSTANTS, VARIABLES, AND
EXPRESSIONS
19
Constants
• Integer: 496, 10005, -234
• Double: 12.0, -16., 0.23, -2.5E-1, 4e-2
• Characters (char type): enclosed in single quotes
– Printing characters: 'a', '5', 'B', '!'
– Non-printing special characters use "escape" sequence (i.e. preceded by a \ ):
'\n' (newline/enter), '\t' (tab) , '\\' (slash), '\'' (apostrophe)
• C-Strings
– 0 or more characters between double quotes 0 104 ‘h’
1 105 ‘i’
"hi1\n", "12345", "b", "\tAns. is %d" 2 49 ‘1’
Text/Character(s) Logical
Number for display (true/false) value
Contains a
decimal/fractional Integer Single Many
value
Positive Possibly
only negative
Use an… Use an…
unsigned
double int int char string bool
3.0, 0, 0,
'a', '1', "Hi", true,
3.14159, 2147682, -2147682,
'.' "2020" false
6.27e23 … 2147682
22
Arithmetic Operators
• Addition, subtraction, multiplication work as expected for
both integer and floating point types
• Division works ‘differently’ for integer vs. doubles/floats
• Modulus is only defined for integers
Operator Name Example
+ Addition 2+5
- Subtraction 41 - 32
* Multiplication 4.23 * 3.1e-2
/ Division 10 / 3 (=3)
(Integer vs. Double division) 10.0 / 3 (=3.3333)
% Modulus (remainder) 17 % 5
[for integers only] (result will be 2)
17 % 10 = __
4 % 7 = __
24
Precedence
• Order of operations/
evaluation of an expression
• Top Priority = highest
(done first)
• Notice operations with the
same level or precedence
usually are evaluated left to
right (explained at bottom)
• Evaluate:
– 2*-4-3+5/2;
• Tips:
– Use parenthesis to add clarity
– Add a space between literals January 2007 v2.2. Copyright °c 2007 Joseph H. Silverman
Permission is granted to make and distribute copies of this card pro-
(2 * -4) – 3 + (5 / 2) vided the copyright notice and this permission notice are preserved on
all copies.
Send comments and corrections to J.H. Silverman, Math. Dept., Brown
Univ., Providence, RI 02912 USA. [email protected]
25
Division
• Computers perform division differently based on the
type of values used as inputs
• Integer Division:
– When dividing two integral values, the result will also be
an integer (any remainder/fraction will be dropped)
– 10 / 4 = 2 52 / 10 = 5 6/7=0
• Floating-point (Double) & Mixed Division
– 10.0 / 4.0 = 2.5 52.0 / 10 = 5.2 6 / 7.0 = 0.8571
– Note: If one input is a double, the other will be promoted
temporarily to compute the result as a double
26
Exercise Review
• Evaluate the following:
– 25 / 3
– 17 + 5 % 2 – 3
– 28 - 5 / 2.0
Exercises from: D.S. Malik, C++ Programming, 5th Ed., Ch. 2, Q6.
27
C/C++ Variables
#include <iostream>
using namespace std;
• Variables allow us to
int main()
– Store a value until it is needed and change its { // Sample variable declarations
value potentially many times char c = 'A';
int x; // uninitialized variables
– Associate a descriptive name with a value // will have a (random) garbage
// value until we initialize it
• Variables are just memory locations that are x = 1; // Initialize x's value to 1
reserved to store one piece of data of }
c = 'B'; // Change c's value to 'B'
C/C++ Variables
• Variables have a: What's in a name?
To give descriptive names we often
– type [int, char, unsigned int, float, double, etc.] need to use more than 1 word/term.
– name/identifier that the programmer will use to But we can't use spaces in our
identifier names. Thus, most
reference the value in that memory location [e.g. x, programmers use either camel-case or
snake-case to write compound names
myVariable, num_dozens, etc.] Camel case: Capitalize the first letter
• Identifiers must start with [A-Z, a-z, or an underscore ‘_’] and can of each word (with the possible
then contain any alphanumeric character [0-9, A-Z, a-z, _] (but no exception of the first word)
punctuation other than underscores) myVariable, isHighEnough
Snake case: Separate each word with
• Use descriptive names (e.g. numStudents, doneFlag) an underscore '_'
• Avoid cryptic names ( myvar1, a_thing ) my_variable, is_high_enough
Evaluate 5 + 3/2
• The answer is 6.5 ??
32
Casting
• To achieve the correct answer for 5 + 3 / 2
• Could make everything a double
– Write 5.0 + 3.0 / 2.0 [explicitly use doubles]
• Could use implicit casting (mixed expression)
– Could just write 5 + 3.0 / 2
• If operator is applied to mixed type inputs, less expressive type is automatically promoted
to more expressive (int is promoted to double)
MODULE 3:
C++ I/O (INPUT/OUTPUT)
34
I/O Streams
• I/O is placed in temporary buffers/streams by the OS/C++ libraries
• cin goes and gets data from the input stream (skipping over preceding
whitespace then stopping at following whitespace)
• cout puts data into the output stream for display by the OS (a flush forces
the OS to display the contents immediately)
#include<iostream>
using namespace std;
int main()
{
cout << "It was the" << endl;
cout << "best of times.";
7 5 y ... input stream: }
output stream:
#include<iostream>
using namespace std; I t w a s t h e \n b
int main()
{ It was the
int x;
cin >> x;
return 0;
output stream:
}
4
C++ Output
• Include <iostream> (not iostream.h)
#include<iostream>
• Add using namespace std; at top of file using namespace std;
C++ Input
#include <iostream>
#include <string>
• cin (character input) object used to using namespace std;
int main(int argc, char *argv[])
accept input from the user and write {
int x;
the value into a variable char c;
string mystr;
– Use the '>>' operator to separate any number double y;
of variables or constants you want to read in cout << "Enter an integer, character,
string, and double separated by
– Every '>>' will skip over any leading spaces:" << endl;
whitespace looking for text it can convert to
cin >> x >> c >> mystr >> y;
the variable form, then stop at the trailing
whitespace cout << "x = " << x << " c = ";
cout << c << "mystr is " << mystr;
cout << "y is " << y << endl;
return 0;
}
cin
#include<iostream>
c= 0 y= 0.0 using namespace std;
int main()
• If the user types in {
char c = 0;
double y = 0.0;
a \t 3 . 5 \n
cin >> myc;
assume these are spaces cin >> y;
• After the first '>>' // use
return
the variables somehow...
0;
}
c= 'a' y= 0.0
\t 3 . 5 \n cin will:
• skip leading whitespace
• After the second '>>'
• stop at trailing whitespace
c= 'a' y= 3.5
\n
38
In-Class Exercises
• Checkpoint 1
40
return 0;
}
int main()
{
int a = 7, b = 9;
More Assignments
• Assigning a variable makes a copy
• Challenge: Swap the value of 2
variables
– Easiest method: Use a 3rd temporary
variable to save one value and then replace
that variable int main()
{
int a = 7, b = 9, temp;
temp
1 3
7
43
– The key pattern is all elements are kept but just reordered
– It is usually necessary to declare and maintain some
20 50 10
temporary variable to avoid elements getting
dropped/overwritten Rotation Idiom
45
– Global variables are visible to all int main(int argc, char *argv[])
the code/functions in the program {
// y and z are "local" variables
and are declared outside of any int y, z=5; // y is garbage, z is five
function
z = add_1(z);
– Local variables are declared inside y = z+1; // an assignment stmt
cout << y << endl;
of a function and are only visible in return 0;
that function and die when the }
function ends
46
Statements
• C/C++ programs are composed of statements
• Most common kinds of statements end with a semicolon
• Declarations (e.g. int x=3;)
• Assignment + Expression (suppose int x=3; int y;)
– x = x * 5 / 9; // compute the expression & place result in x
// x = (3*5)/9 = 15/9 = 1
• Assignment + Function Call ( + Expression )
– x = cos(0.0) + 1.5;
– sin(3.14); // Must save or print out the result (x = sin(3.14), etc.)
• cin, cout statements
– cout << cos(0.0) + 1.5 << " is the answer." << endl;
• Return statement (immediately ends a function)
– return value;
48
In-Class Exercises
• Checkpoint 2
50
SOLUTIONS
51