SlideShare a Scribd company logo
1 of 37
LAB 1: INTRODUCTION TO C++
ENG. MOHAMMED AL-OBAIDI
UNIVERSITY OF SANA’A
FACILITY OF ENGINEERING
MECHATRONICS
DEPARTMENT
ASSESSMENT & REFERENCES
 Assessment:
 - Projects
 - Reports
 - Quizzes
 - Final Exam (practical)
 References:
 C++ Primer, Fifth Edition
 Object Oriented Programming with C++,
8th Edition
 Beginning C++ Programming - From
Beginner to Beyond
LAB OUTLINE:
 Very brief history of C++
 Definition object-oriented programming
 When C++ is a good choice
 The Code::Blocks IDE
 Object-oriented concepts
 First program!
 Some C++ syntax
 Function calls
 Create a C++ class
VERY BRIEF HISTORY OF C++
C
C++
OBJECT-ORIENTED PROGRAMMING (OOP)
 Object-oriented programming (OOP) seeks to define a program in
terms of the things in the problem (files, molecules, buildings,
cars, people, etc.), what they need, and what they can do.
 OOP is a programming paradigm based on objects.
 Objects contain data (Attributes or fields) and code (methods).
 Data within objects is referred to as attributes.
 Code within objects is referred to as procedures.
 Objects can represent real-world entities (e.g., a car).
 Attributes describe properties of objects (e.g., color, model,
speed).
 Methods define actions that objects can perform (e.g., start, stop,
accelerate).
OBJECT-ORIENTED PROGRAMMING (OOP)
 OOP defines classes to represent these things.
 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.
public interface
private data and methods
“Class Car”
OBJECT-ORIENTED PROGRAMMING (OOP)
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
remained popular for ~30 years and will
continue to be so in the foreseeable
future.
 Why?
 Complex problems and programs can be
effectively implemented
 OOP works in the real world!
 No other language quite matches C++’s
combination of performance,
expressiveness, and ability to handle
complex programs.
 Choose C++ when:
 Program performance matters
 Dealing with large amounts of data, multiple
CPUs, complex algorithms, etc.
 Programmer productivity is less important
 It is faster to produce working code in Python,
Matlab or other scripting languages!
 The programming language itself can help
organize your code
 Ex. In C++ your objects can closely model
elements of your problem
 Access to libraries
 Ex. Nvidia’s CUDA Thrust library for GPUs
CODE::BLOCKS
 In this LABs we will use the Code::Blocks integrated development
environment (IDE) for writing and compiling C++
 About C::B
 cross-platform: supported on Mac OSX, Linux, and Windows
 Oriented towards C, C++, and Fortran, supports others such as Python
 Short learning curve compared with other IDEs such as Eclipse or Visual Studio
 Has its own automated code building system, so we can concentrate on
C++
 It can convert its build system files to make and Makefiles so you are not tied to C::B
 Project homepage: http://www.codeblocks.org
IDE ADVANTAGES
 Handles build process for you
 Syntax highlighting and live error
detection
 Code completion (fills in as you type)
 Creation of files via templates
 Built-in debugging
 Code refactoring (ex. Change a variable
name everywhere in your code)
 Higher productivity
Popular IDEs available
 Code::Blocks (used here)
 geany – a minimalist IDE, simple to use
 Eclipse – a highly configurable, adaptable
IDE. Very powerful but with a long
learning curve
 Spyder – Python only, part of Anaconda
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.
OPENING C::B AND CREATING A 1ST C++ PROJECT…
 Step 1. Create a project from the File menu or the Start Here tab:
 Step 2. Choose the Console category and then the Console application and click Go.
 Step 3: Click Next on the “Welcome to the new console application wizard!” screen.
 Step 4: Choose C++!
 …then click Next.
 Step 5. Enter a project title. Let C::B fill in the other fields for you. If you like you can
change the default folder to hold the project. Click Next.
 Step 6: Choose the compiler. For this tutorial, choose GNU GCC as the compiler. Click
Next.
 Step 8: Your project is now created! Click on Sources in the left column, then double-click
main.cpp.
 Click the icon in the toolbar or press F9 to compile and run the program.
HELLO, WORLD!
 Console window:
 Build and compile
