Introduction and basic C++ programming Getting Started



Download 403.98 Kb.
Page1/3
Date28.05.2018
Size403.98 Kb.
#51778
  1   2   3


Introduction and basic C++ programming


Getting Started:
Attendance
Syllabus
Handouts – bloodshed c++ & turingscraft/codelab
Compiler – bloodshed c++ on my webpage url to download the free compiler.
Code Lab
Steps to enroll in and start using turning's craft
Go to the following address:
http://www.turingscraft.com/
click on register
student
continue
your access code is CUN-BRO-6465-2210
university is CUNY-brooklyn
type in the email address you want to use (real)
select a password

enter your first and last names


accept the agreement

you are taken to the exercises


please start working on them – I will put up due dates
also, please let me know if the process works


High-level ‑ Compiler Languages (closer to human languages – assembly low level – closer to machine language)
More English‑like, more natural. Each high-level language statement translates to several low-level language statements. Use compilers to translate from the high‑level language into machine language. Compilers translate the whole program first, then execute the object program.
A compiler language is a high-level language which is machine-independent.

High-level languages are more English-like, easier to code, more costly to run, less flexible. e.g., FORTRAN, BASIC, COBOL, PL/1, ALGOL, APL, Pascal, SIMSCRIPT, Smalltalk, C, C++, Java.


A compiler is a translator program that transforms high-level program code into a low-level machine-level executable program.

compiler

or interpreter

source program

object program



C++ Programming



Every programming language has facilities to: in C++


  1. Read data from some input device cin >>




  1. Write output information onto an output device cout <<




  1. Perform arithmetic operations + - * /




  1. Perform relational operations < == >




  1. Perform logical operations ! && ||




  1. Branch to a non-sequential instruction (w/wo structure) while




  1. Store (and retrieve) data values to (and from) memory =



Homework
Running a simple C++ program in Bloodshed Dev-C++

Bloodshed Dev-C++ provides an integrated environment for writing programs. "Integrated environment" means Dev-C++ is a combination program, consisting of a text editor and a C++ compiler. A text editor is a limited word processing program that allows you to type in your program, make corrections and changes, and save and retrieve your program from disk storage. The editor is integrated with the Dev-C++ compiler so that you can easily switch between editing your program and compiling and running it. Note that the Dev-C++ compiler allows you to write, compile and run programs in either C or C++.


When you are in the Dev-C++ environment,

1. Select File | New | Source file.




2. Type in program

3. Right BEFORE the line that says return 0;

 type this:

    system("pause");                  (pause can be lowercase or caps)

This line will keep the output window open when the program has finished executing.

 

Enter the following program into the program1.cpp file window.



Every C++ program we write will start with a comment followed by these three lines.
// hello.cpp

// A First Program in C++

#include

using namespace std;

int main()

{

cout << "Hello. My name is Big Bird.\n";



system(“pause”);

return 0; //indicates that the program ended successfully

}

4. Save the file by selecting File | Save as , and name the file (something like a1.cpp).



5. Select Execute | Compile and Run (or press F9).

You should get an output window like this:



 6. To print the output,

   a. Right-click in top bar of output window and choose Select All.

   b. Then right-click again and click Copy.

   c. Go back into the editor, select File | New | Source File.

   d. In the new window, right-click and select Paste.

   e. Then use File | Print to print this window.
7. Go to the source file window and select File | Print to print the source file.
8. Click the X in the top right corner to exit the program.
You have just written (OK, typed) and run your first C++ program! (Whew!)

Some Parts of the Program

// hello.cpp

// A First Program in C++

#include

using namespace std;

int main()

