Introduction to C CS1 Lesson 2 John Cole 1 Parts of a C Program sample C program include ltiostreamgt using namespace std int main cout ltlt Hello there return 0 ID: 332856
Download Presentation The PPT/PDF document "CS1 Lesson 2" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
CS1 Lesson 2
Introduction to C++
CS1 Lesson 2 -- John Cole
1Slide2
Parts of a C++ Program
// sample C++ program
#include <iostream>
using namespace std;
int main()
{ cout << "Hello, there!"; return 0;}
CS1 Lesson 2 -- John Cole
2Slide3
Notes:
Preprocessor directives begin with # (pound sign).
For #include, the file name is in brackets if it is one of the standard headers, in quotes if it is one of yours.
CS1 Lesson 2 -- John Cole
3Slide4
The cout
Object
Displays output on the screen (the stdout device)Use the << (stream insertion) operator.
You can string these together:
cout
<< “The values is” << x;CS1 Lesson 2 -- John Cole4Slide5
The endl
Manipulator
endl (end line) makes the stream go to a new line.cout << “First line” <<
endl
<< “second line”;
Note that the last character is the lower-case letter “L”, not the digit “1”.(You can also use \n in a string:cout << “First line\nSecond line”;We’ll discuss other manipulators later.CS1 Lesson 2 -- John Cole5Slide6
The #include Directive
Any line that starts with a # sign is not an actual C++ statement. It directs the compiler to do something.
#include directs the compiler to include a source file as though you had typed it in line.There is no semicolon at the end of this directive.
CS1 Lesson 2 -- John Cole
6Slide7
Variables
Variable: a storage location in memory
Has a name and a type of data it can holdCan be changed by your program
Must be defined before it can be used:
int item; item = 1;CS1 Lesson 2 -- John Cole7Slide8
Literals
A value (including strings) written into the program code.
Examples:“Hello World” // string3.14159 // double
‘z’ // char
Avoid using literals. They can make your program inflexible.
CS1 Lesson 2 -- John Cole8Slide9
Identifiers
Any programmer-defined name, including the names of variables.
Function names, class names, etc. are identifiers.C++ keywords cannot be used as identifiers
CS1 Lesson 2 -- John Cole
9Slide10
C++ Keywords
CS1 Lesson 2 -- John Cole
10Slide11
Identifier Rules
The first character must be a letter or an underscore (_)
After the first character you may use letters, numbers, and underscoresUpper- and lower-case letters are distinct.
CS1 Lesson 2 -- John Cole
11Slide12
Identifier Conventions
Identifiers for methods and variables generally begin with a lower-case letter. If contains more than one word, the second word is capitalized:
itemsOrdered; totalSalesTax
Class names begin with a capital letter.
Named constants are usually all upper case:
const double PI = 3.1415926535;Avoid single-letter identifiers in all but the simplest cases.CS1 Lesson 2 -- John Cole12Slide13
Integer Data Types
CS1 Lesson 2 -- John Cole
13Slide14
Integers, continued
When you use an integer literal, it is by default stored as an int. To make it a long, follow the number with ‘L’:
1234 is an int
1234L is a long.
Integer constants that begin with 0 (zero) are octal: 061. (089 is not valid)
Integer constants that begin with 0x are hexadecimal: 0xFF, 0x1ACS1 Lesson 2 -- John Cole14Slide15
The char Data Type
This represents a single character.
It can also be treated as an integer. You can do arithmetic on them.In ASCII encoding, these take one byte of memory.The numeric value of the character is stored:
char
columnID
= ‘A’; // stores 65char row = ‘2’; // stores 50CS1 Lesson 2 -- John Cole15Slide16
Character Strings
A series of characters stored in memory is called a string. String literals are enclosed in quotes, and are stored with a binary zero (null) at the end.
“Hello” is stored as:
CS1 Lesson 2 -- John Cole
16Slide17
The C++ string class
Special data type supports working with strings
#include <string>
Can define
string
variables in programs:string firstName, lastName;Can receive values with assignment operator:firstName = "George";lastName = "Washington";Can be displayed via coutcout << firstName << " " << lastName;CS1 Lesson 2 -- John Cole17Slide18
Floating-Point Data Types
The floating-point data types are:
float
double
long double
They can hold real numbers such as: 12.45 -3.8Stored in a form similar to scientific notationAll floating-point numbers are signedCS1 Lesson 2 -- John Cole18Slide19
Floating Point
CS1 Lesson 2 -- John Cole
19Slide20
Floating Point Literals
Can be represented in
Fixed point (decimal) notation:
31.4159 0.0000625
E notation:
3.14159E1 6.25e-5Are double by defaultCan be forced to be float (3.14159f) or long double (0.0000625L)CS1 Lesson 2 -- John Cole20Slide21
The bool
Data Type
Represents values that are true or
false
bool
variables are stored as small integersfalse is represented by 0, true by 1: bool bRun = true; bool finished = false;CS1 Lesson 2 -- John Cole21Slide22
The Size of a Data Type
The
sizeof operator gives the size of any data type or variable:
double amount;
cout << "A double is stored in " << sizeof(double) << "bytes\n"; cout << "Variable amount is stored in " << sizeof(amount) << "bytes\n";CS1 Lesson 2 -- John Cole22Slide23
Assignment
An assignment statement uses the
= operator to store a value in a variable.
item = 12;
long
fedDeficit= 1000000000000L;This statement assigns the value 12 to the item variable.CS1 Lesson 2 -- John Cole23Slide24
Variable Initialization
To initialize a variable means to assign it a value when it is defined:
int
length = 12;
Can initialize some or all variables:
int length = 12, width = 5, area;CS1 Lesson 2 -- John Cole24Slide25
Scope of Variables
The
scope of a variable: the part of the program in which the variable can be accessedA variable cannot be used before it is defined
i
nt
main(){ cout << value; // Error int value = 31;}CS1 Lesson 2 -- John Cole25Slide26
Scope, continued
for (
int
iy
=0; iy<10; iy++) { cout << iy; }cout << iy; // iy is out of scope here.CS1 Lesson 2 -- John Cole26Slide27
Arithmetic Operators
Used for performing numeric calculations
C++ has unary, binary, and ternary operators:unary (1 operand)
-5
binary (2 operands)
13 - 7ternary (3 operands) exp1 ? exp2 : exp3CS1 Lesson 2 -- John Cole27Slide28
Binary Arithmetic Operators
CS1 Lesson 2 -- John Cole
28Slide29
Division
/
(division) operator performs integer division if both operands are integers
cout
<< 13 / 5; // displays 2
cout << 91 / 7; // displays 13If either operand is floating point, the result is floating pointcout << 13 / 5.0; // displays 2.6cout << 91.0 / 7; // displays 13.0CS1 Lesson 2 -- John Cole29Slide30
Modulus
%
(modulus) operator computes the remainder resulting from integer division
cout
<< 13 % 5; // displays 3
% requires integers for both operandscout << 13 % 5.0; // errorCS1 Lesson 2 -- John Cole30Slide31
Comments
Use comments to explain to yourself and other programmers (including your instructor and TAs) what your program does.
The compiler ignores comments, so they don’t increase code size.See the Web site for more notes on comments
CS1 Lesson 2 -- John Cole
31Slide32
Comment Types
A single-line comment is anything following a // (Unless the // is in quotes)
You can delimit comments with /* and */ and span multiple lines. You can also use this style within a line:calculate(double rate, /* tax rate*/, double amount);
CS1 Lesson 2 -- John Cole
32Slide33
Named Constants
Use the “const
” modifier to indicate that a variable really isn’t:const
int
MAX_RECORDS = 100;const double PI = 3.1415926535;Use these in place of literals, especially if you use the value more than once.Avoid using #defineCS1 Lesson 2 -- John Cole33Slide34
Programming Style
Make your programs look visually pleasing and readable.
Use good naming conventions.
Common elements to improve readability:
Braces
{ } aligned verticallyIndentation of statements within a set of bracesBlank lines between declaration and other statementsLong statements wrapped over multiple lines with aligned operatorsCS1 Lesson 2 -- John Cole34Slide35
Standard and Prestandard
C++
Older-style C++ programs:Use
.h
at end of header files:
#include <iostream.h>Use #define preprocessor directive instead of const definitionsDo not use using namespace conventionMay not compile with a standard C++ compilerCS1 Lesson 2 -- John Cole35