Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

Lecture 3 introduction to Programming languages C++

Uploaded by

ahra8462967
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Lecture 3 introduction to Programming languages C++

Uploaded by

ahra8462967
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Introduction to Programming

Languages
Introduction to C++

Lecture 3
Very brief history of C++

For details more check out A History of C++: 1979−1991


C++
class GasMolecule

Object-oriented programming • Data:


• molecular weight, structure, common
names, etc.
• Object-oriented programming • Methods:
• IR(wavenumStart, wavenumEnd) :
(OOP) seeks to define a program in return IR emission spectrum in range
terms of the things in the problem (files,
molecules, buildings, cars, people, etc.),
what they need, and what they can do. Objects (instances of a class)

GasMolecule ch4
GasMolecule co2
“pseudo-code”

spectrum = ch4.IR(1000,3500)
Name = co2.common_name
Object-oriented programming “Class Car”

• OOP defines classes to represent these


things.
public interface
• Classes can contain data and methods
(internal functions).
• Classes control access to internal data
and methods. A public interface is used
by external code when using the class.
• This is a highly effective way of modeling
real world problems inside of a computer
program.

private data and methods


Object-Oriented Programming

• C++ fully supports object-oriented


programming, including the four pillars of
object-oriented development −
• Encapsulation
• Data hiding
• Inheritance
• Polymorphism
• Standard Libraries
• building blocks including variables, data types
and literals, etc.
• rich set of functions manipulating files,
strings, etc.
• rich set of methods manipulating data
structures, etc.
Characteristics of C++
• C++ is…
• Compiled.
• A separate program, the compiler, is used to turn C++ source code into a form directly
executed by the CPU.
• Strongly typed and unsafe
• Conversions between variable types must be made by the programmer (strong typing) but can
be circumvented when needed (unsafe)
• C compatible
• call C libraries directly and C code is nearly 100% valid C++ code.
• Capable of very high performance
• The programmer has a very large amount of control over the program execution
• Object oriented
• With support for many programming styles (procedural, functional, etc.)
• No automatic memory management
• The programmer is in control of memory usage
When to choose C++
• Despite its many competitors C++ has • Choose C++ when:
remained popular for ~30 years and will • Program performance matters
continue to be so in the foreseeable • Dealing with large amounts of data, multiple
future. CPUs, complex algorithms, etc.
• Why? • Programmer productivity is less important
• It is faster to produce working code in
• Complex problems and programs can be Python, R, Matlab or other scripting
effectively implemented languages!
• OOP works in the real world! • The programming language itself can help
• No other language quite matches C++’s organize your code
combination of performance, • Ex. In C++ your objects can closely model
expressiveness, and ability to handle elements of your problem
complex programs. • Access to libraries
• Ex. Nvidia’s CUDA Thrust library for GPUs
• Your group uses it already!
RULES
Naming Rules in C/C++
• Following are the naming rules in C/C++
• Can contain letters, digits and underscores.
• Digit can not be the first character.
• Spaces are not allowed.
• May not be same as keyword or function name etc.
• First 40 characters are significant, i.e. Length can be
of max. 40 characters, but varies from compiler to
compiler.
• Can not consist of an underscore alone.
Types of C/C++ Instructions
There are 4 types of C/C++ Instructions.
i) Type declaration Instructions
Variable types and definitions etc.
ii) Input/Output Instructions
Data Input, Data Display, Data Write etc
iii) Control Instructions
Controls the sequence of execution of the program instructions.
iv) Arithmetic Instructions
Arithmetic Operations etc
IDE Advantages IDEs available on the SCC
▪ Code::Blocks (used here)
• Handles build process for you
▪ geany – a minimalist IDE, simple to use
• Syntax highlighting and live error detection
▪ Eclipse – a highly configurable, adaptable
• Code completion (fills in as you type) IDE. Very powerful but with a long
• Creation of files via templates learning curve
• Built-in debugging ▪ Spyder – Python only, part of Anaconda

• Code refactoring (ex. Change a variable


name everywhere in your code)
• Higher productivity Some Others
▪ Xcode for Mac OSX
▪ Visual Studio for Windows
▪ NetBeans (cross platform)
Opening C::B
• The 1st time it is opened C::B will search for compilers it can
use.
• A dialog that looks like this will open. Select GCC if there are
multiple options:

• And click OK.


IDEs we will use
• Visual studio • DEV
First Program in C++
TASK 1
• Find ASCII codes for Char data types of letters present in
your name.( capital /small)
Examples

