SlideShare ist ein Scribd-Unternehmen logo
1 von 13
C++ Basics
Variables, Identifers
By D.Madhusudhan Reddy
107Y1A0572
Variables
variable can hold a number or a data of other types, it
always holds something. A variable has a name
the data held in variable is called value
variables are implemented as memory locations and
assigned certain memory address. The exact address
depends on computer and compiler.
we think as though the memory locations are actually
labeled with variable names
12.5
32
'c'
y
Temperature
Letter
1001
1002
1003
1004
1005
1006
1007
-Number 1008
1009
Identifiers
name of a variable (or any other item you define in program) is
called identifier
identifier must start with a letter or underscore symbol (_), the
rest of the characters should be letters, digits or underscores
the following are valid identifiers:
x x1 x_1 _abc sum RateAveragE
the following are not legal identifiers. Why?
13 3X %change data-1 my.identifier a(3)
C is case sensitive:
MyVar and myvar are different identifiers
What Are Good Identifiers?
careful selection of identifiers makes your program clearer
identifiers should be
short enough to be reasonable to type (single word is norm)
– Standard abbreviations are fine (but only standard abbreviations)
long enough to be understandable
two styles of identifiers
C-style - terse, use abbreviations and underscores to separate the words,
never use capital letters for variables
Pascal-style - if multiple words: capitalize, don’t use underscores
– camel Case – variant of Pascal-style with first letter lowercased
pick style and use consistently
ex: Pascal-style C-style Camel Case
Min min min
Temperature temperature temperature
CameraAngle camera_angle cameraAngle
CurrentNumberPoints cur_point_nmbr currentNumberPoints
Keywords
keywords are identifiers reserved as part of the language
int, return, float, double
they cannot be used by the programmer to name things
they consist of lowercase letters only
they have special meaning to the compiler
Keywords (cont.)
asm do if return typedef
auto double inline short typeid
bool dynamic_cast int signed typename
break delete long sizeof union
case else mutable static unsigned
catch enum namespace static_cast using
char explicit new struct virtual
class extern operator switch void
const false private template volatile
const_cast float protected this wchar_t
continue for public throw while
default friend register true union
delete goto reinterpret_cast try unsigned
Variable Declarations
every variable in C++ program needs to be declared
declaration tells the compiler (and eventually the computer) what
kind of data is going to be stored in the variable
the kind of data stored in variable is called it’s type
a variable declaration specifies
type
name
declaration syntax:
two commonly used numeric types are:
int - whole positive or negative numbers:
1,2, -1,0,-288, etc.
double - positive or negative numbers with fractional part:
1.75, -0.55
example declarations:
int numberOfBars;
double weight, totalWeight;
type id, id, ..., id;
known
type
list of one or
more identifiers
Where to Declare
the variables should be declared as close to the place where
they are used as possible.
if the variable will be used in several unrelated locations, declare
it at the beginning of the program:
int main() {
 right here
note that variable contains a value after it is declared. The value
is usually arbitrary
Assignment
assignment statement is an order to the computer to set the
value of the variable on the left hand side of the equation to what
is written on the right hand side
it looks like a math equation, but it is not
Example:
numberOfBars = 37;
totalWeight = oneWeight;
totalWeight = oneWeight * numberOfBars;
numberOfBars = numberOfBars + 3;
var = value;
Output
To do input/output, at the beginning of your program you have to insert
#include <iostream>
using std::cout; using std::endl;
C++ uses streams for input an output
stream - is a sequence of data to be read (input stream) or a sequence of data
generated by the program to be output (output stream)
variable values as well as strings of text can be output to the screen using cout
(console output):
cout << number_of_bars;
cout << ”candy bars”;
cout << endl;
<< is called insertion operator, it inserts data into the output stream, anything
within double quotes will be output literally (without changes) - ”candy bars
taste good”
note the space before letter “ c” - the computer does not inert space on its own
keyword endl tells the computer to start the output from the next line
More Output
the data in output can be stacked together:
cout << number_of_bars << ”candy barsn”
symbol n at the end of the string serves the same purpose as endl
arithmetic expressions can be used with the output statement:
cout << “The total cost is $” << (price + tax);
Escape Sequences
certain sequences of symbols make special meaning to the computer.
They are called escape sequences
escape sequence starts with a backslash (). It is actually just one special
character.
Useful escape sequences:
– new-line n
– horizontal tab t
– alert a
– backslash 
– double quote ”
What does this statement print?
cout << ”” this is a t very cryptic ” statement  n”;
Input
cin - (stands for Console INput) - is used to fill the values of variables with the
input from the user of the program
to use it, you need to add the following to the beginning of your program
using std::cin;
when the program reaches the input statement it just pauses until the user types
something and presses <Enter> key
therefore it is beneficial to precede the input statement with some explanatory
output called prompt:
cout << “Enter the number of candy bars
cout << “and weight in ounces.n”;
cout << “then press returnn”;
cin >> number_of_bars >> one_weight;
>> is extraction operator
dialog – collection of program prompts and user responses
note how input statements (similar to output statements) can be stacked
input tokens (numbers in our example) should be separated by (any amount of)
whitespace (spaces, tabs, newlines)
the values typed are inserted into variables when <Enter> is pressed, if more
values needed - program waits, if extra typed - they are used in next input
statements if needed

Weitere ähnliche Inhalte

Was ist angesagt?

C programming(Part 1)
C programming(Part 1)C programming(Part 1)
C programming(Part 1)SURBHI SAROHA
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)SURBHI SAROHA
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiSowmyaJyothi3
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)SURBHI SAROHA
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C ProgrammingKamal Acharya
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programmingSabik T S
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in cyazad dumasia
 
