0% found this document useful (0 votes)
18 views51 pages

Unit1 CIntro

With n bits, we can form 2^n numbers. The number of possible combinations grows exponentially as we increase the number of bits.

Uploaded by

Zaid Salman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views51 pages

Unit1 CIntro

With n bits, we can form 2^n numbers. The number of possible combinations grows exponentially as we increase the number of bits.

Uploaded by

Zaid Salman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

1

CS 103 Lecture 2 Slides

C/C++ Basics

Mark Redekopp
2

Announcements
• Ensure you can gain access to Vocareum.com

• Lab 1 review answers must be submitted on our website


– Attend lab to meet your TAs and mentors and get help with lab 1
3

A quick high-level view before we dive into the details…

PROGRAM STRUCTURE AND


COMPILATION PROCESS
4

C/C++ Program Format/Structure


/* Anything between slash-star and
• Comments star-slash is ignored even across
multiple lines of text or code */
– Anywhere in the code
– C-Style => "/*" and "*/" // Anything after "//" is ignored on a line
– C++ Style => "//"
// #includes allow access to library functions
• Compiler Directives #include <iostream>
#include <cmath>
– #includes tell compiler what other library using namespace std;
functions you plan on using
void printName()
– 'using namespace std;' -- Just do it for now! {
• main() function }
cout << "Tommy Trojan" << endl;

– Starting point of execution for the program


// Execution always starts at the main() function
– All code/statements in C must be inside a int main()
function {
cout << "Hello: " << endl;
– Statements execute one after the next and printName();
end with a semicolon (;) printName();
return 0;
– Ends with a 'return 0;' statement }
• Other functions Hello:
– printName() is a function that can be Tommy Trojan
"called"/"invoked" from main or any other Tommy Trojan
function
5

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

$ g++ –g –Wall –o test test.cpp $ g++ –g –Wall –o test test.cpp


or
$ ./test
$ make test

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

• Unique address assigned to each cell 2 10010000

– Used to reference the value in that location 3 11110100


4 01101000
• We first need to understand the various 5 11010001
ways our program can represent data and …
allocate memory
• When programming 5 4 3 2
1023 00001011
it is necessary to 5 4 1

understand how data is 5 S

5
3

4
2 F

stored 5 Memory
Device
9

Starting With Numbers


• A single bit can only represent 1 and 0
• To represent more than just 2 values
1
we need to use A bit

combinations/sequences of many bits


– A byte is defined as a group 8-bits
– A word varies in size but is usually 32-bits 01000001
• So how do we interpret those A byte

sequences of bits?
– Let's learn about number systems
0101110 11010001 10110101 01110111
A word
10

Binary Number System


• Humans use the decimal number system
– Based on number 10
– 10 digits: [0-9]
• Because computer hardware uses digital
signals with 2 values, computers use the
binary number system
– Based on number 2
– 2 binary digits (a.k.a bits): [0,1]
11

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?

512 256 128 64 32 16 8 4 2 1

1024 512 256 128 64 32 16 8 4 2 1


14

C Integer Data Types


• In C/C++ constants & variables can be of different types
and sizes
– A Type indicates how to interpret the bits and how much
memory to allocate
– Integer Types (signed by default… unsigned with optional
leading keyword)
C Type C Type (Unsigned) Bytes Bits Signed Range Unsigned
(Signed) Range
char unsigned char 1 8 -128 to +127 0 to 255
short unsigned short 2 16 -32768 to +32767 0 to 65535
int unsigned int 4 32 -2 billion to 0 to 4 billion
+2 billion
long long unsigned long long 8 64 -8*1018 to +8*1018 0 to 16*1018
15

C Floating Point Types


• float and double types:
– Allow decimal representation (e.g. 6.125) as well as very large integers
(+6.023E23)
C Type Bytes Bits Range
float 4 32 ±7 significant digits * 10+/-38
double 8 64 ±16 significant digits * 10+/-308

• Prefer double over float


– Many compilers will upgrade floats to doubles anyhow
• Don't use floating-point if you don't need to
– It suffers from rounding error
– Some additional time overhead to perform arithmetic operations
16

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

Interpreting Binary Strings


• Given a string of 1’s and 0’s, you need to know the
representation system being used, before you can
understand the value of those 1’s and 0’s.
• Information (value) = Bits + Context (System)
– Types provide the context (system)

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’

– Ends with a '\0'=NULL character added as the last 3 10 ‘\n’


4 00 Null
byte/character to allow code to delimit the end of the string 5 17

• Boolean (C++ only): true, false 6


7
59
c3
– Physical representation: 0 = false, (Non-zero) = true …
String Example
(Memory Layout)
20

You're Just My Type