messages
HELLO, WORLD! EXPLAINED
The main routine – the start of every C++ program! It
returns an integer value to the operating system and (in
this case) takes no arguments: main()
The return statement returns an integer value to
the operating system after completion. 0 means
“no error”. C++ programs prefered return an
integer value.
CONTINUE..
loads a header file containing function and class
definitions
Loads a namespace called std. Namespaces are used to
separate sections of code for programmer convenience.
To save typing we’ll always use this line in this tutorial.
 cout is the object that writes to the stdout device, i.e. the console
window.
 It is part of the C++ standard library.
 Without the “using namespace std;” line this would have been called
as std::cout. It is defined in the iostream header file.
 << is the C++ insertion operator. It is used to pass characters from
the right to the object on the left. endl is the C++ newline character.
HEADER FILES
 C++ (along with C) uses header files as to
hold definitions for the compiler to use
while compiling.
 A source file (file.cpp) contains the code
that is compiled into an object file (file.o).
 The header (file.h) is used to tell the
compiler what to expect when it assembles
the program in the linking stage from the
object files.
 Source files and header files can refer to
any number of other header files.
#include <iostream>
using namespace std;
int main()
{
string hello = "Hello";
string world = "world!";
string msg = hello + " " + world ;
cout << msg << endl;
msg[0] = 'h';
cout << msg << endl;
return 0;
}
C++ language headers aren’t referred
to with the .h suffix. <iostream>
provides definitions for I/O functions,
including the cout function.
SLIGHT CHANGE
 Let’s put the message into some variables
of type string and print some numbers.
 Things to note:
 Strings can be concatenated with a + operator.
 No messing with null terminators or strcat() as in
C
 Some string notes:
 Access a string character by brackets or function:
 msg[0]  “H” or msg.at(0)  “H”
 C++ strings are mutable – they can be
changed in place.
 Press F9 to recompile & run.
#include <iostream>
using namespace std;
int main()
{
string hello = "Hello";
string world = "world!";
string msg = hello + " " + world ;
cout << msg << endl;
msg[0] = 'h';
cout << msg << endl;
return 0;
}
A FIRST C++ CLASS: STRING
 string is not a basic type (more on those
later), it is a class.
 string hello creates an instance of a
string called “hello”.
 hello is an object.
 Remember that a class defines some data
and a set of functions (methods) that
operate on that data.
 Let’s use C::B to see what some of these
methods are….
#include <iostream>
using namespace std;
int main()
{
string hello = "Hello";
string world = "world!";
string msg = hello + " " + world ;
cout << msg << endl;
msg[0] = 'h';
cout << msg << endl;
return 0;
}
A FIRST C++ CLASS: STRING
 Update the code as you see here.
 After the last character is entered C::B will
display some info about the string class.
 If you click or type something else just
delete and re-type the last character.
 Ctrl-space will force the list to appear.
#include <iostream>
using namespace std;
int main()
{
string hello = "Hello";
string world = "world!";
string msg = hello + " " + world ;
cout << msg << endl;
msg[0] = 'h';
cout << msg << endl;
msg
return 0;
}
A FIRST C++ CLASS: STRING
 Next: let’s find the size() method without scrolling for it.
List of other
string objects
Shows this
function
(main) and the
type of msg
(string)
List of string
methods
 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.
A FIRST C++ CLASS: STRING
 Tweak the code to print the number of
characters in the string, build, and run it.
 From the point of view of main(), the msg
object has hidden away its means of tracking
and retrieving the number of characters
stored.
 Note: while the string class has a huge
number of methods your typical C++ class
has far fewer!
#include <iostream>
using namespace std;
int main()
{
string hello = "Hello" ;
string world = "world!" ;
string msg = hello + " " + world ;
cout << msg << endl ;
msg[0] = 'h';
cout << msg << endl ;
cout << msg.size() << endl ;
return 0;
}
 Note that cout prints integers
without any modification!
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:
 Comments are marked for a single line with a // or for multilines with a pair of /* and */ :
 Variables can be declared at any time in a code block.
void my_function() {
int a ;
a=1 ;
int b;
}
int a ;
a = 1 + 3 ;
// this is a comment.
/* everything in here
is a comment */
 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:
 A void type means the function does not return a value.
 Variables are declared with a type and a name:
