SlideShare une entreprise Scribd logo
1  sur  41
Programming fundamentals
week 2 : Getting Started with C++
Objective
In this chapter, you will:
• Become familiar with the basic components
and syntax of a C++ program. Explore
simple data types
• Variables declaration
• Memory used by data types
• Comments
• Escape sequence
Variables and Identifiers
• Variables have names – we call these names
identifiers.
• An identifier must begin with a letter or an
underscore _
• C++ is case sensitive upper case (capital) or
lower-case letters are considered different
characters. Average, average and AVERAGE are
three different identifiers.
• Identifiers cannot be reserved words (special
words like int, main, etc.)
• Two predefined identifiers are cout and cin
4
Variables and Identifiers
(continued)
• The following are legal identifiers in C++:
– first
– conversion
– payrate
Example of illegal identifier
Illegal identifier Description
Employee salary There can be no space between employee and salary
Hello! The exclamation mark cannot be used in an identifier
One+two The symbol + cannot be used in an idenrifie.
2nd An identifier cannot begin with a digit
5
Reserved Words (Keywords)
• Reserved words (also called keywords) are defined with
predefined meaning and syntax in the language
• Include:
• int
• float
• double
• char
• const
• void
• return
6
C++ Fundamental Data Types
• Data type: set of values together with a set of
operations
• C++ data types fall into three categories:
• Primitive data types include integer, float,
character, Boolean.
• Abstract data type include class, structure.
• Derived data types include array, function,
pointer, and reference.
7
C++ Fundamental Data Types
In C++, data types are declarations for variables.
This determines the type and size of data associated
with variables. For example,
int age = 13;
Here, age is a variable of type int. meaning, the
variable can only store integers of either 2 or 4 bytes.
8
C++ Fundamental Data Types
The table below shows the fundamental data types,
their meaning, and their sizes (in bytes):
Data Type Meaning Size (in bytes)
int Integer 2 or 4
float Floating-point 4
double Double floating-point 8
char Character 1
bool Boolean 1
void Empty 0
9
int Data Type
• The int keyword is used to indicate integers.
• Its size is usually 4 bytes. Meaning, it can store
values from -2147483648 to 2147483647
• Examples:
– Int salary = 85000;
• Positive integers do not need a + sign
10
• float and double are used to store floating-point
numbers (decimals and exponentials).
• The size of float is 4 bytes and the size of double
is 8 bytes. Hence, double has two times the
precision of float. To learn more, visit C++ float
and double.
• For example,
– float area = 64.74;
– double volume – 134.64534;
Floating-Point Data Types
11
char Data Type
• Keyword char is used for characters.
• Its size is 1 byte.
• Characters in C++ are enclosed inside single quotes ' '
– 'A', 'a', '0', '*', '+', '$', ‘&’
For example,
char test = ‘h’;
12
bool Data Type
• The bool data type has one of two possible values:
true or false.
• Booleans are used in conditional statements and
loops (which we will learn in later chapters).
• For example,
– bool con = false;
13
void Data Type
• The void keyword indicates an absence of data. It
means "nothing" or "no value".
• We will use void when we learn about functions
and pointers.
– Note: We cannot declare variables of the void type.
14
string Type
• Programmer-defined type supplied in Standard C++ library
• Sequence of zero or more characters
• Enclosed in double quotation marks
• Null: a string with no characters
• Each character has relative position in string
– Position of first character is 0
• Length of a string is number of characters in it
– Example: length of "William Jacob" is 13
15
Form and Style
• Consider two ways of declaring variables:
– Method 1
int feet, inch;
double x, y;
– Method 2
int a,b;double x,y;
• Both are correct; however, the second is hard to
read
Modifiers
• We can further modify some of the fundamentals data
types by using type modifiers. There are 4 type modifiers
in C++. They are:
– signed
– unsigned
– short
– long
Modified Data types List
Data Type Size (in
Bytes)
Meaning
signed int 4 Used for integers (equivalent to int0
unsigned int 4 Can only store positive integers
short 2 Used for small integers(range -32768 to 32767)
unsigned short 2 Used for small positive integers(range 0 to
65.535)
long 4 Used for large integers (equivalent to long int)
long long 8 Used for very large integers
unsigned long
long
8 Used for very large positive integers
uong double 12 Used for large floating-point numbers
signed char 1 Used for characters (range -127 to 127)
18
Use of Blanks
• In C++, you use one or more blanks to
separate numbers when data is input
• Used to separate reserved words and
identifiers from each other and from other
symbols
• Must never appear within a reserved word or
identifier
19
Constants and Variables
• Named constant: memory location whose
content can’t change during execution
• The syntax to declare a named constant is:
• In C++, const is a reserved word.
• Variable: memory location whose content
may change during execution
20
Programming Example:
Variables and Constants
• Variables
int feet; //variable to hold given feet
int inches; //variable to hold given inches
double centimeters; //variable to hold length in
//centimeters
• Named Constant
const double CENTIMETERS_PER_INCH = 2.54;
const int INCHES_PER_FOOT = 12;
21
Whitespaces
• Every C++ program contains whitespaces
– Include blanks, tabs, and newline characters
• Used to separate special symbols, reserved
words, and identifiers
• Proper utilization of whitespaces is
important
– Can be used to make the program readable
22
Declaring & Initializing
Variables
• Ways to place data into a variable:
– Use C++’s assignment statement
•feet = 35;
– Use input (read) statements
•cin >> feet;
23
Declaring & Initializing
Variables
– Use C++’s assignment statement example
int first=13, second=10;
char ch=' ';
double x=12.6;
• All variables must be initialized before they
are used
– But not necessarily during declaration
24
Input (Read) Statement
• cin is used with >> to gather input
• The stream extraction operator is >>
• For example, if miles is a double variable
cin >> miles;
– Causes computer to get a value of type
double
– Places it in the variable miles
25
Input (Read) Statement
(continued)
• Using more than one variable in cin allows
more than one value to be read at a time
• For example, if feet and inches are
variables of type int, a statement such as:
cin >> feet >> inches;
– Inputs two integers from the keyboard
– Places them in variables feet and inches
respectively
26
Output
• The syntax of cout and << is:
– Called an output statement
• The stream insertion operator is <<
• Expression evaluated and its value is
printed at the current cursor position on the
screen
27
Output (continued)
• A manipulator is used to format the output
– endl causes insertion point to move to
beginning of next line
– Example:
28
Output (continued)
• The new line character is 'n'
– May appear anywhere in the string
cout << "Hello there.";
cout << "My name is James.";
• Output:
Hello there.My name is James.
cout << "Hello there.n";
cout << "My name is James.";
• Output :
Hello there.
My name is James.
29
Output (continued)
30
Comments
• Comments are for the reader, not the compiler
• Two types:
– Single line
// This is a C++ program. It prints the sentence:
// Welcome to C++ Programming.
– Multiple line
/*
You can include comments that can
occupy several lines.
*/
31
Documentation
• A well-documented program is easier to
understand and modify
• You use comments to document programs
• Comments should appear in a program to:
– Explain the purpose of the program
– Identify who wrote it
– Explain the purpose of particular statements
32
Preprocessor Directives
• C++ has a small number of operations
• Many functions and symbols needed to run a C++
program are provided as collection of libraries
• Every library has a name and is referred to by a
header file
• Preprocessor directives are commands supplied to
the preprocessor
• All preprocessor commands begin with #
• No semicolon at the end of these commands
33
Preprocessor Directives
(continued)
• Syntax to include a header file:
• For example:
#include <iostream>
The #include is a preprocessor directive used to include files
in our program. This allows us to use cout in our program
to print output on the screen and cin to take input from
user.
34
namespace and Using cin and
cout in a Program
• cin and cout are declared in the header file
iostream, but within std namespace
• To use cin and cout in a program, use the
following two statements:
#include <iostream>
using namespace std;
• using namespace std means that we can use
names for objects and variables from the standard
library.
35
Creating a C++ Program
• C++ program has two parts:
– Preprocessor directives
– The program
• Preprocessor directives and program statements
constitute C++ source code (.cpp)
• Executable code is produced and saved in a file
with the file extension .exe
36
Creating a C++ Program
(continued)
• A C++ program is a collection of functions, one of which
is the function main
• The first line of the function main is called the heading of
the function:
int main()
• The statements enclosed between the curly braces ({ and
}).
• A valid C++ program must have the main() function. The
curly braces indicate the start and the end of the function.
• The execution of code beings from this function.
37
Creating a C++ Program
Example: Body of the Function
Program:
#include <iostream>
using namespace std;
int main(){
cout<<“Hello World”;
}
Output:
Hello World
38
Creating a C++ Program
(continued)
39
Creating a C++ Program
(continued)
Sample Run:
Line 9: firstNum = 18
Line 10: Enter an integer: 15
Line 13: secondNum = 15
Line 15: The new value of firstNum = 60
40
Program Style and Form
• Every C++ program has a function main
• It must also follow the syntax rules
• Other rules serve the purpose of giving
precise meaning to the language
41
Use of Semicolons, Brackets, and
Commas
• All C++ statements end with a semicolon
– Also called a statement terminator
• { and } are not C++ statements
• Commas separate items in a list

Contenu connexe

Similaire à programming week 2.ppt

C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginnersophoeutsen2
 
c-introduction.pptx
c-introduction.pptxc-introduction.pptx
c-introduction.pptxMangala R
 
Data types slides by Faixan
Data types slides by FaixanData types slides by Faixan
Data types slides by FaixanٖFaiXy :)
 