7. input and output functions
7. input and output functions7. input and output functions
7. input and output functionsWay2itech
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’eShikshak
 

Was ist angesagt? (19)

Basic Input and Output
Basic Input and OutputBasic Input and Output
Basic Input and Output
 
C programming(Part 1)
C programming(Part 1)C programming(Part 1)
C programming(Part 1)
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya Jyothi
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C Programming
 
CP Handout#2
CP Handout#2CP Handout#2
CP Handout#2
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in c
 
Unit ii ppt
Unit ii pptUnit ii ppt
Unit ii ppt
 
7. input and output functions
7. input and output functions7. input and output functions
7. input and output functions
 
C language basics
C language basicsC language basics
C language basics
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
 
Input And Output
 Input And Output Input And Output
Input And Output
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
 
CP Handout#8
CP Handout#8CP Handout#8
CP Handout#8
 
Foundations of Programming Part I
Foundations of Programming Part IFoundations of Programming Part I
Foundations of Programming Part I
 

Ähnlich wie L03vars

02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic Manzoor ALam
 
Chapter 3 - Variable Memory Concept
Chapter 3 - Variable Memory ConceptChapter 3 - Variable Memory Concept
Chapter 3 - Variable Memory ConceptDeepak Singh
 
2 EPT 162 Lecture 2
2 EPT 162 Lecture 22 EPT 162 Lecture 2
2 EPT 162 Lecture 2Don Dooley
 
Basics Of C++.pptx
Basics Of C++.pptxBasics Of C++.pptx
Basics Of C++.pptxDineshDhuri4
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Functionimtiazalijoono
 
Programming in C - interview questions.pdf
Programming in C - interview questions.pdfProgramming in C - interview questions.pdf
Programming in C - interview questions.pdfSergiuMatei7
 
C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance levelsajjad ali khan
 
C++ Overview
C++ OverviewC++ Overview
C++ Overviewkelleyc3
 
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docxINPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docxjaggernaoma
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxKrishanPalSingh39
 

Ähnlich wie L03vars (20)

keyword
keywordkeyword
keyword
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
 
Chapter2
Chapter2Chapter2
Chapter2
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
Chapter 3 - Variable Memory Concept
Chapter 3 - Variable Memory ConceptChapter 3 - Variable Memory Concept
Chapter 3 - Variable Memory Concept
 
2 EPT 162 Lecture 2
2 EPT 162 Lecture 22 EPT 162 Lecture 2
2 EPT 162 Lecture 2
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Basics Of C++.pptx
Basics Of C++.pptxBasics Of C++.pptx
Basics Of C++.pptx
 
