Us C++ 2021 04
Us C++ 2021 04
Us C++ 2021 04
int foo;
int *x;
foo = 123;
x = &foo;
foo = foo + 5;
// *x = *x+5;
Example
Assigning a value to a
dereferenced pointer
A pointer must have a value before you can
dereference it (follow the pointer).
x some int
int *x;
int **y; y some *int some int
int *x;
int a[10]; x is “the address of a[2] ”
x = &a[2];
for (int i=0;i<3;i++)
x[i]= x[i]+1;
x[i] is the same as a[i+2]
Pointer arithmetic
Integer math operations can be used with pointers.
If you increment a pointer, it will be increased by the
size of whatever it points to.
int *ptr = a;
*(ptr+2)
*(ptr+4)
*ptr
msg
int count;
int &blah = count;
Example
void add10( int &x) {
x = x+10;
}
…
add10(counter);
triangle(4); triangle(5);
* *
*** ***
***** *****
******* *******
*********
Exercise 2
Write a strcpy function that copys a
string to another one.
Write a strcmp function that compares 2 strings and
returns true if they are the same string, false if they
are not.
Write a strspc function that removes all spaces from a
string.
Exercise 3
(Square of Asterisks) Write a function that displays at
the left margin of the screen a solid square of asterisks
whose side is specified in integer parameter side. For
example, if side is 4, the function displays the following:
* * * *
* * * *
* * * *
* * * *
char8(5);
* * * * *
* *
* * * * *
* *
* * * * *
Exercise 7
Write a function that prints a solid inverse triangle
solinvtriangle(4);
*******
*****
***
*
Write a function that prints an inverse triangle
invtriangle(4);
*******
* *
* *
*
Exercise 8
Write a program to pass in a integer number. Output
2 numbers: one number includes the odd position
number characters, another includes the even
position number characters. Calculate the total of the
two numbers.
Ex:
Input: 245387
Output: 258 and 437
Total: 695
Any Questions?
[email protected]
Quiz #4
(Prime Numbers) An integer is said to be prime if it’s
divisible by only 1 and itself. For example, 2, 3, 5 and 7
are prime, but 4, 6, 8 and 9 are not.
a) Write a function that determines whether a number is
prime.
b) Use this function in a program that determines and
prints all the prime numbers between 2 and 10,000.
How many of these numbers do you really have to test
before being sure that you’ve found all the primes?
c) Initially, you might think that n/2 is the upper limit for
which you must test to see whether a number is prime,
but you need only go as high as the square root of n.
Why? Rewrite the program, and run it both ways.
Estimate the performance improvement.