int add(int x, int y) {
int z = x + y ;
return z ;
}
// No arguments? Still need ():
void my_function() {
/* do something...
but a void value means the
return statement can be skipped.*/
}
// Specify the type
int x = 100;
float y;
vector<string> vec ;
// 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
char unsigned char 8-bit integer
short unsigned short 16-bit integer
int unsigned int 32-bit integer
long unsigned long 64-bit integer
bool true or false
Name Value
float 32-bit floating point
double 64-bit floating point
long long 128-bit integer
long double 128-bit floating
point
NEED TO BE SURE OF INTEGER SIZES?
 Enter the following code.
#include <iostream>
using namespace std;
int main()
{
cout << "The size of unsigned int is " << sizeof(unsigned int) << " bytesn";
return 0;
}
EXCERCISE
Exercise 2:
#include <iostream>
#include <string>
using namespace std;
int main()
{ int i , j=1 , n ;
cout<<"Enter a number please: " ;
cin<<n ;
for(i=1 ; i<=n ; i++)
{ for( ; j<n ; j++)
{ cout<<j++<<" "; }
}
endl;
return 0;
}
EXERCISE
Exercise 2:
#include <iostream>
#include <string>
using namespace std;
int main()
{ int i , j=1 , n ;
cout<<"Enter a number please: " ;
cin<<n ;
for(i=1 ; i<=n ; i++)
{ for( ; j<n ; j++)
{ cout<<j++<<" "; }
}
endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{ int i , j , n ;
cout<<"Enter a number please: " ;
cin>>n ;
for(i=1 ; i<=n ; i++)
{
for( j=1; j<=i ; j++)
{
cout<<j<<" ";
}
cout<<endl;
}
return 0;
}
Problem 1:
#include <iostream>
#include <string>
using namespace std;
int main()
{ string name , fname ;
cout<<"Enter your name, please: ";
cin>>name;
cout<<"nEnter your friend name, please: ";
cin>>fname;
cout<<"nYour names are:"<<endl<<name<<endl<<fname;
return 0; }
Problem 2:
#include <iostream>
#include <string> using
namespace std; int
main()
{ string name , fname ;
cout<<"Enter your name, please: ";
cin>>name;
cout<<"nEnter your friend name, please: ";
getline(cin,fname);
cout<<"nYour names are:"<<endl<<name<<endl<<fname;
return 0; }
Problem 3:
#include <iostream>
#include <string>
using namespace std;
int main()
{ int level ; string name ;
cout<<"Enter your Level, please: ";
cin>>level;
cout<<"nEnter your name, please: ";
getline(cin,name);
cout<<"nYour Level is: "<<level<<endl;
cout<<"nYour name is: "<<name<<endl;
return 0;
}

More Related Content

Similar to Lab 1.pptx

Similar to Lab 1.pptx (20)

Session 1 - c++ intro
Session   1 - c++ introSession   1 - c++ intro
Session 1 - c++ intro
 
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to it
 
The C++ Programming Language
The C++ Programming LanguageThe C++ Programming Language
The C++ Programming Language
 
The basics of c programming
The basics of c programmingThe basics of c programming
The basics of c programming
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Basics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptxBasics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptx
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
C++ for hackers
C++ for hackersC++ for hackers
C++ for hackers
 
His162013 140529214456-phpapp01
His162013 140529214456-phpapp01His162013 140529214456-phpapp01
His162013 140529214456-phpapp01
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
Unit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introductionUnit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introduction
 
Basics Of C++.pptx
Basics Of C++.pptxBasics Of C++.pptx
Basics Of C++.pptx
 
2621008 - C++ 1
2621008 -  C++ 12621008 -  C++ 1
2621008 - C++ 1
 
1 c introduction
1 c introduction1 c introduction
1 c introduction
 
C introduction
C introductionC introduction
C introduction
 
PRINCE PRESENTATION(1).pptx
PRINCE PRESENTATION(1).pptxPRINCE PRESENTATION(1).pptx
PRINCE PRESENTATION(1).pptx
 
C Lecture
C LectureC Lecture
C Lecture
 

More from MohammedAlobaidy16 (19)

cnc_codes_and_letters.ppt
cnc_codes_and_letters.pptcnc_codes_and_letters.ppt
cnc_codes_and_letters.ppt
 
1684424.ppt
1684424.ppt1684424.ppt
1684424.ppt
 
Lab 4 (1).pdf
Lab 4 (1).pdfLab 4 (1).pdf
Lab 4 (1).pdf
 
Lab 3.pptx
Lab 3.pptxLab 3.pptx
Lab 3.pptx
 
Lab 3.pptx
Lab 3.pptxLab 3.pptx
Lab 3.pptx
 
ch22.ppt
ch22.pptch22.ppt
ch22.ppt
 
ch07.ppt
ch07.pptch07.ppt
ch07.ppt
 
LAB3_CADCAM_using_MasterCam.pptx
LAB3_CADCAM_using_MasterCam.pptxLAB3_CADCAM_using_MasterCam.pptx
LAB3_CADCAM_using_MasterCam.pptx
 
oopusingc.pptx
oopusingc.pptxoopusingc.pptx
oopusingc.pptx
 
MS Office Word.pptx
 MS Office Word.pptx MS Office Word.pptx
MS Office Word.pptx
 
MT 308 Industrial Automation.ppt
MT 308 Industrial Automation.pptMT 308 Industrial Automation.ppt
MT 308 Industrial Automation.ppt
 
ch25.ppt
ch25.pptch25.ppt
ch25.ppt
 
ch05.ppt
ch05.pptch05.ppt
ch05.ppt
 
ch02.ppt
ch02.pptch02.ppt
ch02.ppt
 
Lab1 - Introduction to Computer Basics Laboratory.pdf
Lab1 - Introduction to Computer Basics Laboratory.pdfLab1 - Introduction to Computer Basics Laboratory.pdf
Lab1 - Introduction to Computer Basics Laboratory.pdf
 
lab3&4.pdf
lab3&4.pdflab3&4.pdf
lab3&4.pdf
 
LAB2_Gcode_Mcode.pptx
LAB2_Gcode_Mcode.pptxLAB2_Gcode_Mcode.pptx
LAB2_Gcode_Mcode.pptx
 
4_5931536868716842982.pdf
4_5931536868716842982.pdf4_5931536868716842982.pdf
4_5931536868716842982.pdf
 
ch01.ppt
ch01.pptch01.ppt
ch01.ppt
 

Recently uploaded

CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 

Recently uploaded (20)

CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 

Lab 1.pptx

  • 1. LAB 1: INTRODUCTION TO C++ ENG. MOHAMMED AL-OBAIDI UNIVERSITY OF SANA’A FACILITY OF ENGINEERING MECHATRONICS DEPARTMENT
  • 2. ASSESSMENT & REFERENCES  Assessment:  - Projects  - Reports  - Quizzes  - Final Exam (practical)  References:  C++ Primer, Fifth Edition  Object Oriented Programming with C++, 8th Edition  Beginning C++ Programming - From Beginner to Beyond
  • 3. LAB OUTLINE:  Very brief history of C++  Definition object-oriented programming  When C++ is a good choice  The Code::Blocks IDE  Object-oriented concepts  First program!  Some C++ syntax  Function calls  Create a C++ class
  • 4. VERY BRIEF HISTORY OF C++ C C++
  • 5. OBJECT-ORIENTED PROGRAMMING (OOP)  Object-oriented programming (OOP) seeks to define a program in terms of the things in the problem (files, molecules, buildings, cars, people, etc.), what they need, and what they can do.  OOP is a programming paradigm based on objects.  Objects contain data (Attributes or fields) and code (methods).  Data within objects is referred to as attributes.  Code within objects is referred to as procedures.  Objects can represent real-world entities (e.g., a car).  Attributes describe properties of objects (e.g., color, model, speed).  Methods define actions that objects can perform (e.g., start, stop, accelerate).
  • 6. OBJECT-ORIENTED PROGRAMMING (OOP)  OOP defines classes to represent these things.  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. public interface private data and methods “Class Car”
  • 8. 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
  • 9. WHEN TO CHOOSE C++  Despite its many competitors C++ has remained popular for ~30 years and will continue to be so in the foreseeable future.  Why?  Complex problems and programs can be effectively implemented  OOP works in the real world!  No other language quite matches C++’s combination of performance, expressiveness, and ability to handle complex programs.  Choose C++ when:  Program performance matters  Dealing with large amounts of data, multiple CPUs, complex algorithms, etc.  Programmer productivity is less important  It is faster to produce working code in Python, Matlab or other scripting languages!  The programming language itself can help organize your code  Ex. In C++ your objects can closely model elements of your problem  Access to libraries  Ex. Nvidia’s CUDA Thrust library for GPUs
  • 10. CODE::BLOCKS  In this LABs we will use the Code::Blocks integrated development environment (IDE) for writing and compiling C++  About C::B  cross-platform: supported on Mac OSX, Linux, and Windows  Oriented towards C, C++, and Fortran, supports others such as Python  Short learning curve compared with other IDEs such as Eclipse or Visual Studio  Has its own automated code building system, so we can concentrate on C++  It can convert its build system files to make and Makefiles so you are not tied to C::B  Project homepage: http://www.codeblocks.org
  • 11. IDE ADVANTAGES  Handles build process for you  Syntax highlighting and live error detection  Code completion (fills in as you type)  Creation of files via templates  Built-in debugging  Code refactoring (ex. Change a variable name everywhere in your code)  Higher productivity Popular IDEs available  Code::Blocks (used here)  geany – a minimalist IDE, simple to use  Eclipse – a highly configurable, adaptable IDE. Very powerful but with a long learning curve  Spyder – Python only, part of Anaconda Some Others  Xcode for Mac OSX  Visual Studio for Windows  NetBeans (cross platform)
  • 12. 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.
  • 13. OPENING C::B AND CREATING A 1ST C++ PROJECT…  Step 1. Create a project from the File menu or the Start Here tab:
  • 14.  Step 2. Choose the Console category and then the Console application and click Go.
  • 15.  Step 3: Click Next on the “Welcome to the new console application wizard!” screen.  Step 4: Choose C++!  …then click Next.
  • 16.  Step 5. Enter a project title. Let C::B fill in the other fields for you. If you like you can change the default folder to hold the project. Click Next.
  • 17.  Step 6: Choose the compiler. For this tutorial, choose GNU GCC as the compiler. Click Next.
  • 18.  Step 8: Your project is now created! Click on Sources in the left column, then double-click main.cpp.  Click the icon in the toolbar or press F9 to compile and run the program.
  • 19. HELLO, WORLD!  Console window:  Build and compile messages
  • 20. HELLO, WORLD! EXPLAINED The main routine – the start of every C++ program! It returns an integer value to the operating system and (in this case) takes no arguments: main() The return statement returns an integer value to the operating system after completion. 0 means “no error”. C++ programs prefered return an integer value.
  • 21. CONTINUE.. loads a header file containing function and class definitions Loads a namespace called std. Namespaces are used to separate sections of code for programmer convenience. To save typing we’ll always use this line in this tutorial.  cout is the object that writes to the stdout device, i.e. the console window.  It is part of the C++ standard library.  Without the “using namespace std;” line this would have been called as std::cout. It is defined in the iostream header file.  << is the C++ insertion operator. It is used to pass characters from the right to the object on the left. endl is the C++ newline character.
  • 22. HEADER FILES  C++ (along with C) uses header files as to hold definitions for the compiler to use while compiling.  A source file (file.cpp) contains the code that is compiled into an object file (file.o).  The header (file.h) is used to tell the compiler what to expect when it assembles the program in the linking stage from the object files.  Source files and header files can refer to any number of other header files. #include <iostream> using namespace std; int main() { string hello = "Hello"; string world = "world!"; string msg = hello + " " + world ; cout << msg << endl; msg[0] = 'h'; cout << msg << endl; return 0; } C++ language headers aren’t referred to with the .h suffix. <iostream> provides definitions for I/O functions, including the cout function.
  • 23. SLIGHT CHANGE  Let’s put the message into some variables of type string and print some numbers.  Things to note:  Strings can be concatenated with a + operator.  No messing with null terminators or strcat() as in C  Some string notes:  Access a string character by brackets or function:  msg[0]  “H” or msg.at(0)  “H”  C++ strings are mutable – they can be changed in place.  Press F9 to recompile & run. #include <iostream> using namespace std; int main() { string hello = "Hello"; string world = "world!"; string msg = hello + " " + world ; cout << msg << endl; msg[0] = 'h'; cout << msg << endl; return 0; }
  • 24. A FIRST C++ CLASS: STRING  string is not a basic type (more on those later), it is a class.  string hello creates an instance of a string called “hello”.  hello is an object.  Remember that a class defines some data and a set of functions (methods) that operate on that data.  Let’s use C::B to see what some of these methods are…. #include <iostream> using namespace std; int main() { string hello = "Hello"; string world = "world!"; string msg = hello + " " + world ; cout << msg << endl; msg[0] = 'h'; cout << msg << endl; return 0; }
  • 25. A FIRST C++ CLASS: STRING  Update the code as you see here.  After the last character is entered C::B will display some info about the string class.  If you click or type something else just delete and re-type the last character.  Ctrl-space will force the list to appear. #include <iostream> using namespace std; int main() { string hello = "Hello"; string world = "world!"; string msg = hello + " " + world ; cout << msg << endl; msg[0] = 'h'; cout << msg << endl; msg return 0; }
  • 26. A FIRST C++ CLASS: STRING  Next: let’s find the size() method without scrolling for it. List of other string objects Shows this function (main) and the type of msg (string) List of string methods
  • 27.  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.
  • 28. A FIRST C++ CLASS: STRING  Tweak the code to print the number of characters in the string, build, and run it.  From the point of view of main(), the msg object has hidden away its means of tracking and retrieving the number of characters stored.  Note: while the string class has a huge number of methods your typical C++ class has far fewer! #include <iostream> using namespace std; int main() { string hello = "Hello" ; string world = "world!" ; string msg = hello + " " + world ; cout << msg << endl ; msg[0] = 'h'; cout << msg << endl ; cout << msg.size() << endl ; return 0; }  Note that cout prints integers without any modification!
  • 29. 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…
  • 30. 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:  Comments are marked for a single line with a // or for multilines with a pair of /* and */ :  Variables can be declared at any time in a code block. void my_function() { int a ; a=1 ; int b; } int a ; a = 1 + 3 ; // this is a comment. /* everything in here is a comment */
  • 31.  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:  A void type means the function does not return a value.  Variables are declared with a type and a name: int add(int x, int y) { int z = x + y ; return z ; } // No arguments? Still need (): void my_function() { /* do something... but a void value means the return statement can be skipped.*/ } // Specify the type int x = 100; float y; vector<string> vec ; // Sometimes types can be inferred auto z = x;
  • 32.  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.
  • 33. 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 char unsigned char 8-bit integer short unsigned short 16-bit integer int unsigned int 32-bit integer long unsigned long 64-bit integer bool true or false Name Value float 32-bit floating point double 64-bit floating point long long 128-bit integer long double 128-bit floating point
  • 34. NEED TO BE SURE OF INTEGER SIZES?  Enter the following code. #include <iostream> using namespace std; int main() { cout << "The size of unsigned int is " << sizeof(unsigned int) << " bytesn"; return 0; }
  • 35. EXCERCISE Exercise 2: #include <iostream> #include <string> using namespace std; int main() { int i , j=1 , n ; cout<<"Enter a number please: " ; cin<<n ; for(i=1 ; i<=n ; i++) { for( ; j<n ; j++) { cout<<j++<<" "; } } endl; return 0; }
  • 36. EXERCISE Exercise 2: #include <iostream> #include <string> using namespace std; int main() { int i , j=1 , n ; cout<<"Enter a number please: " ; cin<<n ; for(i=1 ; i<=n ; i++) { for( ; j<n ; j++) { cout<<j++<<" "; } } endl; return 0; } #include <iostream> #include <string> using namespace std; int main() { int i , j , n ; cout<<"Enter a number please: " ; cin>>n ; for(i=1 ; i<=n ; i++) { for( j=1; j<=i ; j++) { cout<<j<<" "; } cout<<endl; } return 0; }
  • 37. Problem 1: #include <iostream> #include <string> using namespace std; int main() { string name , fname ; cout<<"Enter your name, please: "; cin>>name; cout<<"nEnter your friend name, please: "; cin>>fname; cout<<"nYour names are:"<<endl<<name<<endl<<fname; return 0; } Problem 2: #include <iostream> #include <string> using namespace std; int main() { string name , fname ; cout<<"Enter your name, please: "; cin>>name; cout<<"nEnter your friend name, please: "; getline(cin,fname); cout<<"nYour names are:"<<endl<<name<<endl<<fname; return 0; } Problem 3: #include <iostream> #include <string> using namespace std; int main() { int level ; string name ; cout<<"Enter your Level, please: "; cin>>level; cout<<"nEnter your name, please: "; getline(cin,name); cout<<"nYour Level is: "<<level<<endl; cout<<"nYour name is: "<<name<<endl; return 0; }