d = 3, f = 5;
x = 'x';
A=5.1
String E= “GeeksforGeeks”
Character C=‘a’, ‘A’, ‘z’
C=a+b
Debugging?
Debugging is the process of finding and removing errors in a program.
In this process, the program is thoroughly checked for errors. Then
errors are pointed out and debugged.
Different types errors which can occur during the execution of a
program
• There are three types of errors which can occur during the execution of
a program.
• Syntax Errors
• Runtime Errors
• Logical errors
syntax error
• A syntax error occurs when the program violates one or more
grammatical rules of the programming language. These errors are
detected at compile time, i.e., when the translator (compiler or
interpreter) attempts to translate the program.
Runtime error
A runtime error occurs when the computer is directed to perform an illegal operation
by the program such as dividing a number by zero. Runtime errors are the only
errors which are displayed immediately during the execution of a program. When
these errors occur, the computer stops the execution of the programming and can
display a diagnostic message that will help in locating the error.
Logical error
• The logical error happens when a program implements a wrong logic.
The translator (compiler or interpreter) does not report any error
message for a logical error. These errors are the most difficult to locate.
Flow Chart
The flowchart is a
pictorial
representation of a
program which
helps in
understanding the
flow of control and
data in the
algorithm.
Algorithm
An algorithm is a finite set
of steps which, if followed,
accomplish a particular task.
An algorithm must be clear,
finite and effective.
Header Files C++ language headers aren’t referred
to with the .h suffix. <iostream>
provides definitions for I/O functions,
including the cout function.
• C++ (along with C) uses header files as to
hold definitions for the compiler to use
while compiling. #include <iostream>
• A source file (file.cpp) contains the code using namespace std;
that is compiled into an object file (file.o).
• The header (file.h) is used to tell the int main()
{
compiler what to expect when it assembles
string hello = "Hello";
the program in the linking stage from the string world = "world!";
object files. string msg = hello + " " + world ;
• Source files and header files can refer to cout << msg << endl;
msg[0] = 'h';
any number of other header files.
cout << msg << endl;
return 0;
}
Slight change
• Let’s put the message into some variables #include <iostream>
of type string and print some numbers.
using namespace std;
• Things to note:
• Strings can be concatenated with a + operator. int main()
{
• No messing with null terminators or strcat() as in
C string hello = "Hello";
string world = "world!";
• Some string notes: string msg = hello + " " + world ;
• Access a string character by brackets or function: cout << msg << endl;
• msg[0] → “H” or msg.at(0) → “H” msg[0] = 'h';
cout << msg << endl;
• C++ strings are mutable – they can be
changed in place. return 0;
}
• Press F9 to recompile & run.
A first C++ class: string
• string is not a basic type (more on #include <iostream>

those later), it is a class. using namespace std;


• string hello creates an int main()
instance of a string called “hello”. {
string hello = "Hello";
• hello is an object. string world = "world!";
string msg = hello + " " + world ;
• Remember that a class defines cout << msg << endl;
some data and a set of functions msg[0] = 'h';
(methods) that operate on that cout << msg << endl;
return 0;
data. }
• Let’s use C::B to see what some
of these methods are….
A first C++ class: string
• Update the code as you see #include <iostream>

here. using namespace std;

• After the last character is int main()


{
entered C::B will display string hello = "Hello";
some info about the string string world = "world!";
string msg = hello + " " + world ;
class. cout << msg << endl;
msg[0] = 'h';
• If you click or type something cout << msg << endl;
else just delete and re-type msg
the last character.
return 0;
• Ctrl-space will force the list }

to appear.
A first C++ class: string
Shows this
function
(main) and the
List of string type of msg
methods (string)
List of other
string objects

• Next: let’s find the size() method without scrolling for it.
A first C++ class: string
• Start typing “msg.size()” until it appears in the list. Once it’s highlighted (or you scroll
to it) press the Tab key to auto-enter it.
• On the right you can click “Open declaration” to see how the C++ compiler defines
size(). This will open basic_string.h, a built-in file.
#include <iostream>

A first C++ class: string using namespace std;

int main()
{
• Tweak the code to print the string hello = "Hello" ;
string world = "world!" ;
number of characters in the string msg = hello + " " + world ;
string, build, and run it. cout << msg << endl ;
msg[0] = 'h';
• From the point of view of cout << msg << endl ;

main(), the msg object has cout << msg.size() << endl ;
hidden away its means of return 0;
tracking and retrieving the }
number of characters stored.
• Note: while the string class ▪ Note that cout prints integers
has a huge number of without any modification!
methods your typical C++
class has far fewer!
Break your code.