• Indicate which constants are matched with
the correct type.
Constant Type Right / Wrong
4.0 int
5 int
'a' string
"abc" string
5. double
5 char
"5.0" double
'5' int

Solutions are provided at the end of the slide packet.


21

What's Your Type


What am I storing?

Text/Character(s) Logical
Number for display (true/false) value

What kind of number is it? Is it a single char or many (i.e.


a string of chars)? Use a…

Contains a
decimal/fractional Integer Single Many
value

What range of values


Use a… might it use? Use a… Use a…

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

EXPRESSIONS & VARIABLES


23

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'

specific size and type A picture of computer memory


char c = 'A';
• Programmer indicates what variables they
(aka RAM)
A single-byte
variable 0 01000001
want when they write their code 1 01001011
– Difference: C requires declaring all variables at 2 10010000
the beginning of a function before any operations. int x; 3 11110100
A four-byte
C++ relaxes this requirement. variable
4 01101000
5 11010001
• The computer will allocate memory for 6 01101000
those variables as the program runs 7 11010001

• We can provide initial values via '=' or leave 1023 00001011
them uninitialized Variables are actually allocated in
RAM when the program is run
28

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

– location [the address in memory where it is allocated]


– Value
• Reminder: You must declare a variable before using it
name
quantity cost
Code int quantity = 4;
double cost = 5.75; 1008412 4 287144 5.75
cout << quantity*cost << endl; Address
value
29

When To Introduce a Variable


• When a value will be supplied
and/or change at run-time (as the
program executes)

• When a value is computed/updated


at one time and used (many times)
later

double a = (56+34) * (81*6.25);


• To make the code more readable by // readability of above vs. below
another human double height = 56 + 34;
double width = 81 * 6.25;
double area = height * width;
30

Assignment operator ‘=‘


• Syntax:
variable = expression; int x = 0;
x = x + 3;
(LHS) (RHS) new-value of x current-value of x
– LHS = Left Hand-Side, RHS = Right Hand Side (3) (0)

• Should be read: Place the value of expression into memory location of


variable
– z = x + y – (2*z);
– Evaluate RHS first, then place the result into the variable on the LHS
– If variable is on both sides, we use the old/current value of the variable on the RHS
• Note: Without assignment values are computed and then forgotten
– x + 5; // will take x's value add 5 but NOT update x (just throws the result away)
– x = x + 5; // will actually updated x (i.e. requires an assignment)
• Shorthand assignment operators for updating a variable based on its
current value: +=, -=, *=, /=, &=, …
– x += 5; (x = x+5)
– y *= x; (y = y*x)
31

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)

• Could use C or C++ syntax for explicit casting


– 5 + (double) 3 / (double) 2 (C-Style cast)
– 5 + static_cast<double>(3) / static_cast<double>(2) (C++-Style)
– 5 + static_cast<double>(3) / 2 (cast one & rely on implicit cast of the other)
– This looks like a lot of typing compared to just writing 5 + 3.0 / 2…but
what if instead of constants we have variables
– int x=5, y=3, z=2; x + y/z;
– x + static_cast<double>(y) / z
33

cout and cin

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

input stream: y ...


35

C++ Output
• Include <iostream> (not iostream.h)
#include<iostream>
• Add using namespace std; at top of file using namespace std;

• Use an appropriate cout statement int main(int argc, char *argv[])


{
• 'cout' requires appropriate use of int x = 5;
char c = 'Y';
separators << between consecutive values double y = 4.5;
or different types of values
cout << "Hello world" << endl;
• 'cout' does not add spaces between cout << "x = " << x;
cout << " c = " << c << "\ny is "
consecutive values; you must do so << y << endl;
return 0;
explicitly }
– Since text strings are a different value we
must separate it with the '<<' operator
• Generally good practice to give some
descriptive text with your numeric output Output from program:
– Note: You may divide up output over multiple Hello world
'cout' statements. Unless an 'endl' or '\n' is x = 5 c = Y
y is 4.5
used the next 'cout' statement will resume where
the last one left off
36

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;
}

Output from program:


Enter an integer, character, string, and double separated by spaces:
5 Y hi 4.5
x = 5 c = Y mystr is hi y is 4.5
37

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

Understanding ASCII and chars


• Characters can still be treated as
numbers char c

char c = 'a'; // same as char c = 97; 97


char d = 'a' + 1; // c now contains 'b' = 98;
cout << d << endl; // I will see 'b' on the screen

char c = '1'; // c contains decimal 49, not 1


// i.e. '1' not equal to 1

c >= 'a' && c <= 'z'; // && means AND


// here we are checking if c is
// storing a lower case letter
39

In-Class Exercises
• Checkpoint 1
40

