0% found this document useful (0 votes)
490 views12 pages

Variables and Assignments

The document discusses variables in programming. It explains that a variable is a named item used to hold a value, like x or numPeople. An assignment statement assigns a variable a value, such as x = 5. The left side of the assignment must be a variable, while the right side can be an expression that evaluates to a value. Subsequent assignments can change the value of a variable. For example, x is initially 5, but then x = 3 assigns it the value of 3, overwriting the previous value.

Uploaded by

Rose
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
490 views12 pages

Variables and Assignments

The document discusses variables in programming. It explains that a variable is a named item used to hold a value, like x or numPeople. An assignment statement assigns a variable a value, such as x = 5. The left side of the assignment must be a variable, while the right side can be an expression that evaluates to a value. Subsequent assignments can change the value of a variable. For example, x is initially 5, but then x = 3 assigns it the value of 3, overwriting the previous value.

Uploaded by

Rose
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

By the way, the real riddle's ending question is actually "What is the bus driver's name?

"— the subject


usually says "How should I know?". The riddler then says "I started with YOU are driving a bus."
The box above served the same purpose as a variable in a program, introduced below.

Variables and assignments

In a program, a variable is a named item, such as x or numPeople, used to hold a value.


An assignment statement assigns a variable with a value, such as x = 5. That statement means x is
assigned with 5, and x keeps that value during subsequent statements, until x is assigned again.
An assignment statement's left side must be a variable. The right side can be an expression, so a statement
may be x = 5, y = x, or z = x + 2. The 5, x, and x + 2 are each an expression that evaluates to a value.

y = x assigns y with x's value, which presently is 5. z = x + 2 assigns z with x's present value plus 2, so 5
+ 2 or 7.

A subsequent x = 3 statement assigns x with 3. x's former value of 5 is overwritten and thus lost. Note
that the values held in y and z are unaffected, remaining as 5 and 7.

X+1=3 (invalid)

The left side must be a variable, not an expression like x + 1. In programming, = does not mean equal. =
means assign the left-side variable with the right-side's value. Thus, the left side MUST be a variable.

x=9
y=3
z=0
x=4
y=6

X is 4; y is 6 and z is 0

#include <iostream>
using namespace std;