C notes for exam preparation
C notes for exam preparationC notes for exam preparation
C notes for exam preparation
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 
Programming in C - interview questions.pdf
Programming in C - interview questions.pdfProgramming in C - interview questions.pdf
Programming in C - interview questions.pdf
 
C++ AND CATEGORIES OF SOFTWARE
C++ AND CATEGORIES OF SOFTWAREC++ AND CATEGORIES OF SOFTWARE
C++ AND CATEGORIES OF SOFTWARE
 
C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance level
 
C++ Overview
C++ OverviewC++ Overview
C++ Overview
 
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docxINPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
AS TASKS #8
AS TASKS #8AS TASKS #8
AS TASKS #8
 

Kürzlich hochgeladen

Farmer Representative Organization in Lucknow | Rashtriya Kisan Manch
Farmer Representative Organization in Lucknow | Rashtriya Kisan ManchFarmer Representative Organization in Lucknow | Rashtriya Kisan Manch
Farmer Representative Organization in Lucknow | Rashtriya Kisan ManchRashtriya Kisan Manch
 
From Goals to Actions: Uncovering the Key Components of Improvement Roadmaps
From Goals to Actions: Uncovering the Key Components of Improvement RoadmapsFrom Goals to Actions: Uncovering the Key Components of Improvement Roadmaps
From Goals to Actions: Uncovering the Key Components of Improvement RoadmapsCIToolkit
 
LPC Operations Review PowerPoint | Operations Review
LPC Operations Review PowerPoint | Operations ReviewLPC Operations Review PowerPoint | Operations Review
LPC Operations Review PowerPoint | Operations Reviewthomas851723
 
LPC Warehouse Management System For Clients In The Business Sector
LPC Warehouse Management System For Clients In The Business SectorLPC Warehouse Management System For Clients In The Business Sector
LPC Warehouse Management System For Clients In The Business Sectorthomas851723
 
Motivational theories an leadership skills
Motivational theories an leadership skillsMotivational theories an leadership skills
Motivational theories an leadership skillskristinalimarenko7
 
Simplifying Complexity: How the Four-Field Matrix Reshapes Thinking
Simplifying Complexity: How the Four-Field Matrix Reshapes ThinkingSimplifying Complexity: How the Four-Field Matrix Reshapes Thinking
Simplifying Complexity: How the Four-Field Matrix Reshapes ThinkingCIToolkit
 
原版1:1复刻密西西比大学毕业证Mississippi毕业证留信学历认证
原版1:1复刻密西西比大学毕业证Mississippi毕业证留信学历认证原版1:1复刻密西西比大学毕业证Mississippi毕业证留信学历认证
原版1:1复刻密西西比大学毕业证Mississippi毕业证留信学历认证jdkhjh
 
How-How Diagram: A Practical Approach to Problem Resolution
How-How Diagram: A Practical Approach to Problem ResolutionHow-How Diagram: A Practical Approach to Problem Resolution
How-How Diagram: A Practical Approach to Problem ResolutionCIToolkit
 
Fifteenth Finance Commission Presentation
Fifteenth Finance Commission PresentationFifteenth Finance Commission Presentation
Fifteenth Finance Commission Presentationmintusiprd
 
Shaping Organizational Culture Beyond Wishful Thinking
Shaping Organizational Culture Beyond Wishful ThinkingShaping Organizational Culture Beyond Wishful Thinking
Shaping Organizational Culture Beyond Wishful ThinkingGiuseppe De Simone
 
Introduction to LPC - Facility Design And Re-Engineering
Introduction to LPC - Facility Design And Re-EngineeringIntroduction to LPC - Facility Design And Re-Engineering
Introduction to LPC - Facility Design And Re-Engineeringthomas851723
 
Reflecting, turning experience into insight
Reflecting, turning experience into insightReflecting, turning experience into insight
Reflecting, turning experience into insightWayne Abrahams
 
Call Us🔝⇛+91-97111🔝47426 Call In girls Munirka (DELHI)
Call Us🔝⇛+91-97111🔝47426 Call In girls Munirka (DELHI)Call Us🔝⇛+91-97111🔝47426 Call In girls Munirka (DELHI)
Call Us🔝⇛+91-97111🔝47426 Call In girls Munirka (DELHI)jennyeacort
 