C PROGRAMMING LANGUAGE.pptx
 C PROGRAMMING LANGUAGE.pptx C PROGRAMMING LANGUAGE.pptx
C PROGRAMMING LANGUAGE.pptxAnshSrivastava48
 
CHAPTER-2.ppt
CHAPTER-2.pptCHAPTER-2.ppt
CHAPTER-2.pptTekle12
 
Programming in C [Module One]
Programming in C [Module One]Programming in C [Module One]
Programming in C [Module One]Abhishek Sinha
 
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit DubeyMCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubeykiranrajat
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ LanguageWay2itech
 
1-19 CPP Slides 2022-02-28 18_22_ 05.pdf
1-19 CPP Slides 2022-02-28 18_22_ 05.pdf1-19 CPP Slides 2022-02-28 18_22_ 05.pdf
1-19 CPP Slides 2022-02-28 18_22_ 05.pdfdhruvjs
 
unit2.pptx
unit2.pptxunit2.pptx
unit2.pptxsscprep9
 
Introduction of c_language
Introduction of c_languageIntroduction of c_language
Introduction of c_languageSINGH PROJECTS
 

Similaire à programming week 2.ppt (20)

C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginner
 
C++ ch2
C++ ch2C++ ch2
C++ ch2
 
c-introduction.pptx
c-introduction.pptxc-introduction.pptx
c-introduction.pptx
 
