You are on page 1of 31

Module 1: Introduction and

First Program

Nguyen Dinh Van


Dinh-van.nguyen@mica.edu.vn
0912751310
Contents
• History of C/C++
• How C++ Relates to Java and C#?
• How to write a first program
• Print to screen
• Get input
• Compile your program
• Variables
• Data Types
• Reserved Words in C++
• Operators
• Type Casting
History of C/C++
• 1972: C was invented and first implemented by Dennis Ritchie in
Bell Labs
• C is structured programming language
• 1979: Bjarne Stroustrup created “C with Classes”, an Object-
oriented version of C
• 1983 the name was changed to C++
How C++ Relates to Java and C#?
• C++ is the parent for both Java and C#
• the syntax are nearly identical
• object model are the same
• The main difference: the type of computing environment
C++ Java and C#
- output from the compiler is machine code - output from the compiler is pseudocode, then this
pseudocode is executed by a runtime system (Java
Virtual Machine (JVM)/Common Language Runtime
(CLR))
- tied to a specific CPU and operating system - runs in a wide variety of environments
- run faster - more slowly
The Skeleton
#include <iostream.h>
void main ( )
{
// Go ahead and memorize this.
// It has to be there!
}

// Note: this should go in a .cpp file


Documenting Your Programs
• This is called “commenting”, and the computer ignores this when
compiling.
• There’s 2 ways to do it in C++!

// This is for a single line comment.


/* This is for a paragraph of comments
and can go on and on. It doesn’t matter
until you see the */
Printing to the Screen
• Use cout to do this (pronounced “see-out”)
• cout can print out just about anything
• Variables of most data types
• Multiple things at once
• Special characters like ‘\n’ (newline), etc.
• Print multiple things with additional <<‘s
• Print out endl to drop to next line
Cout
• Some examples:

cout << “This is a sample string”;


cout << my_int << endl;
cout << “C++ scares me”;
cout << “Hello” << “ world!” << endl;
Getting Input from the User
• Use cin (pronounced “see-in”)
• Read into variables (later)
• Example:
// Declare a variable
int myInt;
// Load it with information from the keyboard
cin >> myInt;
// Print it out
cout << “myInt is “ << myInt << endl;
Cin
• More examples:

cin >> my_int;

cin >> age >> name;


Chaining stream Operations
• There is no limit to the number of things that you can print & read

• Simply chain them together like this:

cout << “First item” << “second item” << endl;


Special Escape Sequences
• Added within strings
• Performs “special character”

\n newline
\r carriage return (not common)
\t tab
\a alert (beep)
\\ backslash
\’ single quote
\” double quote
Your First C++ Program
#include <iostream.h>

void main ( ) {
cout << “Hello World” << endl;
}

// Note: yes, this should be put into a .cpp file


Rules about Syntax
• Where do the ;’s go?
• Semicolons come after single statements
• Similar to a period at the end of a sentence
• Where do the { and } go?
• Creates a block of text for multiple single statements
• { tells the computer to begin a section
• } tells the computer to end a section
• Can be nested (or inside of each other)
• Let’s go back to our first c++ program
Your First C++ Program

#include <iostream.h>
Begin the main
void main ( ) {
cout << “Hello World” << endl;
}
End the main End a single statement
Compiling Your Program
• You’ll use one of two things:
• The command-line: g++ (on Unix)
• Your IDE (like Visual C++)
• When you compile, you’ll have one of two things happen:
• It compiles
• It doesn’t
• If it doesn’t compile, you have syntax errors
Knowing When to Compile
• As a rule, the less comfortable you are, the more you should compile
• This isolates the errors
• As a rule, compile:
• After you type in the skeleton
• After every 5 or 10 lines of new code
• Don’t become dependent on the compiler!
Variables
• Computer programs manipulate data
• There is a need to store data
• Variables:
• Represent a named cell in the computer’s memory
• Used to hold information
• When you declare a variable:
• You open up some of the computer’s memory
• You’re giving the variable an identifier (name)
• You only do this once per variable
Data Types
• A data type describes the kind of information a variable
can hold
• Some data types are built into the language
• Some data types we define ourselves (later)
• Different Forms:
• Primitive data types
• Complex data types
Primitive Data Types
• These are the simplest kinds of data types
• Built-in
• Whole numbers:
• short (relatively small numbers)
• int (larger numbers)
• long (VERY large numbers)
• Number of bytes these take up depends on compiler and OS!
Primitive Data Types
• Decimal numbers:
• float (less precise than a double)
• double (more precise than a float)
• Precision means how many numbers come after the decimal point
• Others:
• char (holds characters like ‘a’, ‘A’, ‘1’, ‘ ‘)
• bool (holds only a true or false value)
How to Declare a Variable
(of any type)

• Format:
<data type> <variable name>;
• Variable name you can choose almost anything
• Examples:
age gpa
byte age;
float gpa;
String name;
char letterGrade; name letterGrade
How Big is it: sizeof( )

• sizeof( ) will tell you how much memory something takes up


in bytes
• Usage:
int myInt;
cout << sizeof (myInt) << endl;
Reserved Words in C++
• These words are used by C++ for special reasons, so you can’t use
them
• List:
• auto, bool, break, case, catch, char, class, const, continue, default, do,
double, else, enum, extern, float, for, friend, goto, if, inline, int, long,
namespace, new, operator, private, protected, public, register, return, short,
signed, sizeof, static, struct, switch, template, this, throw, try, typedef, union,
unsigned, void, volatile, while
Legal Variable Names
• Can’t be a reserved word
• Can’t begin with a number
• Can’t contain special symbols
• Like #, @, !, ^, &, /, ), or SPACES
• Exceptions: underscore _, and dollar sign $
• Examples:
byte $theValue; // legal
char test_value; // legal
double double; // not legal
int rum&coke; // not legal
boolean true or false; // not legal for two reasons!
Literal Values
• Values that are constant
• Examples:

• String literal – “Hello, World!”


• Whole number literal – 17
• Decimal literal – 3.14159
• Character literal – ‘V’
Initializing Variables
• Initializing a variable means giving a variable some kind of starting value
• Assignment operator is =
• Copies the information on the right into the variable on the left and must be
compatible
• Can be a literal OR another variable!
• Examples:
int age;
age = 15;
char letterGrade = ‘B’;
char yourGrade = letterGrade;
Why Size Matters
• Each data type takes up a different amount of the computers memory (in bytes)
• Can’t put a larger data typed variable into a smaller data typed variable:
short s = 5; long l = 5;
long l = s; short s = l;

long long
long
short
short short
Operators
• + adds two variables/literals together (including
Strings)
• - subtraction
• / division
• * multiplication
• % modulus (remainder)
• ( and ) follows standard math rules
• Example:
int result = ( (4 % 3) * 5) + 1; // result gets 6
Type Casting
• This occurs when you want to put something larger into something smaller
• Can possibly lose precision or value
• Has format:
<smaller var> = (<smaller data type>)<larger var>;
• Example:
long myLong = 17;
short myShort = (short)myLong;
// We are squeezing myLong into myShort!
Exercises

1. Write a program in C++ to find Size of fundamental data types.


2. Write a program in C++ to print the sum of two numbers using
variables.
3. Write a program in C++ to swap two numbers.
4. Input the radius of a sphere, calculate the volume.
5. Input the side of a cube, calculate its volume.
6. Input the radius and the height of the cylinder, calculate its volume.
7. Write a program in C++ to find the Area and Perimeter of a
Rectangle.

You might also like