Unlocking Productivity and Personal Growth through the Importance-Urgency Matrix
Unlocking Productivity and Personal Growth through the Importance-Urgency MatrixUnlocking Productivity and Personal Growth through the Importance-Urgency Matrix
Unlocking Productivity and Personal Growth through the Importance-Urgency MatrixCIToolkit
 
Measuring True Process Yield using Robust Yield Metrics
Measuring True Process Yield using Robust Yield MetricsMeasuring True Process Yield using Robust Yield Metrics
Measuring True Process Yield using Robust Yield MetricsCIToolkit
 
Beyond the Five Whys: Exploring the Hierarchical Causes with the Why-Why Diagram
Beyond the Five Whys: Exploring the Hierarchical Causes with the Why-Why DiagramBeyond the Five Whys: Exploring the Hierarchical Causes with the Why-Why Diagram
Beyond the Five Whys: Exploring the Hierarchical Causes with the Why-Why DiagramCIToolkit
 
Effective learning in the Age of Hybrid Work - Agile Saturday Tallinn 2024
Effective learning in the Age of Hybrid Work - Agile Saturday Tallinn 2024Effective learning in the Age of Hybrid Work - Agile Saturday Tallinn 2024
Effective learning in the Age of Hybrid Work - Agile Saturday Tallinn 2024Giuseppe De Simone
 
Paired Comparison Analysis: A Practical Tool for Evaluating Options and Prior...
Paired Comparison Analysis: A Practical Tool for Evaluating Options and Prior...Paired Comparison Analysis: A Practical Tool for Evaluating Options and Prior...
Paired Comparison Analysis: A Practical Tool for Evaluating Options and Prior...CIToolkit
 
Management and managerial skills training manual.pdf
Management and managerial skills training manual.pdfManagement and managerial skills training manual.pdf
Management and managerial skills training manual.pdffillmonipdc
 

Kürzlich hochgeladen (20)

Farmer Representative Organization in Lucknow | Rashtriya Kisan Manch
Farmer Representative Organization in Lucknow | Rashtriya Kisan ManchFarmer Representative Organization in Lucknow | Rashtriya Kisan Manch
Farmer Representative Organization in Lucknow | Rashtriya Kisan Manch
 
From Goals to Actions: Uncovering the Key Components of Improvement Roadmaps
From Goals to Actions: Uncovering the Key Components of Improvement RoadmapsFrom Goals to Actions: Uncovering the Key Components of Improvement Roadmaps
From Goals to Actions: Uncovering the Key Components of Improvement Roadmaps
 
LPC Operations Review PowerPoint | Operations Review
LPC Operations Review PowerPoint | Operations ReviewLPC Operations Review PowerPoint | Operations Review
LPC Operations Review PowerPoint | Operations Review
 
LPC Warehouse Management System For Clients In The Business Sector
LPC Warehouse Management System For Clients In The Business SectorLPC Warehouse Management System For Clients In The Business Sector
LPC Warehouse Management System For Clients In The Business Sector
 
Motivational theories an leadership skills
Motivational theories an leadership skillsMotivational theories an leadership skills
Motivational theories an leadership skills
 
Simplifying Complexity: How the Four-Field Matrix Reshapes Thinking
Simplifying Complexity: How the Four-Field Matrix Reshapes ThinkingSimplifying Complexity: How the Four-Field Matrix Reshapes Thinking
Simplifying Complexity: How the Four-Field Matrix Reshapes Thinking
 
原版1:1复刻密西西比大学毕业证Mississippi毕业证留信学历认证
原版1:1复刻密西西比大学毕业证Mississippi毕业证留信学历认证原版1:1复刻密西西比大学毕业证Mississippi毕业证留信学历认证
原版1:1复刻密西西比大学毕业证Mississippi毕业证留信学历认证
 
How-How Diagram: A Practical Approach to Problem Resolution
How-How Diagram: A Practical Approach to Problem ResolutionHow-How Diagram: A Practical Approach to Problem Resolution
How-How Diagram: A Practical Approach to Problem Resolution
 