C material
C materialC material
C material
 
C language
C languageC language
C language
 
Data types slides by Faixan
Data types slides by FaixanData types slides by Faixan
Data types slides by Faixan
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
C PROGRAMMING LANGUAGE.pptx
 C PROGRAMMING LANGUAGE.pptx C PROGRAMMING LANGUAGE.pptx
C PROGRAMMING LANGUAGE.pptx
 
CHAPTER-2.ppt
CHAPTER-2.pptCHAPTER-2.ppt
CHAPTER-2.ppt
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
Programming in C [Module One]
Programming in C [Module One]Programming in C [Module One]
Programming in C [Module One]
 
C programming
C programming C programming
C programming
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit DubeyMCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
 
C PROGRAMING.pptx
C PROGRAMING.pptxC PROGRAMING.pptx
C PROGRAMING.pptx
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
 
1-19 CPP Slides 2022-02-28 18_22_ 05.pdf
1-19 CPP Slides 2022-02-28 18_22_ 05.pdf1-19 CPP Slides 2022-02-28 18_22_ 05.pdf
1-19 CPP Slides 2022-02-28 18_22_ 05.pdf
 
unit2.pptx
unit2.pptxunit2.pptx
unit2.pptx
 
Introduction of c_language
Introduction of c_languageIntroduction of c_language
Introduction of c_language
 
Aniket tore
Aniket toreAniket tore
Aniket tore
 

Dernier

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 

Dernier (20)

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 

