w3school intro to c++

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Numeric Types

Use int when you need to store a whole number without decimals, like 35 or 1000, and float or double when you need a floating point number (with decimals), like 9.99 or 3.14515.

Arithmetic Operators

+ Addition: Adds together two values, ie x + y - Subtraction: Subtracts one value from another , ie x - y * Multiplication: Multiplies two values, ie x * y / Division: Divides one value by another, ie x / y % Modulus : Returns the division remainder, ie x % y ++ Increment: Increases the value of a variable by 1, ie ++x -- Decrement: Decreases the value of a variable by 1, ie --x

Boolean Expression

A Boolean expression is a C++ expression that returns a boolean value: 1 (true) or 0 (false). You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true: Example int x = 10; int y = 9; cout << (x > y); // returns 1 (true), because 10 is higher than 9 Or even easier: Example cout << (10 > 9); // returns 1 (true), because 10 is higher than 9 In the examples below, we use the equal to (==) operator to evaluate an expression: Example int x = 10; cout << (x == 10); // returns 1 (true), because the value of x is equal to 10 Example cout << (10 == 15); // returns 0 (false), because 10 is not equal to 15

Function Declaration and Definition

A C++ function consist of two parts: Declaration: the function's name, return type, and parameters (if any) Definition: the body of the function (code to be executed) void myFunction() { // declaration // the body of the function (definition) } Note: If a user-defined function, such as myFunction() is declared after the main() function, an error will occur. It is because C++ works from top to bottom; which means that if the function is not declared above main(), the program is unaware of it. However, it is possible to separate the declaration and the definition of the function - for code optimization. You will often see C++ programs that have function declaration above main(), and function definition below main(). This will make the code better organized and easier to read

Boolean Types

A boolean data type is declared with the bool keyword and can only take the values true or false. When the value is returned, true = 1 and false = 0. Example bool isCodingFun = true; bool isFishTasty = false; cout << isCodingFun; // Outputs 1 (true) cout << isFishTasty; // Outputs 0 (false) Boolean values are mostly used for conditional testing,

Boolean Values

A boolean variable is declared with the bool keyword and can only take the values true or false: Example bool isCodingFun = true; bool isFishTasty = false; cout << isCodingFun; // Outputs 1 (true) cout << isFishTasty; // Outputs 0 (false) From the example above, you can read that a true value returns 1, and false returns 0. However, it is more common to return boolean values from boolean expressions

Scientific Numbers

A floating point number can also be a scientific number with an "e" to indicate the power of 10: Example float f1 = 35e3; double d1 = 12E4; cout << f1; cout << d1;

C++ Functions

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. Functions are used to perform certain actions, and they are important for reusing code: Define the code once, and use it many times.

#include <iostream>

A header file library that lets us work with input and output objects, such as cout. Header files add functionality to C++ programs.

Creating References

A reference variable is a "reference" to an existing variable, and it is created with the & operator: string food = "Pizza"; // food variable string &meal = food; // reference to food Now, we can use either the variable name food or the reference name meal to refer to the food variable: Example string food = "Pizza"; string &meal = food; cout << food << "\n"; // Outputs Pizza cout << meal << "\n"; // Outputs Pizza

Append

A string in C++ is actually an object, which contain functions that can perform certain operations on strings. For example, you can also concatenate strings with the append() function: Example string firstName = "John "; string lastName = "Doe"; string fullName = firstName.append(lastName); cout << fullName;

C++ Identifiers

All C++ variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). Note: It is recommended to use descriptive names in order to create understandable and maintainable code

cout

An object used together with the insertion operator (<<) to output/print text.

C++ Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type, specify the name of the array followed by square brackets and specify the number of elements it should store: string cars[4]; We have now declared a variable that holds an array of four strings. To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces: string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"}; To create an array of three integers, you could write: int myNum[3] = {10, 20, 30};

Assignment Operators