• Remove a semi-colon. Re-compile. What messages do you get from the compiler
and C::B?
• Fix that and break something else. Capitalize string → String

• C++ can have elaborate error messages when compiling. Experience is the only
way to learn to interpret them!

• Fix your code so it still compiles and then we’ll move on…
Basic Syntax
• C++ syntax is very similar to C, Java, or C#. Here’s a few things up front and we’ll cover
more as we go along.
• Curly braces are used to denote a code block (like the main() function):
{ … some code … }
• Statements end with a semicolon:
int a ;
a = 1 + 3 ;

• Comments are marked for a single line with a // or for multilines with a pair of /* and */ :
// this is a comment.
/* everything in here
is a comment */

void my_function() {
int a ;
• Variables can be declared at any time in a code block. a=1 ;
int b;
}
• Functions are sections of code that are called from other code. Functions always have a
return argument type, a function name, and then a list of arguments separated by
commas:

int add(int x, int y) { // No arguments? Still need ():


int z = x + y ; void my_function() {
return z ; /* do something...
} but a void value means the
return statement can be skipped.*/
}

• A void type means the function does not return a value.

// Specify the type


int x = 100;
float y;
vector<string> vec ;
• Variables are declared with a type and a name: // Sometimes types can be inferred
auto z = x;
• A sampling of arithmetic operators:
• Arithmetic: + - * / % ++ --
• Logical: && (AND) ||(OR) !(NOT)

• Comparison: == > < >= <= !=

• Sometimes these can have special meanings beyond


arithmetic, for example the “+” is used to concatenate strings.

• What happens when a syntax error is made?


• The compiler will complain and refuse to compile the file.
• The error message usually directs you to the error but sometimes the
error occurs before the compiler discovers syntax errors so you hunt a
little bit.
Built-in (aka primitive or intrinsic) Types
• “primitive” or “intrinsic” means these types are not objects
• Here are the most commonly used types.
• Note: The exact bit ranges here are platform and compiler dependent!
• Typical usage with PCs, Macs, Linux, etc. use these values
• Variations from this table are found in specialized applications like embedded system processors.

Name Name Value Name Value


char unsigned char 8-bit integer float 32-bit floating point
short unsigned short 16-bit integer double 64-bit floating point
int unsigned int 32-bit integer long long 128-bit integer
long unsigned long 64-bit integer long double 128-bit floating point
bool true or false
http://www.cplusplus.com/doc/tutorial/variables/

http://www.cplusplus.com/doc/tutorial/variables/
Need to be sure of integer sizes?
• In the same spirit as using integer(kind=8) type notation in Fortran, there are type definitions that
exactly specify exactly the bits used. These were added in C++11.
• These can be useful if you are planning to port code across CPU architectures (ex. Intel 64-bit CPUs
to a 32-bit ARM on an embedded board) or when doing particular types of integer math.
• For a full list and description see: http://www.cplusplus.com/reference/cstdint/

#include <cstdint>
Name Name Value
int8_t uint8_t 8-bit integer
int16_t uint16_t 16-bit integer
int32_t uint32_t 32-bit integer
int64_t uint64_t 64-bit integer
Type Casting
• C++ is strongly typed. It will auto-convert a variable of one type to another in a limited fashion: if it
will not change the value.
short x = 1 ;
int y = x ; // OK
short z = y ; // NO!

• Conversions that don’t change value: increasing precision (float → double) or integer → floating
point of at least the same precision.
• C++ allows for C-style type casting with the syntax: (new type) expression
double x = 1.0 ;
int y = (int) x ;
float z = (float) (x / y) ;

• But since we’re doing C++ we’ll look at the 4 ways of doing this in C++ next...
Type Casting
double d = 1234.56 ;
• static_cast<new type>( expression ) float f = static_cast<float>(d) ;
• This is exactly equivalent to the C style // same as
cast.
float g = (float) d ;
• This identifies a cast at compile time.
• This will allow casts that reduce precision (ex. double → float)
• ~99% of all your casts in C++ will be of this type.

• dynamic_cast<new type>( expression)


• Special version where type casting is performed at runtime, only
works on reference or pointer type variables.
• Usually handled automatically by the compiler where needed,
rarely done by the programmer.

You might also like