programming week 2.ppt

  • 1. Programming fundamentals week 2 : Getting Started with C++
  • 2. Objective In this chapter, you will: • Become familiar with the basic components and syntax of a C++ program. Explore simple data types • Variables declaration • Memory used by data types • Comments • Escape sequence
  • 3. Variables and Identifiers • Variables have names – we call these names identifiers. • An identifier must begin with a letter or an underscore _ • C++ is case sensitive upper case (capital) or lower-case letters are considered different characters. Average, average and AVERAGE are three different identifiers. • Identifiers cannot be reserved words (special words like int, main, etc.) • Two predefined identifiers are cout and cin
  • 4. 4 Variables and Identifiers (continued) • The following are legal identifiers in C++: – first – conversion – payrate Example of illegal identifier Illegal identifier Description Employee salary There can be no space between employee and salary Hello! The exclamation mark cannot be used in an identifier One+two The symbol + cannot be used in an idenrifie. 2nd An identifier cannot begin with a digit
  • 5. 5 Reserved Words (Keywords) • Reserved words (also called keywords) are defined with predefined meaning and syntax in the language • Include: • int • float • double • char • const • void • return
  • 6. 6 C++ Fundamental Data Types • Data type: set of values together with a set of operations • C++ data types fall into three categories: • Primitive data types include integer, float, character, Boolean. • Abstract data type include class, structure. • Derived data types include array, function, pointer, and reference.
  • 7. 7 C++ Fundamental Data Types In C++, data types are declarations for variables. This determines the type and size of data associated with variables. For example, int age = 13; Here, age is a variable of type int. meaning, the variable can only store integers of either 2 or 4 bytes.
  • 8. 8 C++ Fundamental Data Types The table below shows the fundamental data types, their meaning, and their sizes (in bytes): Data Type Meaning Size (in bytes) int Integer 2 or 4 float Floating-point 4 double Double floating-point 8 char Character 1 bool Boolean 1 void Empty 0
  • 9. 9 int Data Type • The int keyword is used to indicate integers. • Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to 2147483647 • Examples: – Int salary = 85000; • Positive integers do not need a + sign
  • 10. 10 • float and double are used to store floating-point numbers (decimals and exponentials). • The size of float is 4 bytes and the size of double is 8 bytes. Hence, double has two times the precision of float. To learn more, visit C++ float and double. • For example, – float area = 64.74; – double volume – 134.64534; Floating-Point Data Types
  • 11. 11 char Data Type • Keyword char is used for characters. • Its size is 1 byte. • Characters in C++ are enclosed inside single quotes ' ' – 'A', 'a', '0', '*', '+', '$', ‘&’ For example, char test = ‘h’;
  • 12. 12 bool Data Type • The bool data type has one of two possible values: true or false. • Booleans are used in conditional statements and loops (which we will learn in later chapters). • For example, – bool con = false;
  • 13. 13 void Data Type • The void keyword indicates an absence of data. It means "nothing" or "no value". • We will use void when we learn about functions and pointers. – Note: We cannot declare variables of the void type.
  • 14. 14 string Type • Programmer-defined type supplied in Standard C++ library • Sequence of zero or more characters • Enclosed in double quotation marks • Null: a string with no characters • Each character has relative position in string – Position of first character is 0 • Length of a string is number of characters in it – Example: length of "William Jacob" is 13
  • 15. 15 Form and Style • Consider two ways of declaring variables: – Method 1 int feet, inch; double x, y; – Method 2 int a,b;double x,y; • Both are correct; however, the second is hard to read
  • 16. Modifiers • We can further modify some of the fundamentals data types by using type modifiers. There are 4 type modifiers in C++. They are: – signed – unsigned – short – long
  • 17. Modified Data types List Data Type Size (in Bytes) Meaning signed int 4 Used for integers (equivalent to int0 unsigned int 4 Can only store positive integers short 2 Used for small integers(range -32768 to 32767) unsigned short 2 Used for small positive integers(range 0 to 65.535) long 4 Used for large integers (equivalent to long int) long long 8 Used for very large integers unsigned long long 8 Used for very large positive integers uong double 12 Used for large floating-point numbers signed char 1 Used for characters (range -127 to 127)
  • 18. 18 Use of Blanks • In C++, you use one or more blanks to separate numbers when data is input • Used to separate reserved words and identifiers from each other and from other symbols • Must never appear within a reserved word or identifier
  • 19. 19 Constants and Variables • Named constant: memory location whose content can’t change during execution • The syntax to declare a named constant is: • In C++, const is a reserved word. • Variable: memory location whose content may change during execution
  • 20. 20 Programming Example: Variables and Constants • Variables int feet; //variable to hold given feet int inches; //variable to hold given inches double centimeters; //variable to hold length in //centimeters • Named Constant const double CENTIMETERS_PER_INCH = 2.54; const int INCHES_PER_FOOT = 12;
  • 21. 21 Whitespaces • Every C++ program contains whitespaces – Include blanks, tabs, and newline characters • Used to separate special symbols, reserved words, and identifiers • Proper utilization of whitespaces is important – Can be used to make the program readable
  • 22. 22 Declaring & Initializing Variables • Ways to place data into a variable: – Use C++’s assignment statement •feet = 35; – Use input (read) statements •cin >> feet;
  • 23. 23 Declaring & Initializing Variables – Use C++’s assignment statement example int first=13, second=10; char ch=' '; double x=12.6; • All variables must be initialized before they are used – But not necessarily during declaration
  • 24. 24 Input (Read) Statement • cin is used with >> to gather input • The stream extraction operator is >> • For example, if miles is a double variable cin >> miles; – Causes computer to get a value of type double – Places it in the variable miles
  • 25. 25 Input (Read) Statement (continued) • Using more than one variable in cin allows more than one value to be read at a time • For example, if feet and inches are variables of type int, a statement such as: cin >> feet >> inches; – Inputs two integers from the keyboard – Places them in variables feet and inches respectively
  • 26. 26 Output • The syntax of cout and << is: – Called an output statement • The stream insertion operator is << • Expression evaluated and its value is printed at the current cursor position on the screen
  • 27. 27 Output (continued) • A manipulator is used to format the output – endl causes insertion point to move to beginning of next line – Example:
  • 28. 28 Output (continued) • The new line character is 'n' – May appear anywhere in the string cout << "Hello there."; cout << "My name is James."; • Output: Hello there.My name is James. cout << "Hello there.n"; cout << "My name is James."; • Output : Hello there. My name is James.
  • 30. 30 Comments • Comments are for the reader, not the compiler • Two types: – Single line // This is a C++ program. It prints the sentence: // Welcome to C++ Programming. – Multiple line /* You can include comments that can occupy several lines. */
  • 31. 31 Documentation • A well-documented program is easier to understand and modify • You use comments to document programs • Comments should appear in a program to: – Explain the purpose of the program – Identify who wrote it – Explain the purpose of particular statements
  • 32. 32 Preprocessor Directives • C++ has a small number of operations • Many functions and symbols needed to run a C++ program are provided as collection of libraries • Every library has a name and is referred to by a header file • Preprocessor directives are commands supplied to the preprocessor • All preprocessor commands begin with # • No semicolon at the end of these commands
  • 33. 33 Preprocessor Directives (continued) • Syntax to include a header file: • For example: #include <iostream> The #include is a preprocessor directive used to include files in our program. This allows us to use cout in our program to print output on the screen and cin to take input from user.
  • 34. 34 namespace and Using cin and cout in a Program • cin and cout are declared in the header file iostream, but within std namespace • To use cin and cout in a program, use the following two statements: #include <iostream> using namespace std; • using namespace std means that we can use names for objects and variables from the standard library.
  • 35. 35 Creating a C++ Program • C++ program has two parts: – Preprocessor directives – The program • Preprocessor directives and program statements constitute C++ source code (.cpp) • Executable code is produced and saved in a file with the file extension .exe
  • 36. 36 Creating a C++ Program (continued) • A C++ program is a collection of functions, one of which is the function main • The first line of the function main is called the heading of the function: int main() • The statements enclosed between the curly braces ({ and }). • A valid C++ program must have the main() function. The curly braces indicate the start and the end of the function. • The execution of code beings from this function.
  • 37. 37 Creating a C++ Program Example: Body of the Function Program: #include <iostream> using namespace std; int main(){ cout<<“Hello World”; } Output: Hello World
  • 38. 38 Creating a C++ Program (continued)
  • 39. 39 Creating a C++ Program (continued) Sample Run: Line 9: firstNum = 18 Line 10: Enter an integer: 15 Line 13: secondNum = 15 Line 15: The new value of firstNum = 60
  • 40. 40 Program Style and Form • Every C++ program has a function main • It must also follow the syntax rules • Other rules serve the purpose of giving precise meaning to the language
  • 41. 41 Use of Semicolons, Brackets, and Commas • All C++ statements end with a semicolon – Also called a statement terminator • { and } are not C++ statements • Commas separate items in a list