00000000 00000001 00000010 00000011 00000100 ... 11111111
00100001
:
int DayOfMonth; // an integer from 0 .. 31 int RockCount; // counting rocks thrown at a lecturer(Note: unlike the real world, there is a limit to the size of integer the system can represent)
float Price; // the cost of an item in $, e.g. $3.40 float Temperature; // e.g. 34.5 degrees(Again, the size and accuracy of real numbers is limited)
char Initial; // someone's middle initial char Command; // e.g. enter C to continue or Q to quitA list of the printable characters is on page 649 of the text
scanf("%d", &foo); // read an integer value and store it in foo
x = y;
(copies a value from variable y into variable x)
w = x + 17 + (y * z);
, (takes the current values stored in x, y,
and z, multiplies the y and z values, adds the values of x and 17, and stores the
result as the new value for variable w)
x = x + 1;
(takes the current value of x, adds 1, and
stores the result as the new value for x)
<cstdio>
library, and is called printf
printf
command
to print out data values we are interested in.
(Because of this, use of literal values is sometimes called "hardcoding" data - the data is fixed within the program, and not open to user modification.)
Some examples are given below.
char SomeCharacter; int AnInteger; float ARealNumber; // hardcoding values ARealNumber = 17.7; AnInteger = -300; SomeCharacter = 'L'; printf("%f", ARealNumber); // prints out the value 17.7 printf("%d", AnInteger); // prints out the value -300 printf("%c", SomeCharacter); // prints out the character L
This assigns a name to the value, and that value is then used throughout the program to refer to that specific value.
For instance, suppose we wrote a program that used the value of Pi for a variety of calculations. We could create a constant that holds the value of Pi as follows:
// example declaration of a constant const float Pi = 3.14; // sample uses of the constant printf( "The value of Pi is %f\n", Pi); float circleDiameter = 1.5; float circleCircumference = circleDiameter * Pi; printf( "For a circle with a diameter of %f ",\n", circleDiameter); printf( " the cirumference is %f\n", circleCircumference);The two main advantages to the use of constants are
For example, if we wanted to use 3.1415 as
the value of Pi, we would only need to change the single line to
const float Pi = 3.1415; rather than needing to search
the code (and risk missing one or more instances).
Doing things one character at a time is irritating for storing names, sentences, etc (imagine having to have a different variable declared for every single character in a name or sentence...)
To get around this, a string literal can be used for output, and is denoted by a pair of double-quotes
printf( "This is a string"); printf( "So is this");Strings are printed exactly as they appear, so the output from the above would look like
This is a stringSo is thisThe special character sequence
\n
can be used to insert a newline character
printf( "This is a string\n"); printf( "So is this");Would produce output
This is a string So is thisC++ comes with a string library that defines a string data type, but its storage format is a little special, so we use a conversion routine called .c_str() to help printf extract the right text from it, e.g.
#include <cstdio> #include <string> int main() { std::string msg = "Hello world!"; printf("%s\n", msg.c_str()); return 0; }
Below we give examples of some basic arithmetic using a set of variables we will declare:
int x, y, z; // creates data storage for 3 integers float A, B, C; // creates data storage for 3 floating point numbers
x = (y + 17) + z;
B = -0.314 - B;
y = (y * y) * 4;
C = C / 3.1415;
x = 100 / 16; // will give x = 6
x = 100 % 16; // will give x = 4
=
must be same
A = x;
x = (+6+7);The first plus is treated as a positive (since it only has one operand to work with, the second as an addition)
12 - 3 - 1
we need to know whether this means 12 - (3 - 1)
or
(12 - 3) - 1
The set of rules used to determine the order of operations is called operator precedence, and in C++ operates as follows:
Z * 17 - 32 + X - Y / X * Yis equivalent to
(((Z * 17) - 32) + X) - ((Y / X) * Y)
char
for character data
int
for integers, long
for large integers
float
for floating point numbers, double
for
bigger numbers
and better accuracy
int x, y; // legal x = 3; y = -x; x = (x - 17) * (y + 230); // illegal (x - 17) = y;
int x; int y; y = x + 17; printf("Y is %d\n", y);Could give output
Y is -17893046
int x = 0; int y = 17; // has same effect as int x, y; x = 0; y = 17;
int
, float
limitations1000 0000 = -128 ... 1111 1110 = -2 1111 1111 = -1 0000 0000 = 0 0000 0001 = 1 0000 0010 = 2 ... 0111 1111 = 127
short
)
Assume 8 decimal places of accuray 2003004000000 + 16000 + 0.035 Correct answer is 2003004016000.035 The computer answer would be 2003004000000
#include <cstdio> const float Pi = 3.1415; int main() { float v, w, x, y, z, goodsum, badsum; printf( "Enter 5 real numbers, "); printf( "from smallest to largest\n"); scanf("%f", &v); scanf("%f", &w); scanf("%f", &x); scanf("%f", &y); scanf("%f", &z); goodsum = v + w + x + y + z; badsum = z + y + x + w + v; printf( "Adding them from smallest to largest"); printf( " gives %f\n", goodsum); printf( "Adding from largest to smallest gives "); printf( "%f\n", badsum); }
++
x++;
--
x--;
+=
x += 17;
*=
x *= 4;
#include <cstdio> #include <climits> #include <cfloat> int main() { printf("The largest positive integer is "); printf("%d\n", INT_MAX); printf( "The smallest negative integer is "); printf("%d\n", INT_MIN); printf( "The largest real number is "); printf("%f\n", FLT_MAX); printf( "The smallest negative float is "); printf("%f\n", FLT_MIN); printf( The maximum precision (digits) is "); printf("%d\n", FLT_DIG); }
/ this program will calculate the area of a square #include <cstdio> int main() { int area; / store calculated area of square int side; / input length of side of square printf( "How wide is the square?" << endl; scanf("%d", &side); area = side * side; printf( "The square has area %area"\n); }
// this program prints information about the author int main() { printf( 'This program was written by Dave Wessels'); printf( 'He didn't do a great job of it, \N'); printf( 'It won't even compile'); } // this program calculates user age #include <cstdio> int main() int currentyear; int birthyear; printf(Enter the year you were born\n"); scanf("%d", &birthyear); printf("Enter the current year \n); scanf("%d", ¤tyear); age = currentyear - birthyear; prinf("This year you will be %i ", age, \n); }
// this program gets the user to enter three // integers and prints them out lined up on // three separate lines, e.g. // 17 // 1024 // 206 #include <cstdio> int main() { // variables for the three integers int firstint; int secondint; int thirdint; print( "Please enter three integers "; scanf("%d", firstint); scanf("%f", &secondint); scanf("%d" &thirdint); printf( "The three integers are:); printf( "%5d", firstint); printf( "%4d", secondint); printf( "%3d", thirdint); return 0; }
// given the radius of a circle, // this program prints its circumference, // and prints its area to three decimal places #include <cstdio> const int Pi = 3.1415 void mian() ( int radius; // input circle radius int circumference; // calculated circumference float area; // calculated area printf( "Enter the integer radius of the circle"); printf('\n'); scanf("%d", &radius); circumference = 2 * radius * Pi; area = Pi * raduis * radius; printf( "The circumference is "circumference"\n", circumference); printf( ", the area is "); printf( "%8.2f\n", area); )
#include <cstdio> const int DaysInYear=365; const int HoursInDay=24; const int MinutesInHour=60; const int SecondsInMinute=60; int main(){ int x; x=DaysInYear*HoursInDay*MinutesInHour*SecondsInMinute; printf("%d seconds in a year \n", x); }
int x = 3; float y; y = x;Before being assigned to
y
, a copy of the value of x
is automatically converted from type int
to type
float
(<type>)(<expression>)
(int)(3.7)
would produce 3
int left, total, dummy; float number; // the following is illegal (% must have an int on right) left = total % number; // but the following would work left = total % (int)(number);General note on conversions:
int
to float
is a widening
conversion.
Widening conversions are commonly regarded as safe (within reasonable limits) and will be permitted in many languages and by many compilers.
float
to an int
would be
a narrowing conversion.
Narrowing conversions are widely regarded as unsafe (as there is a high possibility for loss of data). In C++ you can still perform many narrowing conversions, but typically a warning will be generated by the compiler if it detects such a conversion.
int x, y; char a, b; x = int('T'); // x = 84 y = x + 1; // y = 85 a = char(y); // a = 'U' b = char(x); // b = 'T'
printf("%c", char(32 + int('a'))); // will print out A