MODULE 4: ODDS & ENDS


(LIBRARY FUNCTIONS,
ASSIGNMENT, AND CASTING)
41

Assignment Means Copy


• Assigning a variable makes a copy int main()
• Challenge: Swap the value of 2 {
int x = 5, y = 3;
variables x = y; // copy y into x

return 0;
}

int main()
{
int a = 7, b = 9;

// now consider swapping


y a a // the value of 2 variables
3 7 9 a = b;
b = a;
x b b
return 0;
5 9 9 }
42

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;

// let's try again


a a a temp = a;
a = b;
7 9 9
b = temp;
b b 2 b
return 0;
9 9 7 }

temp
1 3
7
43

Problem Solving Idioms


• An idiom is a colloquial or common
mode of expression
– Example: "raining cats and dogs"
• Programming has common modes of
expression that are used quite often to
solve problems algorithmically
• We have developed a repository of these
common programming idioms. We
STRONGLY suggest you
– Reference them when attempting to
solve programming problems
– Familiarize yourself with them and their
structure until you feel comfortable
identifying them
44

Assignment Idioms: Shifting and Rotation


• The shifting idiom shifts data among variables usually 40
replacing/dropping some elements to make room for x1 x2 x3
10 20 50
new ones
– The key pattern is some elements get dropped/overwritten
and other elements are reassigned/moved
20 50 40
– It is important to start by assigning the variable to be
replaced/dropped and then move in order to variables Shifting Idiom

receiving newer data


– Examples: Top k items (high score list)
• The rotation idiom reorders or rearranges data among x1 x2 x3

variables without replacing/dropping elements 10 20 50

– 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

A Few Odds and Ends


/*----Section 1: Compiler Directives ----*/
#include <iostream>
• Variable Initialization #include <cmath>
using namespace std;
– When declared they will have
"garbage" (random or unknown) // Global Variables
int x; // Anything after "//" is ignored
values unless you initialize them
– Each variable must be initialized int add_1(int input)
{
separately // y and z not visible here, but x is
return (input + 1);
• Scope }

– 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

Math & Other Library Functions


#include <iostream>
• C++ predefines a variety of functions for you. Here are #include <cmath>
#include <algorithm>
a few of them: using namespace std;
– sqrt(x): returns the square root of x (in <cmath>) int main()
– pow(x, y): returns xy, or x to the power y {
// can call functions
(in <cmath>) // in an assignment
– sin(x)/cos(x)/tan(s): returns the trig. Function's double res = cos(0); // res = 1.0
value for x if x is in radians (in <cmath>)
// can call functions in an
– abs(x): returns the absolute value of x (in <cstdlib>) // expression
res = sqrt(2) / 2; // res = 1.414/2
– max(x, y) and min(x,y): returns the
maximum/minimum of x and y (in <algorithm>) cout << max(34, 56) << endl;
// outputs 56
• You call these by writing them similarly to how you
would use a function in mathematics [using return 0;
}
parentheses for the inputs (aka) arguments]
• Result is replaced into bigger expression http://www.cplusplus.com/reference/cmath/
• Must #include the correct library
– #includes tell the compiler about the various pre-defined
functions that your program may choose to call
47

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

Pre- and Post-Increment Operators


• ++ and -- operators can be used to "increment-by-1" or "decrement-by-1"
– If ++ comes before a variable it is call pre-increment; if after, it is called post-increment
– x++; // If x was 2 it will be updated to 3 (x = x + 1)
– ++x; // Same as above (no difference when not in a larger expression)
– x--; // If x was 2 it will be updated to 1 (x = x – 1)
– --x; // Same as above (no difference when not in a larger expression)
• Difference between pre- and post- is only evident when used in a larger
expression
• Meaning:
– Pre: Update (inc./dec.) the variable before using it in the expression
– Post: Use the old value of the variable in the expression then update (inc./dec.) it
• Examples [suppose we start each example with: int y; int x = 3; ]
– y = x++ + 5; // Post-inc.; Use x=3 in expr. then inc. [y=8, x=4]
– y = ++x + 5; // Pre-inc.; Inc. x=4 first, then use in expr. [y=9, x=4]
– y = x-- + 5; // Post-dec.; Use x=3 in expr. then dec. [y=8, x=2]
49

In-Class Exercises
• Checkpoint 2
50

SOLUTIONS
51

You're Just My Type


• Indicate which constants are matched with
the correct type.
Constant Type Right / Wrong
4.0 int double (.0)
5 int int
'a' string char
"abc" string C-string
5. double float/double (. = non-integer)
5 char Int…but if you store 5 in a char
variable it'd be okay (char = some
number that fits in 8-bits/1-byte
"5.0" double C-string
'5' int char

You might also like