Вы находитесь на странице: 1из 5

Chapter 1: Introduction

1.1 What is C++?


- Has 2 parts: Preprocessor Directives & Main function
- First part: Preprocessor Directives
- All directive begin with “#” character .E.g., #include, #define
- Why preprocessor directives?
- C++ defines only a small number of operations.
- Most of the functions and symbols are in Libraries.
- #include directive
- Allows a program to access the library
- E.g., #include <iostream>, #include <ctype> ,#include <cmath>
- E.g., when we use cout and cin, we must declare #include <iostream> on the top of the
program.

- #define directive
- Create a symbolic constant for a constant value.
- E.g., #define PI 3.141593 // create symbolic constant PI for 3.141593
#define MAX 100

- Second Part: Main Function


- All C++ program must have main() function.
- Every program in C++ begins executing at the function main()
- All function start with a “{“ and end with a “}” symbol. It is the body of the function.

// A first program in C++


#include <iostream>

int main()
{
std::cout << "Welcome to C++!\n"; // display message
return 0; //indicate to operating system that program ended successfully
}

//alternative way of writing first program


#include <iostream>
using namespace std;

int main()
{
cout << "Welcome to C++!\n";
return 0;
}
Note: The entire line in C++ is called a statement. Every C++ statement must end with a
semicolon.

 What happen to the following program?


#include <iostream>
using namespace std;

int main()
{
cout << "Welcome\nto\n\nC++!\n";
return 0;
}

//Program reads input from user and displays the result


#include <iostream>
using namespace std;
int main()
{ int num; // variable declaration

cout << "Please enter a number.";// prompt user for data


cin >> num; // read a number from user into variable num
cout << "You have entered: " << num << endl;
return 0;
}

1
//Program that displays the sum of two numbers.
#include <iostream>
using namespace std;

int main()
{
int num1, num2;
int sum;

cout << "Enter two integer: ";


cin >> num1>> num2;

sum = num1 + num2;

cout << "Sum is " << sum << endl;

return 0;
}

1.2 Variables Declaration and Constant


- A variable is a location in memory where a value can be store.
- Every variable has a name, a type, and a value and must be declared
before it is used.

int numberOfStudents;
float totalWeight;

- We can assign a value to the variables at the same time that we declare it. This is called
initialization.

int sum = 0;
float totalWeight=156.7;
double PI = 3.1415926535;
- Furthermore, we can specify that a variable's value cannot be altered during the execution of a
program with the reserved word "const":
const double PI = 3.1415926535;

1.3 Data Types


C++ has 4 basic data types:
 int - store integer value, use 4 bytes of memory. E.g., int salary=3000;
float /double - store decimal value. 4 bytes for float and 8 bytes for double. E.g., double n;
char - store one character, 1 byte. E.g., char grade =’A’;
bool - store either true or false. 1 byte. E.g., bool no=0;

int main()
{
bool result=true;

if(result)
cout << "10 > 9 is " << (10>9) << endl;

return 0;
}

1.4 Arithmetic in C++


- Most C++ programs perform arithmetic calculations.

C++ operation Arithmetic operator Algebraic expression C expression


Addition + f+7 f+7
Subtraction - p–c p– c
Multiplication * bm or b.m b*m
Division & integer division / x/y or x ÷ y x /y
Modulus % r mod s r%s

- Integer division yields an integer result

2
E.g. 7/4 = 1 17 / 5 = 3 0/4 = 0 4/0 is
undefined

- C++ provides the modulus operator, %, which yields the remainder after integer division. The
modulus operator is an integer operator that can be used only with integer operands.
E.g. 7%4=3 17 % 5 = 2 15%0 is undefined

1.5 Comments
- Comments do not cause the computer to perform any action when the program is run. They are
ignored by the compiler.
- Comments are used for
- explaining difficult sections of code
- describes the program, author, date, modification changes etc.
- documentation of variables and their usage
- copyrighting
- Use // for single line
- Symbol /* and end with */ for multiple lines
- E.g. /*
* Programmer: William Bell Date completed: May 9, 2003
* Instructor: Janet Smith Class: CIS61
*
* Calculates and displays the area and circumference of a circle
*/

1.6 Input Statement


- Accepting data from the user through keyboard
- E.g., cin >> salary;
cin >> d >>f >> c;

1.7 Output Statement


- Output the text within the double quotation marks to the screen.
- E.g., cout << "The student is good"; //print a text
cout << "The amount is " << total; //print text and variable

- insert a newline with endl. The name endl short for “end line” and belongs to namespace std.
- E.g.,
cout << endl;
cout << total << endl;

- output line can combine with escape sequence to format the output text

Escape sequence Description


\n Newline. Position the screen cursor to the beginning of the next line
\t Horizontal tab. Move the screen cursor to the next tab stop
\\ Blackslash. Used to print a blackslash character
\’ Single quote. Used to print a single quote character
\" Double quote. Used to print a double quote character
\a Alert. Sound the system bell

1.8 Common Programming Errors

3
- Debugging – to find any error in the program
- Types of Errors:
 Syntax Errors - code violation during compilation. E.g., missing semicolon, undefined variable,
did not close ‘/*’ with ‘*/’
 Run-time Errors - illegal operation occur during execution. E.g., divide a number by zero,
open an non existing file
 Logic Errors - passed syntax and run-time errors but produce false result. It is usually
causes by the algorithm of the program

1.9 I/O Manipulators


- Using library <iomanip>

setw(int n) sets width of next output value only to the argument.


setprecision(int n) set decimal places. Default is 6.
fixed output as decimal notation
scientific output as scientific notation
left left align . Use with setw()
right right align. Use with setw()

 setw()
int n=1234
cout << setw(10) <<n; //default right align
output:
1 2 3 4

cout << setw(5)<<n;


output:
1 2 3 4

 setprecision()
- The precision determines the maximum number of digits that shall be output to express
floating-point values, counting both the digits before and after the decimal point.

#include <iostream>
#include <iomanip>
using namespace std;
int main () {

double f =3.141596;
cout << setprecision (5) << f << endl;
cout << setprecision (3) << f << endl;
return 0;
}

Output: 3.1416 // rounded up


3.14

 Fixed or Scientific

float n=12.345678; Output:


cout << n << endl; 12.3457
cout << fixed;
cout << n << endl; 12.345678
cout << scientific;
cout << n << endl; 1.234568e+001
cout << scientific;
cout << setprecision(5)<<n <<endl; 1.23457e+001

 Left/Right
float n=123.4568457; output
<---------- 20 ----------->
cout<< n << endl; 123.457
cout<< fixed;
cout<< setw(20)<< setprecision(4)<<n << endl; 123.4568

4
cout<< setw(20)<< left <<setprecision(3)<< n << endl; 123.457
cout<< setw(20)<< right << setprecision(2)<<n << endl; 123.46

Вам также может понравиться