Fifteenth Finance Commission Presentation
Fifteenth Finance Commission PresentationFifteenth Finance Commission Presentation
Fifteenth Finance Commission Presentation
 
Shaping Organizational Culture Beyond Wishful Thinking
Shaping Organizational Culture Beyond Wishful ThinkingShaping Organizational Culture Beyond Wishful Thinking
Shaping Organizational Culture Beyond Wishful Thinking
 
Introduction to LPC - Facility Design And Re-Engineering
Introduction to LPC - Facility Design And Re-EngineeringIntroduction to LPC - Facility Design And Re-Engineering
Introduction to LPC - Facility Design And Re-Engineering
 
Reflecting, turning experience into insight
Reflecting, turning experience into insightReflecting, turning experience into insight
Reflecting, turning experience into insight
 
Call Us🔝⇛+91-97111🔝47426 Call In girls Munirka (DELHI)
Call Us🔝⇛+91-97111🔝47426 Call In girls Munirka (DELHI)Call Us🔝⇛+91-97111🔝47426 Call In girls Munirka (DELHI)
Call Us🔝⇛+91-97111🔝47426 Call In girls Munirka (DELHI)
 
Unlocking Productivity and Personal Growth through the Importance-Urgency Matrix
Unlocking Productivity and Personal Growth through the Importance-Urgency MatrixUnlocking Productivity and Personal Growth through the Importance-Urgency Matrix
Unlocking Productivity and Personal Growth through the Importance-Urgency Matrix
 
Measuring True Process Yield using Robust Yield Metrics
Measuring True Process Yield using Robust Yield MetricsMeasuring True Process Yield using Robust Yield Metrics
Measuring True Process Yield using Robust Yield Metrics
 
Beyond the Five Whys: Exploring the Hierarchical Causes with the Why-Why Diagram
Beyond the Five Whys: Exploring the Hierarchical Causes with the Why-Why DiagramBeyond the Five Whys: Exploring the Hierarchical Causes with the Why-Why Diagram
Beyond the Five Whys: Exploring the Hierarchical Causes with the Why-Why Diagram
 
Effective learning in the Age of Hybrid Work - Agile Saturday Tallinn 2024
Effective learning in the Age of Hybrid Work - Agile Saturday Tallinn 2024Effective learning in the Age of Hybrid Work - Agile Saturday Tallinn 2024
Effective learning in the Age of Hybrid Work - Agile Saturday Tallinn 2024
 
Paired Comparison Analysis: A Practical Tool for Evaluating Options and Prior...
Paired Comparison Analysis: A Practical Tool for Evaluating Options and Prior...Paired Comparison Analysis: A Practical Tool for Evaluating Options and Prior...
Paired Comparison Analysis: A Practical Tool for Evaluating Options and Prior...
 
Management and managerial skills training manual.pdf
Management and managerial skills training manual.pdfManagement and managerial skills training manual.pdf
Management and managerial skills training manual.pdf
 
sauth delhi call girls in Defence Colony🔝 9953056974 🔝 escort Service
sauth delhi call girls in Defence Colony🔝 9953056974 🔝 escort Servicesauth delhi call girls in Defence Colony🔝 9953056974 🔝 escort Service
sauth delhi call girls in Defence Colony🔝 9953056974 🔝 escort Service
 

