The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Lecture/Lab #8
Scope of a name, user-defined types (struct)
What's an idiomatic way to increment an integer in C++?
Is this valid C++? If so, what will be the output of this snippet when x is equal to 17?
if ( x >= 0 )
if ( x < 10 )
std::cout << "x is in the [0, 10) interval\n";
else
std::cout << "x is negative\n";
Is this valid C++? If so, what does it do?
for ( ; ; )
std::cout << "Hi there...\n";
What does the following function do?
void foo( int n )
{
switch ( n )
{
case 9: std::cout << "9 ";
case 8: std::cout << "8 ";
case 7: std::cout << "7 ";
case 6: std::cout << "6 ";
case 5: std::cout << "5 ";
case 4: std::cout << "4 ";
case 3: std::cout << "3 ";
case 2: std::cout << "2 ";
case 1: std::cout << "1 ";
case 0: std::cout << "0 ";
}
std::cout << "the end\n";
}
void foo() { n = 42; }
int main() {
int n = 0;
foo();
std::cout << n << "\n";
}
def foo():
n = 42
def main():
n = 0
foo()
print(n)
main()
#include <iostream>
int sum = 0;
void compute( int x, int y ) {
sum = x + y;
}
int main() {
int sum = -1;
compute( 2, 2 );
float pi = 3.14;
std::cout << pi << "\n";
if ( sum < 0 ) {
double pi = 3.14159;
std::cout << pi << "\n";
}
std::cout << sum << "\n";
}
Global aka namespace scope
sum
compute
main
main function scope
sum
pi
if block scope
pi
Use your understanding of variable scopes and programming best practices to correct the following program
Open the exercise template
Write your code, press Run to test
When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)
Click on the corresponding option in the "Lab8 exercises" poll in #general
char, int, double, unsigned long long
string("hello, ") + name
Defining a basic data structure type
#include <iostream>
void draw_line( int x1, int y1, int x2, int y2 )
{
std::cout
<< "draw_line: ("
<< x1 << ", " << y1 << ")-("
<< x2 << ", " << y2 << ")\n";
}
void draw_rect( int x1, int y1, int x2, int y2 );
void draw_triangle( int x1, int y1, int x2, int y2,
int x3, int y3 );
int main() {
draw_line( 0, 0, 10, 10 );
draw_line( 10, 0, 10, 0 );
}
struct point
{
point( int x, int y )
: x( x ), y( y )
{}
int x;
int y;
};
point p( 1, -1 );
std::cout << p.x + p.y << "\n";
class point():
def __init__( self, x, y ):
self.x = x
self.y = y
p = point( 1, -1 )
print( p.x + p.y )
Write a function that adds two points and a function that compares two points for equality
Open the exercise template
Write your code, press Run to test
When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)
Click on the corresponding option in the "Lab8 exercises" poll in #general