Assignment operators are used to assign values to variables. In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x: Example int x = 10; The addition assignment operator (+=) adds a value to a variable: Example int x = 10; x += 5;

Modify the Pointer Value

C++ Modify Pointers Modify the Pointer Value You can also change the pointer's value. But note that this will also change the value of the original variable: Example string food = "Pizza"; string* ptr = &food; // Output the value of food (Pizza) cout << food << "\n"; // Output the memory address of food (0x6dfed4) cout << &food << "\n"; // Access the memory address of food and output its value (Pizza) cout << *ptr << "\n"; // Change the value of the pointer *ptr = "Hamburger"; // Output the new value of the pointer (Hamburger) cout << *ptr << "\n"; // Output the new value of the food variable (Hamburger) cout << food << "\n";

length () vs size()

C++ String Length String Length To get the length of a string, use the length() function: Example string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; cout << "The length of the txt string is: " << txt.length(); Tip: You might see some C++ programs that use the size() function to get the length of a string. This is just an alias of length(). It is completely up to you if you want to use length() or size(): Example string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; cout << "The length of the txt string is: " << txt.size();

C++ Math

C++ has many functions that allows you to perform mathematical tasks on numbers

Create a Function

C++ provides some pre-defined functions, such as main(), which is used to execute code. But you can also create your own functions to perform certain actions. To create (often referred to as declare) a function, specify the name of the function, followed by parentheses ()

C++ Conditions and If Statements

C++ supports the usual logical conditions from mathematics: Less than: a < b Less than or equal to: a <= b Greater than: a > b Greater than or equal to: a >= b Equal to a == b Not Equal to: a != b You can use these conditions to perform different actions for different decisions.

Adding Numbers and Strings

C++ uses the + operator for both addition and concatenation. Numbers are added. Strings are concatenated. If you add two numbers, the result will be a number: Example int x = 10; int y = 20; int z = x + y; // z will be 30 (an integer) If you add two strings, the result will be a string concatenation: Example string x = "10"; string y = "20"; string z = x + y; // z will be 1020 (a string) If you try to add a number to a string, an error occurs

C++ Comments

Comments can be used to explain C++ code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Comments can be singled-lined or multi-lined.

Comparison Operators

Comparison operators are used to compare two values. Note: The return value of a comparison is either true (1) or false (0). In the following example, we use the greater than operator (>) to find out if 5 is greater than 3: Example int x = 5; int y = 3; cout << (x > y); // returns 1 (true) because 5 is greater than 3

system ("pause"); return 0

Ends the main function.

Example of switch

Example int day = 4; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; case 4: cout << "Thursday"; break; case 5: cout << "Friday"; break; case 6: cout << "Saturday"; break; case 7: cout << "Sunday"; break; } // Outputs "Thursday" (day 4)

