Please press the reset button if you want to change the comparison value.
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
}
Line 1: #include <stdio.h> is a statement to include the header file library.
<stdio.h> is a library that lets us work with input and output functions, such as printf().
Line 2: blank space. C ignores white space, but we need white spaces to increase our code readability.
Line 3: the main() function. As its name implies, main() function consists of the main code to be executed.
Any code inside the curly brackets { } is called “inside the main() function”
Line 4: printf() is a function used to output or print text to the screen.
Line 5: return 0; ends the main() function.
Note: every C statement ends with a semicolon (;)
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
Line 1: #include <iostream> is a statement to include the header file library.
<iostream> is a library that lets us work with input and output functions, such as cout.
Line 2: blank space. C++ ignores white space, but we need white spaces to increase our code readability.
Line 3: the main() function. As its name implies, main() function consists of the main code to be executed.
Any code inside the curly brackets { } is called “inside the main() function”
Line 4: std::cout is a function used to output or print text to the screen.
Line 5: return 0; ends the main() function.
Note: every C++ statement ends with a semicolon (;)
There are several data types for C, but these are the frequently used ones:
| Data Type | Size | Description |
|---|---|---|
| int | 2 or 4 bytes | Stores whole numbers (integers) |
| float | 4 bytes | Stores floating point numbers, but only sufficient for storing 6-7 decimal digits |
| double | 8 bytes | Stores floating point numbers, with the ability to store until 15 decimal digits. |
| bool | 1 byte | Stores only two kinds of values: True or False. |
| char | 1 byte | Stores a single character. The character can be a letter, number, or ASCII value. |
<stdbool.h>
In C, we also have format specifiers to specify which data type we use.
| Format Specifier | Data Type |
|---|---|
| %d | int |
| %f | float |
| %lf | double |
| %c | char |
| %s | string (also called 'text') |
| %d | bool |
There are several data types for C++, but these are the frequently used ones:
| Data Type | Size | Description |
|---|---|---|
| integer (int) | 2 or 4 bytes | Stores whole numbers (integers) |
| float | 4 bytes | Stores floating point numbers, but only sufficient for storing 6-7 decimal digits |
| double | 8 bytes | Stores floating point numbers, with the ability to store until 15 decimal digits. |
| boolean (bool) | 1 byte | Stores only two kinds of values: True or False. |
| character (char) | 1 byte | Stores a single character. The character can be a letter, number, or ASCII value. |
| auto | adjust automatically according to the data type | Automatically detects and assigns data type to the variable |
The general rules for naming variables are:
int, printf, etc.The general rules for naming variables are:
int, float, etc.The general rules for naming variables are:
int, float , etc.This conversion is done manually by using constructor functions. There are three well-known constructor functions:
int() - constructs an integer numberfloat() - constructs a float numberstr() - constructs a string Example:
x = int(9.12) #x will be 9
y = float(8) #y will be 8.0
z = str(100) #z will be '100'
Syntax:
printf("some random text") is used to print text inside the " ".
printf("format specifier", variable_name) is used to print the variable specified.
Format specifier is used to specify which data type that you want to use. You can
see what is a format specifier in the variable and data type page.
Example:
#include <stdio.h>
int main() {
int myNum = 19;
printf("Hello World!");
printf("%d",myNum);
return 0;
}
C++ uses std::cout to print output text or values to the console.
std::cout does not insert a new line at the end of the output.
If we want to insert a new line to the output, we have to use std::endl.
Syntax:
std::cout << "Some random text" << std::endl;
Example:
#include <iostream>
int main() {
int myNum = 19;
std::cout << "Hello World!" << std::endl;
std::cout << myNum;
return 0;
}
In C++, you can use the cin function to get user input.
cin can also get multiple inputs by separating the inputs
by the operator >>.
Syntax:
std::cin >> input1 >> input2 >> inputn;
Example:
#include <iostream>
int main() {
int myNum;
char myChar;
std::cout << "Input a number and a character: ";
std::cin >> myNum >> myChar;
std::cout << myNum << myChar;
return 0;
}
In Python, you can use the input function to get user input.
Note that if we don't typecast the input, then it will automatically be treated as
a string by Python.
Syntax: variable_name = input("Enter a string: ")
Example code:
#input is treated as string
myNum = input("Enter a number: ")
#input is treated as int
myNum2 = int(input("Enter a number: "))
There are two types of comments in C:
Syntax: //some comments here
/* Hello world!
Some comment here
*/
Example:
#include <stdio.h>
int main() {
char myName[20];
//this line will not be executed
printf("Input a name:");
fgets(myName, sizeof(myName), stdin);
/*
printf("hello")
The console will not show "hello" because the
printf("hello") is in the comment and will not
be executed.
*/
return 0;
}
There are two types of comments in C++:
Syntax: //some comments here
/* Hello world!
Some comment here
*/
Example:
#include <iostream>
#include <string>
int main() {
std::string myName;
//this line will not be executed
std::cout << "Input your full name: ";
getline(std::cin, myName);
/*
std::cout << "hello";
The console will not show "hello" because the
std::cout << "hello" is in the comment and will
not be executed.
*/
return 0;
}
Below are the most commonly used escape sequences for C.
| Escape Sequences | Description |
|---|---|
| \n (newline) | Insert a new line on the output. |
| \t (tab) | Insert a horizontal tab on the output. |
| \\ (backslash) | Backslash can't be printed directly as it
is used for escape sequences in C, so we have to place another backslash following the backslash used for an escape sequence. So, to print backslash, we type \\ not \ |
| \' (single quote) | Print a single quote in the output |
| \" (double quote) | Print a double quote in the output |
| \? (question mark) | Print a question mark in the output |
| \b (backspace) | Move the cursor one position back in the current line of text. |
| \a (alert or bell) | A beep is generated by the computer on execution. |
| \r (carriage return) | Move the cursor to the beginning of the current line. |
| \v (vertical tab) | Insert a vertical tab on the output. |
Below are the most commonly used escape sequences for C++.
| Escape Sequences | Description |
|---|---|
| \n (newline) | Insert a new line on the output (have the same use as std::endl). |
| \t (tab) | Insert a horizontal tab on the output. |
| \\ (backslash) | Backslash can't be printed directly as it
is used for escape sequences in C++, so we have to place another backslash following the backslash used for an escape sequence. So, to print backslash, we type \\ not \ |
| \' (single quote) | Print a single quote in the output |
| \" (double quote) | Print a double quote in the output |
| \? (question mark) | Print a question mark in the output |
| \b (backspace) | Move the cursor one position back in the current line of text. |
| \a (alert or bell) | A beep is generated by the computer on execution. |
| \r (carriage return) | Move the cursor to the beginning of the current line. |
| \v (vertical tab) | Insert a vertical tab on the output. |
Below are the most commonly used escape sequences for Python.
| Escape Sequences | Description |
|---|---|
| \n (newline) | Insert a new line on the output. |
| \t (tab) | Insert a horizontal tab on the output. |
| \\ (backslash) | Backslash can't be printed directly as it
is used for escape sequences in Python so we have to place another backslash following the backslash used for an escape sequence. So, to print backslash, we type \\ not \ |
| \' (single quote) | Print a single quote in the output |
| \" (double quote) | Print a double quote in the output |
| \? (question mark) | Print a question mark in the output |
| \b (backspace) | Move the cursor one position back in the current line of text. |
| \a (alert or bell) | A beep is generated by the computer on execution. |
| \r (carriage return) | Move the cursor to the beginning of the current line. |
| \v (vertical tab) | Insert a vertical tab on the output. |
There are no specific exception handling function in C.
C++ exception handling consists of three major keywords:
throw throw n;trytry has to be followed by one or more
catch keywords to perform the exception-catching.
catch
try {
// protected code
} catch( ExceptionName e1 ) {
// code to handle the exception e1
} catch( ExceptionName e2 ) {
//code to handle the exception e2
} catch( ExceptionName eN ) {
// code to handle the exception eN
}
Example:
#include <stdio.h>
double division(int a, int b) {
if( b == 0 ){
throw "Division by zero!";
}
return (a/b);
}
int main () {
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
std::cout << z << std::endl;
} //test the above code block
catch (const char* msg) {
std::cerr << msg << std::endl;
}
/*if the result type is const char*
(the result is the message "Division by zero!"),
then cerr (print error message) of the msg.
In this case, msg is "Division by zero!" */
return 0;
}
Python exception handling consists of four major keywords with else
and finally being optional:
Syntax:
try:
#code block
except error_name:
#code block
except:
#code block
else:
#code block
finally:
#code block
Example code:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
else:
print("Nothing went wrong")
finally:
print("Exception handling process is done")
Output:
Variable x is not defined
Exception handling process is done
| Operator | Name | Description | Example |
|---|---|---|---|
| + | Addition | Add two values together | a + b |
| - | Subtraction | Subtract one value from another | a - b |
| * | Multiplication | Multiplies two values | a * b |
| / | Division | Divides one value by another | a / b |
| % | Modulus | Returns the division remainder | a % b |
| ++ | Increment | Increase the value by 1 | a ++ |
| -- | Decrement | Decrease the value by 1 | a - - |
| Operator | Name | Description | Example |
|---|---|---|---|
| + | Addition | Add two values together | a + b |
| - | Subtraction | Subtract one value from another | a - b |
| * | Multiplication | Multiplies two values | a * b |
| / | Division | Divides one value by another | a / b |
| % | Modulus | Returns the division remainder | a % b |
| ++ | Increment | Increase the value by 1 | a ++ |
| -- | Decrement | Decrease the value by 1 | a - - |
| Operator | Name | Description | Example |
|---|---|---|---|
| + | Addition | Add two values together | a + b |
| - | Subtraction | Subtract one value from another | a - b |
| * | Multiplication | Multiplies two values | a * b |
| / | Division | Divides one value by another | a / b |
| % | Modulus | Returns the division remainder | a % b |
| ** | Exponentiation | Do exponential operation | a**b |
| // | Floor Division | Divides one value by another and return the result of an integer | a // b |
There is no identity operator in C.
There is no identity operator in C++.
There is no membership operator in C.
There is no membership operator in C++.
Lists
Syntax:
list_name1 = [] #empty list
list_name2 = [3, "hello", 22.5, [True, False]]
Tuples
Syntax:
tuple_name1 = () #empty tuple
tuple_name2 = (3, "hello", 22.5, [True, False])
tuple_name3 = (1,) #if we want to make a tuple with 1 element, we have to put a comma
Sets
Syntax:
set_name1 = {} #empty set
set_name2 = {3, "hello", 22.5, [True, False]}
#1 and True are considered the same in sets.
#0 and False are also considered the same in sets.
Dictionaries
Syntax:
dict_name1 = {} #empty dictionary
dict_name2 = {key1 : value1, key2 : value2, key3 : value3}
Syntax: array_name[index_number] = new_value;
Example code:
#include <stdio.h>
int main() {
int myNumber[] = {25, 50, 75, 100};
int yourNumber[4];
//yourNumber doesn't contain any value
//you can't change the size of the array after creation
myNumber[0] = 30; //change the value 25 to 30
//myNumber will contain 30,50,75,100 now
yourNumber[0] = 40;
yourNumber[1] = 50;
yourNumber[2] = 45;
yourNumber[3] = 55;
//yourNumber will contain 40,50,45,55 now
return 0;
}
Syntax: array_name[index_number] = new_value;
Example code:
#include <iostream>
int main() {
int myNumber[] = {25, 50, 75, 100};
int yourNumber[4];
//yourNumber doesn't contain any value
//you can't change the size of the array after creation
myNumber[0] = 30; //change the value 25 to 30
//myNumber will contain 30,50,75,100 now
yourNumber[0] = 40;
yourNumber[1] = 50;
yourNumber[2] = 45;
yourNumber[3] = 55;
//yourNumber will contain 40,50,45,55 now
return 0;
}
Lists
Syntax: list_name[index_number] = new_value
Example:
myNumber[0] = 10Tuples
Syntax: tuple_name[index_number]
Note that we can't change tuple's element. If we want to change it, we have to
change the whole tuple (redefine the tuple).
Sets
Syntax:
for item in set_name:
#code block
Dictionaries
Syntax:
dict_name2 = {"name": "Mega", "age" : 18}
print(dict_name2["name"]) #the output will be Mega
We use dict_name.keys() to access the keys in a dictionary,
dict_name.values() to access the values in a dictionary, and
dict_name.items() to access keys and values in a dictionary.
We declare the size of the array as the index number.
Syntax: array_name[index_number] = new_value;
We can also use the sizeof() function to return the
size of an array in
byte, so we have to divide the sizeof(array) with
sizeof(array_type) to know
how many elements that exist in the array. If you want to use easier method,
you can directly use std::size(array) to know the amount of the elements in an array.
#include <iostream>
int main() {
int myNumbers[5] = {20, 30, 40, 50, 60};
int byte_size = sizeof(myNumbers); //value is 20
int array_size = sizeof(myNumbers)/sizeof(int); //value is 5
int array_size2 = std::size(myNumbers); //value is 5
return 0;
}
Lists
We can slice a list with the syntax list_name[a:b].
Example code:
myList = ["alpha", "beta", "delta", "gamma", "epsilon", "theta"]
print(myList[1:4])
print(myList[:4])
print(myList[1:])
print(myList[-4:-1])
Output:
['beta', 'delta', 'gamma']
['alpha', 'beta', 'delta', 'gamma']
['beta', 'delta', 'gamma', 'epsilon', 'theta']
['delta', 'gamma', 'epsilon']
We can also use the len()
function to return the size of a list or the amount of the elements in the list.
Syntax: len(list_name)
Tuples
We can use the len()
function to return the size of a tuple or the amount of the elements in the tuple.
Syntax: len(tuple_name)
Sets
We can use the len()
function to return the size of a set or the amount of the elements in the set.
Syntax: len(set_name)
Dictionaries
We can use the len()
function to return the size of a dictionary or the amount of the elements in the dictionary.
Syntax: len(dict_name)
Syntax:
struct struct_name{
Variable_type1 variable_name1;
Variable_type2 variable_name2;
…
};
int main(){
Struct struct_name structure_variable_name;
}
To access the members of a structure, you have to use dot (.)
in int main() after you declare the name of the structure variable.
Example code:
#include <stdio.h>
struct Phone {
int price;
char brand[10];
int year;
};
int main() {
struct Phone phone1 = {5000, "Aster", 2019};
struct Phone phone2 = {3000, "Bianca", 2022};
struct Phone phone3 = {2000, "Charlie", 2021};
struct Phone phone4;
phone4 = phone3; //assign the value of phone3 to phone4
phone4.year = 2022; //change phone4's year to 2022
printf("%d %s %d\n", phone1.price, phone1.brand, phone1.year);
printf("%d %s %d\n", phone2.price, phone2.brand, phone2.year);
printf("%d %s %d\n", phone3.price, phone3.brand, phone3.year);
printf("%d %s %d\n", phone4.price, phone4.brand, phone4.year);
return 0;
}
Output:
5000 Aster 2019
3000 Bianca 2022
2000 Charlie 2021
2000 Charlie 2022
Syntax:
int main(){
struct {
Variable_type1 variable_name1;
Variable_type2 variable_name2;
Variable_typen variable_namen;
}struct_variable_name1, struct_variable_name2, struct_variable_namen;
}
To access the members of a structure, you have to use dot (.) in int main()
after you declare the name of the structure variable.
Syntax: struct_variable_name.variable_name1 = value;
Example code:
#include <iostream.h>
#include <string.h>
struct Phone {
int price;
std::string brand;
int year;
};
int main() {
struct Phone phone1 = {5000, "Aster", 2019};
struct Phone phone2 = {3000, "Bianca", 2022};
struct Phone phone3 = {2000, "Charlie", 2021};
struct Phone phone4;
phone4 = phone3; //assign the value of phone3 to phone4
phone4.year = 2022; //change phone4's year to 2022
std::cout<< phone1.price<< " " << phone1.brand << " " << phone1.year;
std::cout<< "\n" << phone2.price<< " " << phone2.brand << " " << phone2.year;
std::cout<< "\n" << phone3.price<< " " << phone3.brand << " " << phone3.year;
std::cout<< "\n" << phone4.price<< " " << phone4.brand << " " << phone4.year;
return 0;
}
Output:
5000 Aster 2019
3000 Bianca 2022
2000 Charlie 2021
2000 Charlie 2022
There is no structure in Python.
There is no built-in function for string concatention in C.
sizeof(variable_name)
in the printf statement to know the array size.
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
}
Example:
#include<stdio.h>
int main() {
int myNum = 10;
if(myNum < 1){
printf("myNum is less than 1");
}else if (myNum < 10){
printf("myNum is less than 10");
}else{
printf("myNum is greater than or equal with 10");
}
return 0;
}
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
}
Example:
#include<iostream>
int main() {
int myNum = 10;
if(myNum < 1){
std::cout<<"myNum is less than 1";
}else if (myNum < 10){
std::cout<<"myNum is less than 10";
}else{
std::cout<<"myNum is greater than or equal with 10";
}
return 0;
}
Syntax:
if condition1:
#block of code to be executed if condition1 is true
elif 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
Example:
myNum = 10;
if myNum < 1:
print("myNum is less than 1")
elif myNum < 10:
print("myNum is less than 10")
else:
print("myNum is greater than or equal with 10")
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
default code block is optional.
Example:
#include<stdio.h>
int main() {
int day = 2;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}
return 0;
}
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
default code block is optional.
Example:
#include<iostream>
int main() {
int day = 2;
switch (day) {
case 1:
std::cout<<"Monday";
break;
case 2:
std::cout<<"Tuesday";
break;
case 3:
std::cout<<"Wednesday";
break;
case 4:
std::cout<<"Thursday";
break;
case 5:
std::cout<<"Friday";
break;
case 6:
std::cout<<"Saturday";
break;
case 7:
std::cout<<"Sunday";
break;
}
return 0;
}
Syntax:
match parameter:
case x:
#code block
case y:
#code block
default:
#code block
default code block is optional.
Example:
day = 2;
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
While
Syntax:
while (condition) {
// code block to be executed
}
Example:
#include<stdio.h>
int main() {
int a = 1;
while(a < 5){
printf("a is %d\n", a);
a++;
}
return 0;
}
Do-While
Syntax:
do {
// code block to be executed
}while (condition);
Example:
#include<stdio.h>
int main() {
int a = 1;
do{
printf("Hello!");
a++;
} while (a < 1);
return 0;
}
While
Syntax:
while (condition) {
// code block to be executed
}
Example:
#include<iostream>
int main() {
int a = 1;
while(a < 5){
std::cout<<"a is " << a << endl;
a++;
}
return 0;
}
Do-While
Syntax:
do {
// code block to be executed
}while (condition);
Example:
#include<iostream>
int main() {
int a = 1;
do{
std::cout<<"Hello!";
a++;
} while (a < 1);
return 0;
}
Syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Example:
#include<stdio.h>
int main() {
for(int i = 0; i < 5 ; i++){
printf("Hello");
}
return 0;
}
Syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Example:
#include<iostream>
int main() {
for(int i = 0; i < 5 ; i++){
std::cout<<"Hello!";
}
return 0;
}
Syntax:
for variable in variables:
#code block to be executed
Example:
fruits=['apple', 'mango', 'banana']
for i in fruits:
print(i)
We can also use the range()
function to specify the number of times we wanted to loop.
Syntax: for variable in range (start, end, step)
Example:
for i in range (3):
print(i)
There is no pointer in Python.
There is no pointer in Python.
Syntax:
variable_type variable_name1;
variable_type* pointer_name1 = &variable_name1;
printf("%p", pointer_name1); //print the memory address of variable_name1
printf("format specifier of variable_name1", *pointer_name1);
//print variable_name1
Example code:
#include<stdio.h>
int main() {
//variable declaration
char myChar = 'C';
int myAge = 18;
//pointer declaration
char* myptr1 = &myChar;
int* myptr2 = &myAge;
printf("%p\n", myptr1); //print memory address of myChar
printf("%c\n", *myptr1); //dereferencing (print myChar)
printf("%p\n", myptr2); //print memory address of myAge
printf("%d", *myptr2); //dereferencing (print myAge)
return 0;
}
Output:
0x7ffdb8071ed3
C
0x7ffdb8071ed4
18
Syntax:
variable_type variable_name1;
variable_type* pointer_name1 = &variable_name1;
//print the memory address of variable_name1
std::cout << pointer_name1 << std::endl;
//print variable_name1
std::cout << *pointer_name1;
Example code:
#include<iostream>
#include<string>
int main(){
//variable declaration
std::string myString = "Car";
int myAge = 18;
//pointer declaration
std::string* myptr1 = &myString;
int* myptr2 = &myAge;
std::cout << myptr1 << std::endl; //print memory address of myString
std::cout << *myptr1 << std::endl;; //dereferencing (print myString)
std::cout << myptr2 << std::endl;; //print memory address of myAge
std::cout << *myptr2 << std::endl;; //dereferencing (print myAge)
*myptr2 = 20;
std::cout << myptr2 << std::endl;; //memory address is still same
std::cout << *myptr2 << std::endl;; //the value of myAge changed
return 0;
}
Output:
0x7fffcc479cd0
Car
0x7fffcc479ccc
18
0x7fffcc479ccc
20
There is no pointer in Python.
In C, the name of an array is actually a pointer to the first element of the array.
In other words, when we print array_name as a pointer by the
format specifier %p is actually the same value as printing
&array_name[0]. Therefore, we can access the elements in an array by dereferencing.
Example code:
#include<stdio.h>
int main() {
int myNumbers[4] = {25, 50, 75, 100};
// Change the value of the second element to 23
*(myNumbers + 1) = 23;
printf("%d ", *myNumbers); //print myNumbers[0]
printf("%d", *(myNumbers + 1)); //print myNumbers[1]
return 0;
}
Output:
25 23
In C++, the name of an array is actually a pointer to the first element of the array.
In other words, when we print array_name
is actually the same value as printing &array_name[0].
Therefore, we can access the elements in an array by dereferencing.
Example code:
#include <iostream>
int main(){
int myNumbers[4] = {25, 50, 75, 100};
// Change the value of the second element to 23
*(myNumbers + 1) = 23;
std::cout << *myNumbers << " "; //print myNumbers[0]
std::cout << *(myNumbers+1) << std::endl; //print myNumbers[1]
std::cout << myNumbers << std::endl;
std::cout << &myNumbers[0]; //notice that both are the same
return 0;
}
Output:
25 23
0x7fffc29fd180
0x7fffc29fd180
There is no pointer in Python.
There is no references in C.
Syntax:
variable_type variable1;
//referencing
variable_type &variable2 = variable1;
Example code:
#include <iostream>
#include <string>
int main() {
std::string food = "Pizza"; //variable declaration
std::string &meal = food; //reference declaration
std::cout << food << "\n";
std::cout << meal << "\n";
meal = "rice";
std::cout << food << "\n"; //food will also change to rice
std::cout << meal;
return 0;
}
Output:
Pizza
Pizza
rice
rice
There is no references in Python.
Example:
#include <iostream>
void displayInfo(int age, int phone){
std::cout << "This is your age, " << age;
std::cout << "\nThis is your phone number, " << phone;
}
int main() {
displayInfo(10, 9912);
return 0;
}
In this example, 10 and 9912 are the arguments,
while age and phone are the parameters.
C doesn't have any lambda function.
Syntax:
data_type function_name = [] () {
//lines of code
};
Explanation:
[] is the lambda introducer which denotes the start of
lambda expression() is the parameter listExample:
#include <iostream>
int main() {
auto display = [](int age=20){
std::cout << age << std::endl;
};
display(10); //the output is 10
display(); //the output is 20
return 0;
}
C doesn't have any class properties.
C doesn't have any class properties.
Syntax: class_name object_name;
To access the attributes of the class, we have to use the dot syntax
(object_name.attribute).
Example:
#include<iostream>
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute
string myString; // Attribute
};
int main() {
MyClass myObj; // Create object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
return 0;
}
C doesn't have any class properties.
We can declare methods inside of the class or outside of the class definition.
And, to call the method, we use the same way as calling attributes (using the
dot syntax).
Example of the inside of the class method:
#include<iostream>
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute
void greet(){
std::cout<<"Hello!";
}
};
int main() {
// Create an object of MyClass
MyClass myObj;
// Access attributes and set values
myObj.myNum = 15;
myObj.greet();
return 0;
}
Example of the outside of the class method:
#include<iostream>
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute
};
void MyClass::greet(){
std::cout<<"Hello!";
}
int main() {
// Create an object of MyClass
MyClass myObj;
// Access attributes and set values
myObj.myNum = 15;
myObj.greet();
return 0;
}
We can declare methods inside of the class.
And, to call the method, we use the same way as calling attributes (using the
dot syntax).
Example:
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age}"
def greet(self):
print(f"Hello, {self.name}!")
myobj = MyClass("John", "20")
myobj.greet()
C doesn't have any class properties.
C doesn't have any class properties.
C doesn't have any class properties.
Example:
#parent class
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#the child class
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
x = Student("Mega", "Kim")
x.printname()
C doesn't have any class properties.
Example:
#include<iostream>
#include<string>
// Base class
class Animal {
public:
void animalSound() {
std::cout << "The animal makes a sound \n";
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
std::cout << "The pig says: wee wee \n";
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
std::cout << "The dog says: bow wow \n";
}
};
int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
Example:
class Pig:
def __init__(self, name):
self.name = name
def animalSound(self):
print("The pig says wee wee")
class Dog:
def __init__(self, name):
self.name = name
def animalSound(self):
print("The dog says bow wow")
mypig = Pig("Piggy")
mydog = Dog("Doggy")
mypig.animalSound()
mydog.animalSound()
Syntax:
char string_name[string_size];
fgets(string_name, string_size, pointer_name);
Example:
#include<stdio.h>
int main() {
FILE *fptr;
// Open a file in read mode
fptr = fopen("filename.txt", "r");
// Store the content of the file
char myString[100];
// Read the content and store it in myString
fgets(myString, 100, fptr);
// Print the file content
printf("%s", myString);
// Close the file
fclose(fptr);
return 0;
}
To read a file, first we need to include the library <fstream>,
then we open the file with ifstream class or
fstream class. We need to
prepare a text string variable to store the file content. Then, we use
the getline() function and finally, we close the file.
Note: getline()
function only read a single line of text, so if you want to read several
line of text, use loops to loop through the getline() function.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
//Create a variable string
string mytext;
// Read from the text file
ifstream MyFile("filename.txt");
// Read the file using getline() function
getline(MyFile, mytext);
cout << mytext;
// Close the file
MyFile.close();
}
To create to a file, first we need to include the library <fstream>, then we
open the file with ofstream class or
fstream class. If there is no file with the file
name we specified, then the system will automatically create a new file for us.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
// Close the file
MyFile.close();
}
To write something, we just need to use fprint() function.
Syntax: fprintf(pointer_name, "text we want to write");
Example:
#include<stdio.h>
int main() {
FILE *fptr;
// Open a file in writing mode
fptr = fopen("filename.txt", "w");
// Write some text to the file
fprintf(fptr, "Some text");
// Close the file
fclose(fptr);
return 0;
}
To write to a file, first we need to include the library <fstream>, then we
open the file with ofstream class or
fstream class. Then we use the insertion
operator (<<) to write and finally, we close the file.
Syntax: fprintf(pointer_name, “text we want to write”);
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "Hello!";
// Close the file
MyFile.close();
}
The append mode uses the same
fprintf() function as the write mode.
Syntax: fprintf(pointer_name, “text we want to write”);
Example:
#include<stdio.h>
int main() {
FILE *fptr;
// Open a file in append mode
fptr = fopen("filename.txt", "a");
// Append some text to the file
fprintf(fptr, "\nHi everybody!");
// Close the file
fclose(fptr);
return 0;
}
We can append to a file using ofstream. But, we need to include the mode
std::ios::app in the open() function.
Syntax: variable_name.open(file_name, std::ios::app);
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Declaring a variable
ofstream myfile;
// Open and append "Hello!" the file
myfile.open("text.txt", ios::app)
myfile << "Hello!"
// Close the file
myfile.close();
return 0;
}