L03vars

  • 1. C++ Basics Variables, Identifers By D.Madhusudhan Reddy 107Y1A0572
  • 2. Variables variable can hold a number or a data of other types, it always holds something. A variable has a name the data held in variable is called value variables are implemented as memory locations and assigned certain memory address. The exact address depends on computer and compiler. we think as though the memory locations are actually labeled with variable names 12.5 32 'c' y Temperature Letter 1001 1002 1003 1004 1005 1006 1007 -Number 1008 1009
  • 3. Identifiers name of a variable (or any other item you define in program) is called identifier identifier must start with a letter or underscore symbol (_), the rest of the characters should be letters, digits or underscores the following are valid identifiers: x x1 x_1 _abc sum RateAveragE the following are not legal identifiers. Why? 13 3X %change data-1 my.identifier a(3) C is case sensitive: MyVar and myvar are different identifiers
  • 4. What Are Good Identifiers? careful selection of identifiers makes your program clearer identifiers should be short enough to be reasonable to type (single word is norm) – Standard abbreviations are fine (but only standard abbreviations) long enough to be understandable two styles of identifiers C-style - terse, use abbreviations and underscores to separate the words, never use capital letters for variables Pascal-style - if multiple words: capitalize, don’t use underscores – camel Case – variant of Pascal-style with first letter lowercased pick style and use consistently ex: Pascal-style C-style Camel Case Min min min Temperature temperature temperature CameraAngle camera_angle cameraAngle CurrentNumberPoints cur_point_nmbr currentNumberPoints
  • 5. Keywords keywords are identifiers reserved as part of the language int, return, float, double they cannot be used by the programmer to name things they consist of lowercase letters only they have special meaning to the compiler
  • 6. Keywords (cont.) asm do if return typedef auto double inline short typeid bool dynamic_cast int signed typename break delete long sizeof union case else mutable static unsigned catch enum namespace static_cast using char explicit new struct virtual class extern operator switch void const false private template volatile const_cast float protected this wchar_t continue for public throw while default friend register true union delete goto reinterpret_cast try unsigned
  • 7. Variable Declarations every variable in C++ program needs to be declared declaration tells the compiler (and eventually the computer) what kind of data is going to be stored in the variable the kind of data stored in variable is called it’s type a variable declaration specifies type name declaration syntax: two commonly used numeric types are: int - whole positive or negative numbers: 1,2, -1,0,-288, etc. double - positive or negative numbers with fractional part: 1.75, -0.55 example declarations: int numberOfBars; double weight, totalWeight; type id, id, ..., id; known type list of one or more identifiers
  • 8. Where to Declare the variables should be declared as close to the place where they are used as possible. if the variable will be used in several unrelated locations, declare it at the beginning of the program: int main() {  right here note that variable contains a value after it is declared. The value is usually arbitrary
  • 9. Assignment assignment statement is an order to the computer to set the value of the variable on the left hand side of the equation to what is written on the right hand side it looks like a math equation, but it is not Example: numberOfBars = 37; totalWeight = oneWeight; totalWeight = oneWeight * numberOfBars; numberOfBars = numberOfBars + 3; var = value;
  • 10. Output To do input/output, at the beginning of your program you have to insert #include <iostream> using std::cout; using std::endl; C++ uses streams for input an output stream - is a sequence of data to be read (input stream) or a sequence of data generated by the program to be output (output stream) variable values as well as strings of text can be output to the screen using cout (console output): cout << number_of_bars; cout << ”candy bars”; cout << endl; << is called insertion operator, it inserts data into the output stream, anything within double quotes will be output literally (without changes) - ”candy bars taste good” note the space before letter “ c” - the computer does not inert space on its own keyword endl tells the computer to start the output from the next line
  • 11. More Output the data in output can be stacked together: cout << number_of_bars << ”candy barsn” symbol n at the end of the string serves the same purpose as endl arithmetic expressions can be used with the output statement: cout << “The total cost is $” << (price + tax);
  • 12. Escape Sequences certain sequences of symbols make special meaning to the computer. They are called escape sequences escape sequence starts with a backslash (). It is actually just one special character. Useful escape sequences: – new-line n – horizontal tab t – alert a – backslash – double quote ” What does this statement print? cout << ”” this is a t very cryptic ” statement n”;
  • 13. Input cin - (stands for Console INput) - is used to fill the values of variables with the input from the user of the program to use it, you need to add the following to the beginning of your program using std::cin; when the program reaches the input statement it just pauses until the user types something and presses <Enter> key therefore it is beneficial to precede the input statement with some explanatory output called prompt: cout << “Enter the number of candy bars cout << “and weight in ounces.n”; cout << “then press returnn”; cin >> number_of_bars >> one_weight; >> is extraction operator dialog – collection of program prompts and user responses note how input statements (similar to output statements) can be stacked input tokens (numbers in our example) should be separated by (any amount of) whitespace (spaces, tabs, newlines) the values typed are inserted into variables when <Enter> is pressed, if more values needed - program waits, if extra typed - they are used in next input statements if needed

Hinweis der Redaktion

  1. Alt+8 to dsiplay in MSVS executable code