Example of a function: void myFunction() { // code to be executed }

Example Explained myFunction() is the name of the function void means that the function does not have a return value. You will learn more about return values later in the next chapter inside the function (the body), add code that defines what the function should do

Example string food = "Pizza"; // A food variable of type string string* ptr = &food; // A pointer variable, with the name ptr, that stores the address of food // Output the value of food (Pizza) cout << food << "\n"; // Output the memory address of food (0x6dfed4) cout << &food << "\n"; // Output the memory address of food with the pointer (0x6dfed4) cout << ptr << "\n";

Example explained Create a pointer variable with the name ptr, that points to a string variable, by using the asterisk sign * (string* ptr). Note that the type of the pointer has to match the type of the variable you're working with. Use the & operator to store the memory address of the variable called food, and assign it to the pointer. Now, ptr holds the value of food's memory address. Tip: There are three ways to declare pointer variables, but the first way is preferred: string* mystring; // Preferred string *mystring; string * mystring;

Example for (int i = 0; i < 5; i++) { cout << i << "\n"; }

Example explained Statement 1 sets a variable before the loop starts (int i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end. Statement 3 increases a value (i++) each time the code block in the loop has been executed.

Creating Pointers

From the previous chapter, that we can get the memory address of a variable by using the & operator: Example string food = "Pizza"; // A food variable of type string cout << food; // Outputs the value of food (Pizza) cout << &food; // Outputs the memory address of food (0x6dfed4) A pointer however, is a variable that stores the memory address as its value. A pointer variable points to a data type (like int or string) of the same type, and is created with the * operator. The address of the variable you're working with is assigned to the pointer

C++ Booleans

In programming, you will need a data type that can only have one of two values, like: YES / NO ON / OFF TRUE / FALSE For this, C++ has a bool data type, which can take the values true (1) or false (0).

Example int x = 20; int y = 18; if (x > y) { cout << "x is greater than y"; }

In the example above we use two variables, x and y, to test whether x is greater than y (using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".

Example int time = 20; if (time < 18) { cout << "Good day."; } else { cout << "Good evening."; } // Outputs "Good evening."

In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on to the else condition and print to the screen "Good evening". If the time was less than 18, the program would print "Good day

Example int time = 22; if (time < 10) { cout << "Good morning."; } else if (time < 20) { cout << "Good day."; } else { cout << "Good evening."; } // Outputs "Good evening."

In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the else if statement, is also false, so we move on to the else condition since condition1 and condition2 is both false - and print to the screen "Good evening". However, if the time was 14, our program would print "Good day."

Memory Address

In the example from the previous page, the & operator was used to create a reference variable. But it can also be used to get the memory address of a variable; which is the location of where the variable is stored on the computer. When a variable is created in C++, a memory address is assigned to the variable. And when we assign a value to the variable, it is stored in this memory address. To access it, use the & operator, and the result will represent where the variable is stored: Example string food = "Pizza"; cout << &food; // Outputs 0x6dfed4 Note: The memory address is in hexadecimal form (0x..). Note that you may not get the same result in your program.

Get Memory Address and Value

In the example from the previous page, we used the pointer variable to get the memory address of a variable (used together with the & reference operator). However, you can also use the pointer to get the value of the variable, by using the * operator (the dereference operator): Example string food = "Pizza"; // Variable declaration string* ptr = &food; // Pointer declaration // Reference: Output the memory address of food with the pointer (0x6dfed4) cout << ptr << "\n"; // Dereference: Output the value of food with the pointer (Pizza) cout << *ptr << "\n"; Note that the * sign can be confusing here, as it does two different things in our code: When used in declaration (string* ptr), it creates a pointer variable. When not used in declaration, it act as a dereference operator.

Creating a Simple Calculator

In this example, the user must input two numbers. Then we print the sum by calculating (adding) the two numbers: Example int x, y; int sum; cout << "Type a number: "; cin >> x; cout << "Type another number: "; cin >> y; sum = x + y; cout << "Sum is: " << sum;

Parameters and Arguments

Information can be passed to functions as a parameter. Parameters act as variables inside the function. Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma

Multiple Parameters

Inside the function, you can add as many parameters as you want: Example void myFunction(string fname, int age) { cout << fname << " Refsnes. " << age << " years old. \n"; } int main() { myFunction("Liam", 3); myFunction("Jenny", 14); myFunction("Anja", 30); return 0; } // Liam Refsnes. 3 years old. // Jenny Refsnes. 14 years old. // Anja Refsnes. 30 years old. Note that when you are working with multiple parameters, the function call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.

Omit Elements on Declaration

It is also possible to declare an array without specifying the elements on declaration, and add them later: string cars[5]; cars[0] = {"Volvo"}; cars[1] = {"BMW"}; ...

User Input Strings

It is possible to use the extraction operator >> on cin to display a string entered by a user: Example string firstName; cout << "Type your first name: "; cin >> firstName; // get user input from the keyboard cout << "Your name is: " << firstName; // Type your first name: John // Your name is: John However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means that it can only display a single word (even if you type many words): Example string fullName; cout << "Type your full name: "; cin >> fullName; cout << "Your name is: " << fullName; // Type your full name: John Doe // Your name is: John From the example above, you would expect the program to print "John Doe", but it only prints "John". That's why, when working with strings, we often use the getline() function to read a line of text. It takes cin as the first parameter, and the string variable as second: Example string fullName; cout << "Type your full name: "; getline (cin, fullName); cout << "Your name is: " << fullName; // Type your full name: John Doe // Your name is: John Doe

append() vs +

It is up to you whether you want to use + or append(). The major difference between the two, is that the append() function is much faster. However, for testing and such, it might be easier to just use +.

Logical Operators

Logical operators are used to determine the logic between variables or values

C++ Loops

Loops can execute a block of code as long as a specified condition is reached. Loops are handy because they save time, reduce errors, and they make code more readable.

Multi-line Comment

Multi-line comments start with /* and ends with */. Any text between /* and */ will be ignored by the compiler

The general rules for constructing names for variables (unique identifiers) are:

Names can contain letters, digits and underscores Names must begin with a letter or an underscore (_) Names are case sensitive (myVar and myvar are different variables) Names cannot contain whitespaces or special characters like !, #, %, etc. Reserved words (like C++ keywords, such as int) cannot be used as names

A list of all comparison operators:

Operator Name Example == Equal to x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or x >= y equal to <= Less than or x <= y equal to

C++ Operators

Operators are used to perform operations on variables and values. In the example below, we use the + operator to add together two values: Example int x = 100 + 50; Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable: Example int sum1 = 100 + 50; // 150 (100 + 50) int sum2 = sum1 + 250; // 400 (150 + 250) int sum3 = sum2 + sum2; // 800 (400 + 400)

C++ <cmath> Header

Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm), can be found in the <cmath> header file: Example // Include the cmath library #include <cmath> cout << sqrt(64); cout << round(2.6); cout << log(2);

Why is it useful to know the memory address?

References and Pointers (which you will learn about in the next chapter) are important in C++, because they give you the ability to manipulate the data in the computer's memory - which can reduce the code and improve the performance. These two features are one of the things that make C++ stand out from other programming languages, like Python and Java.

Single-line comments

Single-line comments start with two forward slashes (//). Any text between // and the end of the line is ignored by the compiler (will not be executed).

C++ Strings

Strings are used for storing text. A string variable contains a collection of characters surrounded by double quotes. To use strings, you must include an additional header file in the source code, the <string> library. Example // Include the string library #include <string> // Create a string variable string greeting = "Hello";

String Concatenation

The + operator can be used between strings to add them together to make a new string. This is called concatenation: Example string firstName = "John "; string lastName = "Doe"; string fullName = firstName + lastName; cout << fullName; In the example above, we added a space after firstName to create a space between John and Doe on output. However, you could also add a space with quotes (" " or ' '): Example string firstName = "John"; string lastName = "Doe"; string fullName = firstName + " " + lastName; cout << fullName;

C++ Break

The break statement can also be used to jump out of a loop. This example jumps out of the loop when i is equal to 4: Example for (int i = 0; i < 10; i++) { if (i == 4) { break; } cout << i << "\n"; }

Character Types

The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c': Example char myGrade = 'B'; cout << myGrade; Alternatively, you can use ASCII values to display certain characters: Example char a = 65, b = 66, c = 67; cout << a; cout << b; cout << c;

C++ Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop. This example skips the value of 4: Example for (int i = 0; i < 10; i++) { if (i == 4) { continue; } cout << i << "\n"; }

C++ Data Types

The data type specifies the size and type of information the variable will store int: 4 bytes, Stores whole numbers, without decimals float: 4 bytes, Stores fractional numbers, containing one or more decimals. Sufficient for storing 7 decimal digits double: 8 bytes, Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits boolean: 1 byte, Stores true or false values char: 1 byte, Stores a single character/letter/number, or ASCII values

The default Keyword

The default keyword specifies some code to run if there is no case match: Example int day = 4; switch (day) { case 6: cout << "Today is Saturday"; break; case 7: cout << "Today is Sunday"; break; default: cout << "Looking forward to the Weekend"; } // Outputs "Looking forward to the Weekend" Note: The default keyword must be used as the last statement in the switch, and it does not need a break.

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. Syntax do { // code block to be executed } while (condition); The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested: Example int i = 0; do { cout << i << "\n"; i++; } while (i < 5); Do not forget to increase the variable used in the condition, otherwise the loop will never end!

void functionName(parameter1, parameter2, parameter3) { // code to be executed }

The following example has a function that takes a string called fname as parameter. When the function is called, we pass along a first name, which is used inside the function to print the full name. Example void myFunction(string fname) { cout << fname << " Refsnes\n"; } int main() { myFunction("Liam"); myFunction("Jenny"); myFunction("Anja"); return 0; } // Liam Refsnes // Jenny Refsnes // Anja Refsnes When a parameter is passed to the function, it is called an argument. So, from the example above: fname is a parameter, while Liam, Jenny and Anja are arguments.

Max and min

The max(x,y) function can be used to find the highest value of x and y: Example cout << max(5, 10); And the min(x,y) function can be used to find the lowest value of x and y: Example cout << min(5, 10);

float vs. double

The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations.

String Types

The string type is used to store a sequence of characters (text). This is not a built-in type, but it behaves like one in its most basic usage. String values must be surrounded by double quotes: Example string greeting = "Hello"; cout << greeting; To use strings, you must include an additional header file in the source code, the <string> library: Example // Include the string library #include <string> // Create a string variable string greeting = "Hello"; // Output string value cout << greeting;

Return Values

The void keyword, used in the previous examples, indicates that the function should not return a value. If you want the function to return a value, you can use a data type (such as int, string, etc.) instead of void, and use the return keyword inside the function: Example int myFunction(int x) { return 5 + x; } int main() { cout << myFunction(3); return 0; } // Outputs 8 (5 + 3) This example returns the sum of a function with two parameters: Example int myFunction(int x, int y) { return x + y; } int main() { cout << myFunction(5, 3); return 0; } // Outputs 8 (5 + 3) You can also store the result in a variable: Example int myFunction(int x, int y) { return x + y; } int main() { int z = myFunction(5, 3); cout << z; return 0; } // Outputs 8 (5 + 3)

C++ While Loop

The while loop loops through a block of code as long as a specified condition is true: Syntax while (condition) { // code block to be executed } In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5: Example int i = 0; while (i < 5) { cout << i << "\n"; i++; } Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end

Short Hand If...Else (Ternary Operator)

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements: Syntax variable = (condition) ? expressionTrue : expressionFalse; Instead of writing: Example int time = 20; if (time < 18) { cout << "Good day."; } else { cout << "Good evening."; } You can simply write: Example int time = 20; string result = (time < 18) ? "Good day." : "Good evening."; cout << result;

int main()

This is called a function. Any code inside its curly brackets {} will be executed.

using namespace std

This means that we can use names for objects and variables from the standard library.

Add Variables Together

To add a variable to another variable, you can use the + operator: Example int x = 5; int y = 6; int sum = x + y; cout << sum;

Call a Function

To call a function, write the function's name followed by two parentheses () and a semicolon ; In the following example, myFunction() is used to print a text (the action), when it is called: Example Inside main, call myFunction(): // Create a function void myFunction() { cout << "I just got executed!"; } int main() { myFunction(); // call the function return 0; } // Outputs "I just got executed!" A function can be called multiple times: Example void myFunction() { cout << "I just got executed!\n"; } int main() { myFunction(); myFunction(); myFunction(); return 0; } // I just got executed! // I just got executed! // I just got executed!

Change String Characters

To change the value of a specific character in a string, refer to the index number, and use single quotes: Example string myString = "Hello"; myString[0] = 'J'; cout << myString; // Outputs Jello instead of Hello

Change an Array Element

To change the value of a specific element, refer to the index number: Example cars[0] = "Opel"; Example string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"}; cars[0] = "Opel"; cout << cars[0]; // Now outputs Opel instead of Volvo

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value: Syntax type variable = value; Where type is one of C++ types (such as int), and variable is the name of the variable (such as x or myName). The equal sign is used to assign values to the variable.

Declare Many Variables

To declare more than one variable of the same type, use a comma-separated list: Example int x = 5, y = 6, z = 50; cout << x + y + z;

String Length

To get the length of a string, use the length() function: Example string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; cout << "The length of the txt string is: " << txt.length();

How do you insert new lines?

To insert a new line, you can use the \n character (Tip: Two \n characters after each other will create a blank line) Another way to insert a new line, is with the <<endl; manipulator

The else if Statement

Use the else if statement to specify a new condition if the first condition is false. Syntax if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false }

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false. Syntax if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false }

The if Statement

Use the if statement to specify a block of C++ code to be executed if a condition is true. Syntax if (condition) { // block of code to be executed if the condition is true } Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error. In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text: Example if (20 > 18) { cout << "20 is greater than 18"; } We can also test variables

C++ Switch Statements,

Use the switch statement to select one of many code blocks to be executed. Syntax switch(expression) { case x: // code block break; case y: // code block break; default: // code block } This is how it works: The switch expression is evaluated once The value of the expression is compared with the values of each case If there is a match, the associated block of code is executed The break and default keywords are optional

C++ Variables

Variables are containers for storing data values. In C++, there are different types of variables (defined with different keywords)

The break Keyword

When C++ reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block. When a match is found, and the job is done, it's time for a break. There is no need for more testing. A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.

Constants

When you do not want others (or yourself) to override existing variable values, use the const keyword (this will declare the variable as "constant", which means unchangeable and read-only). You should always declare the variable as constant when you have values that are unlikely to change: Example const int minutesPerHour = 60; const float PI = 3.14;

C++ For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop: Syntax for (statement 1; statement 2; statement 3) { // code block to be executed } Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed.

Function Overloading

With function overloading, multiple functions can have the same name with different parameters: Example int myFunction(int x) float myFunction(float x) double myFunction(double x, double y) Consider the following example, which have two functions that add numbers of different type: Example int plusFuncInt(int x, int y) { return x + y; } double plusFuncDouble(double x, double y) { return x + y; } int main() { int myNum1 = plusFuncInt(8, 5); double myNum2 = plusFuncDouble(4.3, 6.26); cout << "Int: " << myNum1 << "\n"; cout << "Double: " << myNum2; return 0; } Instead of defining two functions that should do the same thing, it is better to overload one. In the example below, we overload the plusFunc function to work for both int and double: Example int plusFunc(int x, int y) { return x + y; } double plusFunc(double x, double y) { return x + y; } int main() { int myNum1 = plusFunc(8, 5); double myNum2 = plusFunc(4.3, 6.26); cout << "Int: " << myNum1 << "\n"; cout << "Double: " << myNum2; return 0; } Note: Multiple functions can have the same name as long as the number and/or type of parameters are different.

Access the Elements of an Array

You access an array element by referring to the index number. This statement accesses the value of the first element in cars: Example string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"}; cout << cars[0]; // Outputs Volvo Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Access Strings

You can access the characters in a string by referring to its index number inside square brackets []. This example prints the first character in myString: Example string myString = "Hello"; cout << myString[0]; // Outputs H

Declaring a variable

You can also declare a variable without assigning the value, and assign the value later: Example int myNum; myNum = 15; cout << myNum; Note that if you assign a new value to an existing variable, it will overwrite the previous value: Example int myNum = 15; // myNum is 15 myNum = 10; // Now myNum is 10 cout << myNum; // Outputs 10

Pass By Reference

You can also pass a reference to the function. This can be useful when you need to change the value of the arguments: Example void swapNums(int &x, int &y) { int z = x; x = y; y = z; } int main() { int firstNum = 10; int secondNum = 20; cout << "Before swap: " << "\n"; cout << firstNum << secondNum << "\n"; // Call the function, which will change the values of firstNum and secondNum swapNums(firstNum, secondNum); cout << "After swap: " << "\n"; cout << firstNum << secondNum << "\n"; return 0; }

Default Parameter Value

You can also use a default parameter value, by using the equals sign (=). If we call the function without an argument, it uses the default value ("Norway"): Example void myFunction(string country = "Norway") { cout << country << "\n"; } int main() { myFunction("Sweden"); myFunction("India"); myFunction(); myFunction("USA"); return 0; } // Sweden // India // Norway // USA A parameter with a default value, is often known as an "optional parameter". From the example above, country is an optional parameter and "Norway" is the default value.

Break and Continue in While Loop

You can also use break and continue in while loops: Break Example int i = 0; while (i < 10) { cout << i << "\n"; i++; if (i == 4) { break; } } Continue Example int i = 0; while (i < 10) { if (i == 4) { i++; continue; } cout << i << "\n"; i++; }

Loop Through an Array

You can loop through the array elements with the for loop. The following example outputs all elements in the cars array: Example string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"}; for(int i = 0; i < 4; i++) { cout << cars[i] << "\n"; } The following example outputs the index of each element together with its value: Example string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"}; for(int i = 0; i < 4; i++) { cout << i << ": " << cars[i] << "\n"; }

Omit Array Size

You don't have to specify the size of the array. But if you don't, it will only be as big as the elements that are inserted into it: string cars[] = {"Volvo", "BMW", "Ford"}; // size of array is always 3 This is completely fine. However, the problem arise if you want extra space for future elements. Then you have to overwrite the existing values: string cars[] = {"Volvo", "BMW", "Ford"}; ✖️ string cars[] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};✔️ If you specify the size however, the array will reserve the extra space: string cars[5] = {"Volvo", "BMW", "Ford"}; // size of array is 5, even though it's only three elements inside it Now you can add a fourth and fifth element without overwriting the others: cars[3] = {"Mazda"}; cars[4] = {"Tesla"};

C++ User Input

cin is a predefined variable that reads data from the keyboard with the extraction operator (>>). In the following example, the user can input a number, which is stored in the variable x. Then we print the value of x: Example int x; cout << "Type a number: "; // Type a number and press enter cin >> x; // Get user input from the keyboard cout << "Your number is: " << x; // Display the input value

double

stores floating point numbers, with decimals, such as 19.99 or -19.99

int

stores integers (whole numbers), without decimals, such as 123 or -123

char

stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes

string

stores text, such as "Hello World". String values are surrounded by double quotes

bool

stores values with two states: true or false

C++ has the following conditional statements:

•Use if to specify a block of code to be executed, if a specified condition is true •Use else to specify a block of code to be executed, if the same condition is false •Use else if to specify a new condition to test, if the first condition is false •Use switch to specify many alternative blocks of code to be executed


संबंधित स्टडी सेट्स

Accident and Health Insurance Basics

View Set

World History II -- French Revolution TEST -- Date: 11/17/23

View Set

M259 (7) - Analytic Trigonometry

View Set

Chapters 20-22: Electricity and Circuits

View Set

ENGLISH 4 COLLEGE PREP : MODULE 01 : LESSON 07 INTRO: EVALUATING YOUR WRITING

View Set

MKTG 310 Exam 2 Chapter 9 - Learning, Memory, and Product Positioning

View Set