Getting Started - Write our First Hello-world C++ ProgramLet us begin by writing our first C++ program that prints the message "hello, world" on the display console. Show
Step 1: Write the Source Code: Enter the following source codes using a programming text editor (such as NotePad++ for Windows or gedit for UNIX/Linux/Mac) or an Interactive Development Environment (IDE) (such as CodeBlocks, Eclipse, NetBeans or Visual Studio - Read the respective "How-To" article on how to install and get started with these IDEs). Do not enter the line numbers (on the left panel), which were added to help in the explanation. Save the source file as "
Step 2: Build the Executable Code: Compile and Link (aka Build) the source code "
Step 3: Run the Executable Code: Execute (Run) the program.
Brief Explanation of the Program/* ...... */
#include <iostream> int main() { ... body ... } cout << "hello, world" << endl; return 0; C++ Terminology and SyntaxStatement: A programming statement performs a piece of programming action. It must be terminated by a semicolon ( Preprocessor Directive: The Block: A block is a group of programming statements enclosed by braces Comments: A multi-line comment begins with Whitespaces: Blank, tab, and newline are collectively called whitespaces. Extra whitespaces are ignored, i.e., only one whitespace is needed to separate the tokens. Nevertheless, extra white spaces and newlines could help you and your readers better understand your program. Use extra whitespaces and newlines liberally. Case Sensitivity: C++ is case sensitive - a ROSE is NOT a Rose, and is NOT a rose. The Process of Writing a C++ ProgramStep 1: Write the source codes ( Step 2: Pre-process the source codes according to the preprocessor directives. Preprocessor directives begin with a hash sign ( Step 3: Compile the pre-processed source codes into object codes ( Step 4: Link the compiled object codes with other object codes and the library object codes ( Step 5: Load the executable code into computer memory. Step 6: Run the executable code, with the input to produce the desried output. C++ Program TemplateYou can use the following template to write your C++ programs. Choose a meaningful filename for you source file that reflects the purpose of your program with file extension of "
Output via "cout <<"In C++, output to the display console is done via " cout << "hello" << " world, " << "again!" << endl; cout << "hello," << endl << "one more time. " << endl << 5 << 4 << 3 << " " << 2.2 << " " << 1.1 << endl; A special symbol called hello world, again! hello, one more time. 543 2.2 1.1 _ Beside the cout << "hello world, again!\n"; cout << "\thello,\none\tmore\ttime.\n"; The output shall look like (the exact tab stop positions depend on your system's setting - eight spaces is used here): hello world, again! hello, one more time. _ Notes: I strongly recommend that you use Exercises
Input via "cin >>"Let's write a program (called "
Enter first integer: 99 Enter second integer: 4 The sum is: 103 The difference is: 95 The product is: 396 The quotient is: 24 Dissecting the Programint firstInt; cout << "Enter first integer: "; cin >> firstInt; Arithmetic Operators: +, =,
*, / Reading multiple items in one cin statementWe could read more than one values in one cout << "Enter two integers (separated by space): ";
cin >> firstInt >> secondInt;
sum = firstInt + secondInt;
cout << "The sum is: " << sum << endl; Enter two integers: 77 88 The sum of 77 and 88 is 165 Take note that the two integer values that you entered must be separated by a space. Exercises
What is a Program?A program is a sequence of instructions (called programming statements), executing one after another - usually in a sequential manner, as illustrated in the previous example and the following flow chart. Example (Sequential): The following program (
Enter the radius: 1.2 The radius is: 1.2 The area is: 4.52389 The circumference is: 7.53982 Dissecting the Programdouble radius, circumference, area; cout
<<
"Enter the radius: "; area = radius * radius * PI; cout << "The radius is: " << radius << endl; Take note that the programming statements inside the Exercises
What is a Variable?Computer programs manipulate (or process) data. A variable is used to store a piece of data for processing. It is called variable because you can change the value stored. More precisely, a variable is a named storage location, that stores a value of a particular data type. In other words, a variable has a "name", a "type" and stores a "value" of that type.
The above diagram illustrates 2 types of variables: To use a variable, you need to first declare its name and type, in one of the following syntaxes: var-type var-name; int sum; double radius; var-type var-name-1, var-name-2,...; int sum, difference, product, quotient; double area, circumference; var-type var-name = initial-value; int sum = 0; double pi = 3.14159265; var-type var-name-1 = initial-value-1, var-name-2 = initial-value-2,... ; int firstNumber = 1, secondNumber = 2; Take note that:
Once a variable is
declared, you can assign and re-assign a value to a variable, via the assignment operator " int number; number = 99; number = 88; number = number + 1; int sum = 0; sum = sum + number; int num1 = 5, num2 = 6; double radius = 1.5; int number; sum = 55.66; sum = "Hello"; Take note that:
x=x+1? x+y=1?Assignment ( "x+y=1" is valid in Mathematics, but is invalid in programming. In programming, the RHS of " Some languages uses Basic Arithmetic OperationsThe basic arithmetic operators are:
Addition, subtraction, multiplication, division and remainder are binary operators that take two operands (e.g., Example The following program (
Enter two integers: 98 5 The sum, difference, product, quotient and remainder of 98 and 5 are 103, 93, 49 0, 19, and 3 number1 after increment is 99 number2 after decrement is 4 The new quotient of 99 and 4 is 24 Dissecting the Programint number1, number2; cout << "Enter two integers (separated by space): "; sum = number1 + number2; cout << "The sum, difference, product, quotient and remainder of " cout << "sum"; cout << sum; ++number1; Exercises
What If Your Need To Add a Thousand Numbers? Use a Loop!Suppose that you want to add all the integers from 1 to 1000. If you follow the previous examples, you would require a thousand-line program! Instead, you could use a loop in your program to perform a repetitive task, that is what the dumb computers are good at. ExampleTry the following program
Enter the upperbound: 10000 The sum from 1 to 10000 is 50005000 Dissecting the Programint sum = 0; cout << "Enter the upperbound: "; int number = 1; initialization-statement; while (test) { loop-body; } next-statement; As illustrated in the flow chart, the initialization statement is first executed. The test is then checked. If the test is true, the body is executed. The test is checked again and the process repeats until the test is false. When the test is false, the loop completes and program execution continues to the next statement after the loop. In our program, the initialization statement declares an In this example, the loop repeats Exercises
Conditional (or Decision)What if you want to sum all the odd
numbers and also all the even numbers between 1 and 1000? There are many way to do this. You could declare two variables:
Enter the upperbound: 1000 The sum of odd numbers is 250000 The sum of even numbers is 250500 The difference is -500 Dissecting the Programint sumOdd = 0; if (number % 2 == 0) { if ( test ) { true-body; } if ( test ) { true-body; } else { false-body; } For a if-then statement, the true-body is executed if the test is true. Otherwise, nothing is done and the execution continues to the next statement. For a if-then-else statement, the true-body is executed if the test is true; otherwise, the false-body is executed. Execution is then continued to the next statement. In our program, we use the remainder operator Comparison OperatorsThere are six comparison (or relational) operators:
Take note that the comparison operator for equality is a double-equal sign Combining Simple ConditionsSuppose that you want to check whether a number There are three so-called logical operators that operate on the boolean conditions:
For examples: (x >= 0) && (x <= 100) (x < 0) || (x > 100) !((x >= 0) && (x <= 100)) ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0) Exercises
Type double & Floating-Point NumbersRecall
that a variable in C/C++ has a name and a type, and can hold a value of only that particular type. We have so far used a type called In programming, real numbers such as Example
Enter the temperature in celsius: 37.2 37.2 degree C is 98.96 degree F. Enter the temperature in fahrenheit: 100 100 degree F is 37.7778 degree C. Mixing int and double, and Type CastingAlthough you can use a At times, you may need both It is important to note that:
You can assign an integer value to a int i = 3; double d; d = i; d = 88; double nought = 0; However, if you assign a double d = 55.66; int i; i = d; Some C++ compilers (e.g., g++ version 3) signal a warning for truncation, while others (e.g., g++ version 4) do not: source.cpp:xx: warning: converting to 'int' from 'double' You should study the "warning messages" carefully - which signals a potential problem in your program, and rewrite the program if necessary. C++ allows you to ignore the warning and run the program. But, the fractional part will be lost during the execution. Type Casting OperatorsIf you are certain that you wish to carry out the type conversion, you could use the so-called type cast operator. The type cast operation could take one of these forms in C++, which returns an equivalent value in the new-type specified. new-type(expression); (new-type)expression; For example, double d = 5.5; int i; i = int(d); i = int(3.1416); i = (int)3.1416; Similarly, you can explicitly convert an ExampleTry the following program and explain the outputs produced:
The sum is 5050 Average 1 is 50 Average 2 is 50.5 Average 3 is 50.5 Average 4 is 50 The first average is incorrect, as For the second average, the value of For the third average, For the fourth average, Exercises
SummaryI have presented the basics for you to get start in programming. To learn programming, you need to understand the syntaxes and features involved in the programming language that you chosen, and you have to practice, practice and practice, on as many problems as you could. Link to "C++ Language References & Resources" What do we call notes in computer code for the programmer that are ignored by the compiler?In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program. They are added with the purpose of making the source code easier for humans to understand, and are generally ignored by compilers and interpreters.
What are notes in code called?Code commenting is the practice of sprinkling short, normally single-line notes throughout your code. These notes are called comments. They explain how your program works, and your intentions behind it.
Which is a line of code that is ignored by an interpreter?In Python, we use the hash symbol # to write a single-line comment. This line is ignored by the Python interpreter. The output of this program will be the same as in Example 1.
Are parts of the source code ignored by the compiler?Abstract: A significant amount of source code in software systems consists of comments, i. e., parts of the code which are ignored by the compiler. Comments in code represent a main source for system documentation and are hence key for source code understanding with respect to development and maintenance.
|