int main() {
int userAge;

cout << "Enter your age: ";


cin >> userAge;
cout << userAge << " is a great age." << endl;

return 0;

Declare an integer variable named numPeople. (Do not initialize the variable.)
int numPeople;

What memory location (address) will a compiler allocate for the variable declaration below. If
appropriate, type: Unknown

int numHouses = 99; answer is unknown

Write an assignment statement to assign numCars with 99. (numCars = 99;)

Assign numFruit with the current value of numApples. (numFruit = numApples;)

The current value in houseRats is 200. What is in houseRats after executing the statement below? Valid
answers: 0, 199, 200, or unknown. (200)

Assign numItems with the result of ballCount - 3. (numItems = ballCount - 3;)

dogCount is 5. What is in dogCount after executing the statement below? (5)

What is in numBooks after both statements execute?

numBooks = 5;
numBooks = 3;
answer = 3

Type the program's output


#include <iostream>
using namespace std;

int main() {
int x;
int y;

x = 9;
y = 6;

cout << x << " " <<


y;

return 0;
Ans = 9 6

Type the program's output


#include <iostream>
using namespace std;

int main() {
int x;
int y;

x = 6;
y = 3;
x = 7;

cout << x << " " <<


y;

return 0;
Ans = 7 3

Type the program's output


#include <iostream>
using namespace std;

int main() {
int x;
int y;

y = 4;
x = y;

cout << x << " " <<


y;

return 0;
Ans 4 4

Type the program's output


#include <iostream>
using namespace std;

int main() {
int x;
int y;

y = 6;
x = y + 4;

cout << x << " " <<


y;

return 0;
Ans = 10 6

Type the program's output


#include <iostream>
using namespace std;

int main() {
int a;
int x;
int y;

a = 5;
x = a + 5;
y = 13;

cout << x << " " <<


y;

return 0;
Ans = 10 13

#include <iostream>
using namespace std;

int main() {
int numCoins;
int numNickels;
int numDimes;

numNickels = 5;
numDimes = 6;

numCoins=numNickels+numDimes;

cout << "There are " << numCoins << " coins" << endl;

return 0;
Declare an integer variable named numDogs, initializing the variable to 0 in the declaration. Int numDogs
=0;

Write one statement that declares an integar variable numHouses initialized to 25

#include <iostream>
using namespace std;

int main() {

int numHouses = 25;

cout << numHouses << endl;

return 0;
}
Write a statement ending with - 1 that decreases variable flyCount's value by flyCount = flyCount -1;
Write a statement that increases numPeople by 5. Ex: If numPeople is initially 10, the output is: There are
15 people.
#include <iostream>
using namespace std;

int main() {
int numPeople;

numPeople = 10;

numPeople = numPeople +5;

cout << "There are " << numPeople << " people." << endl;

return 0;

Rules for identifiers

A name created by a programmer for an item like a variable or function is called an identifier. An
identifier must:

 be a sequence of letters (a-z, A-Z), underscores (_), and digits (0-9)


 start with a letter or underscore

Note that "_", called an underscore, is considered to be a letter.


Identifiers are case sensitive, meaning upper and lower case letters differ. So numCats and NumCats are
different.
A reserved word is a word that is part of the language, like int, short, or double. A reserved word is also
known as a keyword. A programmer cannot use a reserved word as an identifier. Many language editors
will automatically color a program's reserved words. A list of reserved words appears at the end of this
section.

Style guidelines for identifiers

While various (crazy-looking) identifiers may be valid, programmers may follow identifier naming
conventions (style) defined by their company, team, teacher, etc. Two common conventions for naming
variables are:

 Camel case: Lower camel case abuts multiple words, capitalizing each word except the first, as in
numApples or peopleOnBus.
 Underscore separated: Words are lowercase and separated by an underscore, as in num_apples or
people_on_bus.

Neither convention is better. The key is to be consistent so code is easier to read and maintain.
Good practice is to create meaningful identifier names that self-describe an item's purpose. Good
practice minimizes use of abbreviations in identifiers except for well-known ones like num in
numPassengers. Programmers must strive to find a balance. Abbreviations make programs harder to read
and can lead to confusion. Long variable names, such as averageAgeOfUclaGraduateStudent may be
meaningful, but can make subsequent statements too long and thus hard to read.
Choose the "best" identifier for a variable with the stated purpose, given the above discussion.

1)The number of students attending UCLA. ( numStudentsUcla)


2)The size of an LCD monitor
size
sizeLcdMonitor
s
sizeLcdMtr

Correct
Lcd is abbreviated but may be OK.

3)
The number of jelly beans in a jar.
numberOfJellyBeansInTheJar
jellyBeansInJar

nmJlyBnsInJr

Commas are not allowed in an integer literal. So 1,333,555 is written as 1333555.


PARTICIPATION ACTIVITY
2.5.4: Expression in statements.

1)
Is the following an error? Suppose an int's maximum value is 2,147,483,647.
numYears = 1,999,999,999; (yes)

Which variable is used for the user's age in years? (userAgeYears)

If the user enters 10, what is userAgeDays assigned? userAgeDays is assigned with


userAgeYears * 365, which is 10 * 365, or 3650.

If the user enters 20, what is userAgeDays after the second assignment


statement? The second assignment statement assigns userAgeDays with 7300 + (20 / 4), which
is 7300 + 5 or 7305.
#include <iostream>
using namespace std;

int main() {
int userAgeYears;
int userAgeDays;
int userAgeMinutes;
int totalHeartbeats;
int avgBeatsPerMinute = 72;

cout << "Enter your age in years: ";


cin >> userAgeYears;

userAgeDays = userAgeYears * 365; // Calculate days without leap


years
userAgeDays = userAgeDays + (userAgeYears / 4); // Add days for leap years

cout << "You are " << userAgeDays << " days old." << endl;

userAgeMinutes = userAgeDays * 24 * 60; // 24 hours/day, 60 minutes/hour


cout << "You are " << userAgeMinutes << " minutes old." << endl;

totalHeartbeats = userAgeMinutes * avgBeatsPerMinute;


cout << "Your heart has beat " << totalHeartbeats << " times." << endl;

return 0;
}
Enter your age in years: 19
You are 6939 days old.
You are 9992160 minutes old.
Your heart has beat 719435520 times.

#include <iostream>
using namespace std;

int main() {
int x;
int y;

x = 1;
y = 3 * (x + 9);

cout << x << " " << y;

return 0; 1 30

#include <iostream>
using namespace std;

int main() {
int x;
int y;

x = 5;
y = x / 2;

cout << x << " " << y;


return 0; 5 2

If initMass is 10.0, growthRate is 1.0 (100%), and yearsGrow is 3, what is finalMass?


finalMass = initMass * Math.pow(1.0 + growthRate, yearsGrow);
80.0

10.0 * Math.pow(1.0 + 1.0, 3.0)


10.0 * Math.pow(2.0, 3.0)
10.0 * 8.0
80.0
A drink costs 2 dollars. A taco costs 4 dollars. Given the number of each, compute total cost and assign
totalCost with the result. Ex: 4 drinks and 6 tacos yields totalCost of 32.

#include <iostream>
using namespace std;
int main() {
int numDrinks;
int numTacos;
int totalCost;
cin >> numDrinks;
cin >> numTacos;
totalCost = (2 * numDrinks) + (4 * numTacos);
cout << "Total cost: " << totalCost << endl;
return 0;
}

Kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
k
Given sphereRadius and piVal, compute the volume of a sphere and assign sphereVolume
with the result. Use (4.0 / 3.0) to perform floating-point division, instead of (4 / 3) which
performs integer division.

Volume of sphere = (4.0 / 3.0) π r3 (Hint: r3 can be computed using *)

#include <iostream>

using namespace std;


int main() {
double piVal = 3.14159;
double sphereVolume;
double sphereRadius;
sphereRadius = 1.0;
sphereVolume = (4.0 / 3.0) * piVal * (sphereRadius * sphereRadius
* sphereRadius);
cout << "Sphere volume: " << sphereVolume << endl;
return 0;

The cost to ship a package is a flat fee of 75 cents plus 25 cents per
pound.
1. Declare a const named CENTS_PER_POUND and initialize with
25.
2. Get the shipping weight from user input storing the weight into
shipWeightPounds.
3. Using FLAT_FEE_CENTS and CENTS_PER_POUND constants,
assign shipCostCents with the cost of shipping a package weighing
shipWeightPounds.
Simple geometry can compute the height of an object from the
object's shadow length and shadow angle using the formula:
tan(angleElevation) = treeHeight / shadowLength.
1. Using simple algebra, rearrange that equation to solve for
treeHeight.
2. Write a statement to assign treeHeight with the height calculated
from an expression using angleElevation and shadowLength.#include
<iostream>
#include <cmath>
using namespace std;

int main( ) {
double treeHeight;
double shadowLength;
double angleElevation;

angleElevation = 0.11693706; // 0.11693706 radians = 6.7 degrees


shadowLength = 17.5;

cout << "Enter the length of shadow: ";


cin >> shadowLength;
cout << "Enter the angle of elevation in radians: ";
cin >> angleElevation;
treeHeight = shadowLength * tan(angleElevation);

cout << "Tree height: " << treeHeight << endl;

return 0;

A cashier distributes change using the maximum number of five dollar bills, followed
by one dollar bills. For example, 19 yields 3 fives and 4 ones. Write a single
statement that assigns the number of 1 dollar bills to variable numOnes, given
amountToChange. Hint: Use the % operator.
#include <iostream>
using namespace std;

int main() {
int amountToChange;
int numFives;
int numOnes;

amountToChange = 19;
numFives = amountToChange / 5;

numOnes = amountToChange % 5;

cout << "numFives: " << numFives << endl;


cout << "numOnes: " << numOnes << endl;

return 0;
}

Compute the average kids per family. Note that the integers should
be type cast to doubles.
#include <iostream>
using namespace std;

int main() {
int numKidsA;
int numKidsB;
int numKidsC;
int numFamilies;
double avgKids;

numKidsA = 1;
numKidsB = 4;
numKidsC = 5;
numFamilies = 3;

avgKids = (numKidsA + numKidsB + numKidsC) / (double)numFamilies;


cout << avgKids << endl;

cout << "Average kids per family: " << avgKids << endl;

return 0;
A user
Amy_5

#include
<iostream
>
#include <string>
using namespace std;
/*
A user types a word and a number on a single line. Read
them into the provided variables. Then print: word_number. End
with newline. Example output if user entered: Amy 5
Amy_5
*/
int main() {
string userWord;
int userNum = 0;
/* Your solution goes here */
cin >> userWord;
cin >> userNum;
cout << userWord << "_" << userNum << endl;

In the example below, if a user inputs an age less than


25, the statement insurancePrice =
4800 executes. Otherwise, insurancePrice =
2200 executes.
PARTICIPATION ACTIVITY
3.2.3: if-else statement: Car insurance.

123
2x speed
22
#include <iostream>
using namespace std;

int main() {
int userAge;
int insurancePrice;

cout << "Enter age: ";


cin >> userAge;

if (userAge < 25) {


insurancePrice = 4800;
}
else {
insurancePrice = 2200;
}

cout << "Annual price: $";


cout << insurancePrice << endl;

return 0;
}

You might also like