{

cout << "Hello. My name is Big Bird.\n";



system(“pause”);

return 0; //indicates that the program ended successfully

}
(1) comments - At the beginning of each program is a comment, a short description of the problem to be solved. The comment explains the program. The comment is not strictly necessary because a program without it is technically correct. But comments are considered the single most important part of good programming style.
Note that each line of the comment begins with //. Once the symbols // are seen by the C++ compiler, everything to the right is ignored.
(also can have comments that look like this /* */ (if forget last ones what do you think happens?)
(2) Preprocessor directive - Tells the pre-processor to include in the program the contents of the I/O stream header file called iostream.h. This allows us to use standard stream input and output objects like cout (displays to the screen).

Any line in a program that starts with # is an instruction to the compiler, not an actual statement in the C++ language. The line containing #include tells the compiler to allow our program to perform standard input and output operations. Because these operations are so basic, this line of code will appear in all the programs we write.


The #include directive tells the compiler that we will be using parts of the standard function library. A function is a building block of a program; typically each function performs one particular task. Information about these functions is contained in a series of header files. In our case, we want the header file called iostream to be included in our program; iostream is short for input/output stream.
C++ divides names into namespaces. Using namespace std is called a using directive. This using directive says that the program is using the std (“standard”) namespace. The names you use will have the meaning defined for them in the std namespace. The line "using namespace std;" allows us to use certain shortcuts, for example to shorten the name of the header file from iostream.h to the simpler iostream. (It also allows the use of string instead of having to say std::string).
(3) int main( ) – main program header - The third line after the comment, int main(), is called the main program header. Every C++ program has at least one function, called main. Program execution begins with the first statement in main. The word int says that this program will return an integer (more about this below), and the empty set of parentheses indicates that the main function will not be sent any information from the outside.
(4) { brackets denote the body of the function }
(5) ; statement terminator

Every C++ statement must end with a semicolon.


(6) << stream insertion operator

Expression to the right of the operator is inserted (sent) to the cout object (the display screen).


(7) \n newline escape sequence

The backslash is an escape character. The character following it takes on a different meaning. eg, \t - tab \a - alert; ring bell

\\ - prints a backslash \” - prints a double quotation mark
(8) return - exits from the function

In this case control over execution is transferred back to the operating system.




Stored Data

Int n;
Variable – a name for a physical location within the computer that can hold one value at a time. (As the name implies, a variable can change its value (e.g. from 4 to 5).


Variables must be declared as a certain type, e.g., int, float, char, … This declaration may appear anywhere in the program before the variable is first used. The declaration creates the object.
Literals - Values, such as a number or text string, that are written literally as part of program code. The opposite of a literal is a variable.
Mnemonic names are useful – like if the variable n is a number from 4 to 9, you can call it number. Or if it’s to hold sum, you can call it sum.
int n;
Semicolon terminates every C++ statement.
The name of the object is n, the type [or class] is int. The object does not yet have a value.
n = 66; //now it has a value
= n is assigned the value 66. (different than mathematical equal sign).

or
int n=66; //declaration can be anywhere in the program


(can have more than one variable on the same line int i, j;)
Names (identifiers) - Names should be meaningful to help document your program.


  • may use letters, digits, underscores. No spaces.

  • may not begin with a digit

  • may be any length but better if less than 31 characters long.

  • C++ is case sensitive; upper and lower case letters are different.

  • no reserved words (e.g., const, void, int, …).

  • Avoid using names beginning with _ (underscore) or __ (double underscore). The C++ compiler uses names like that for special purposes.

varname = expr;


price = cost + 3;
If price is initially 7 and cost is 5 what is price after this statement?

8
In C++, double is the primary data type for real numbers. This data type permits decimal places; in addition, it can represent numbers that are extremely large or small. C++ relies on the individual compiler and its implementation on a specific machine to determine the limits of data types. The range of numbers that can be represented by data type int is about five billion; type long int (usually abbreviated as long) has an even larger range of integers.


A variable with data type double can store a much wider range of values and includes numbers with many decimal places. The exact range varies from compiler to compiler, but almost all allow numbers like positive or negative values ranging from 1.0 × 10-30 or 1.0 × 1030, which are infinitesimal and enormous.
C++ has another data type, float, which can also hold floating point numbers but in a smaller range. Although our numbers fit comfortably into variables of type float, we’ll use the larger type double as is commonly done in C++.
Division:
Division in arithmetic is normally --a -- or a ÷ b, but in C++, division is indicated by a

b

slash (/). More precisely, a/b means a divided by b. Here are some examples:


• If a is 10 and b is 5, then a/b is 2.
• If a is 11 and b is 4, then a/b is 2 (the fractional part of the answer is lost).
• If a is 10, then a/4. is 2.5 (in this case, the entire answer is kept).
• If a is 4, then 10.0/a is 2.5 (the entire answer is kept).
• If dist is 3.6 and hours is 2.4 then dist/hours is 1.5.

In these examples, the result of division, called the quotient, is sometimes an integer and sometimes not. If either (or both) operand is not an integer (e.g., 10.6/2.3, 10.6/2, or even 10/2.0), the division will work as it does in arithmetic, and the quotient will have decimal places. However, if one integer is divided by another, C++ uses integer division to find the quotient. This value is always an integer since any fractional part of the quotient is chopped off.


Because the fractional part of the answer is lost in integer division, C++ has a modulus or remainder operator, denoted by %, that will give the remainder when one integer is divided by another. For example, if c is 10 and d is 6, then c % d is 4. As another example, 26 % 5 is 1. Also 5 % 6 is 5. In general, x % y gives the remainder when x is divided by y. (The calculations can be tricky if one or both of the values is negative. See Exercise 11 for more details.) Of course, for both of these operations (/ and %), it is understood that the second operand cannot be 0 to avoid the obvious problem of dividing by 0.
A simple C++ program

This program:

// Calculates the mean of three numbers.


#include

using namespace std; //need this to drop .h

int main()

{

cout << "First Arithmetic Program" << endl;



cout << (12+5+10)/3 << endl;

system("pause");

return 0;

}
produces this output:


First Arithmetic Program by Big Bird.
9

Press any key to continue . . .
(6) << stream insertion operator

Expression to the right of the operator is inserted (sent) to the screen.




Now, let’s try using a variable to store the mean before printing it.
// This program calculates the mean of three numbers.

// Big Bird learns about variables.


#include

using namespace std;

int main()

{

double mean;



cout << "Second Arithmetic Program by Big Bird.\n\n";

mean = (12+5+10)/3;

cout << mean << endl;

system(“pause”);

return 0;

}
Output:






Try a different set of three numbers. Edit the program and run it again.
// calculates the mean of three numbers.

// Big Bird tries new data.

#include

using namespace std;

int main()

{

double mean;



cout << "Third Arithmetic Program by Big Bird.\n\n";

mean = (11+5+10)/3;

cout << mean <

system(“pause”);

return 0;

}
Third Arithmetic Program by Big Bird.


8

Press any key to continue . . .



OOPS!! What happened? [syntax (compile-time) error vs. run-time error vs. logic (run-time) error]

// calculates the mean of three numbers.

// Big Bird learns that expressions have a type.
#include

using namespace std;

int main()

{

double mean;



cout << "Fourth Arithmetic Program by Big Bird.\n\n";

mean = (11+5+10)/3.0;

cout << mean;

return 0;

} //end main
Output [that’s better!]:
Third Arithmetic Program by Big Bird.
8.66667

Press any key to continue . . .



(C++ Program Phases: …in the C++ programming environment
Edit - Text editor window. Save with .cpp extension
Preprocess - e.g., text replacement, including other library files with the file to be compiled
Compile - to object code
Link - links the object code with the code for the standard library functions referred to in the program. This produces an executable image (with no missing pieces). During Build process
Load - program is placed in memory
Execute - one instruction at a time)

Download 403.98 Kb.

Share with your friends:
  1   2   3




The database is protected by copyright ©ininet.org 2024
send message

    Main page