Syntax Comparison

Please press the reset button if you want to change the comparison value.


    

        


RESULT




                   
                
#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 (;)


                
                  
                
            


          print("Hello World")
          

The print() function is used to display "Hello World" to the user.


          
            
          
        

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.

Note:
in C, to declare a boolean data type, we need to include the library <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

            
              
            
        

There are several data types for Python:

Data Type Categories
Text Type str
Numeric Type int, float, complex
Sequence Type list, tuple, range
Mapping Type dict
Set Type set, frozenset
Boolean Type bool
Binary Type bytes, bytearray, memoryview
None Type NoneType

            
              
            
      

The general rules for naming variables are:

  • Names can contain letters, digits, and underscores
  • Names must begin with a letter or an underscore (_)
  • Names are case-sensitive (lowercase and uppercase letters have different meanings)
  • Names cannot contain whitespaces or special characters ($, #, %, etc.)
  • Names cannot contain reserved words, such as int, printf, etc.

            
              
            
        

The general rules for naming variables are:

  • Names can contain letters, digits, and underscores
  • Names must begin with a letter or an underscore (_)
  • Names are case-sensitive (lowercase and uppercase letters have different meanings)
  • Names cannot contain whitespaces or special characters ($, #, %, etc.)
  • Names cannot contain reserved words, such as int, float, etc.

            
              
            
        

The general rules for naming variables are:

  • Names can contain letters, digits, and underscores
  • Names must begin with a letter or an underscore (_)
  • Names are case-sensitive (lowercase and uppercase letters have different meanings)
  • Names cannot contain whitespaces or special characters ($, #, %, etc.)
  • Names cannot contain reserved words, such as int, float , etc.

      
        
      
    

Syntax: data_type variable_name;

Example:

            
            #include <stdio.h>

            int main() {
                int myNum;
                return 0;
            }
            
          


        

Multiple Variable Declaration

Syntax: data_type variable_name1, variable_name2, variable_name3;

Example:

            
            #include <stdio.h>

            int main() {
                int myNum1, myNum2, myNum3;
                return 0;
            } 
            
        


        
          
        
      

Syntax: data_type variable_name;

Example:

            
            #include <iostream>

            int main() {
                int myNum;
                return 0;
            }
            
        


        

Multiple variable declaration

Syntax: data_type variable_name1, variable_name2, variable_name3;

Example:

            
            #include <iostream>

            int main() {
                int myNum1, myNum2, myNum3;
                return 0;
            } 
            
        


        
          
        
      

Creating variables also known as declaring variables is an action of making a variable to store data.

Example: x = 5


      
        
      
  

Example:

          
      #include <stdio.h>

      int main() {
          int myNum = 9.8;
          printf("%d",myNum); //the output is 9
          return 0;
      }
          
      


        
          
        
    

Example:

          
        #include <iostream>

        int main() {
            int myNum = 9.8;
            std::cout << myNum; //the output is 9
            return 0;
        }
          
          


        
          
        
    

Example:

x = 8 	#x is automatically set to int


    
      
    

Example:

          
        #include <stdio.h>

        int main() {
            int myNum1 = 10;
            float myNum2 = (float) myNum1;
            printf("%f",myNum2); //myNum2 will show as 10.0000
            return 0;
        }
          
          


        
          
        
    

Example:

        
        #include <iostream>

        int main() {
            int myNum1 = 10;
            float myNum2 = (float) myNum1;
            std::cout << myNum2; //myNum2 will show as 10.0000
            return 0;
        }
        
          


        
          
        
    

This conversion is done manually by using constructor functions. There are three well-known constructor functions:

  • int() - constructs an integer number
  • float() - constructs a float number
  • str() - 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'
        
        


      
        
      
  

Example:

        
        #include <stdio.h>

        //global variable
        int phi = 3.14; 

        int sum (int a, int b){
            //local variable inside the sum function  
            int result; 
        }

        int main() {
            //local variable inside the main function  
            int myNum1; 
            return 0;
        }
        
        


        
          
        
      

Example:

        
        #include <iostream>

        //global variable
        int phi = 3.14; 

        int sum (int a, int b){
            //local variable inside the sum function
            int result; 
        }

        int main() {
            //local variable inside the main function
            int myNum1; 
            return 0;
        }
        
        


        
          
        
      

Example:

      
      x = "Hello!" 	#this is a global variable

      def myFunc(){
          y = "Hi!"	#this is a local variable
      } 
      
      


        
          
        
  

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;
        }            
      
      


        
          
        
    

Python uses print() to print output text or values to the console. print() in Python inserts a new line at the end of the output and insert a whitespace to separate each element automatically.

Syntax:

      
      print("Some random text")
      print(variable_name1, variable_name2)         
      
      


  
    
  

In C, you can use the scanf() function to get user input.

Syntax:   scanf("format specifier", &variable_name)

Example:

    
    #include <stdio.h>

    int main() {
        int myNum;
        char myChar;

        printf("Input a number and a character:");
        scanf("%d %c",&myNum, &myChar);
        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:

  • Single Line Comment
  • Syntax: //some comments here

  • Multiple Line Comments
  • Syntax:
                
            /*	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++:

  • Single Line Comment
  • Syntax: //some comments here

  • Multiple Line Comments
  • Syntax:
                
            /*	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;
  }            
      
      


    
      
    
    

Python comment is a single line.

Syntax: #some comment here

Example:


      #this line will not be executed
      myNum = input("Enter a number: ")
      print(myNum)
      
      #print("hello")
      #"hello" will not be printed out because
      #it is in the comment block.           
  
  


  
    
  

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
  • Syntax: throw n;
  • try
  • The keyword try has to be followed by one or more catch keywords to perform the exception-catching.
  • catch
  • Syntax:
    
            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;
      }
        
The output of this block of code is "Division by zero!"


        
          
        
    

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

    
      
    
Operator Example Meaning
= a = 5 a = 5
+= a += 5 a = a + 5
-= a -= 5 a = a - 5
*= a *= 5 a = a * 5
/= a /= 5 a = a / 5
%= a %= 5 a = a % 5
&= a &= 5 a = a & 5
|= a |= 5 a = a | 5
^= a ^= 5 a = a ^ 5
>>= a >>= 5 a = a >> 5
<<= a <<= 5 a = a << 5

    
      
    
    
Operator Example Meaning
= a = 5 a = 5
+= a += 5 a = a + 5
-= a -= 5 a = a - 5
*= a *= 5 a = a * 5
/= a /= 5 a = a / 5
%= a %= 5 a = a % 5
&= a &= 5 a = a & 5
|= a |= 5 a = a | 5
^= a ^= 5 a = a ^ 5
>>= a >>= 5 a = a >> 5
<<= a <<= 5 a = a << 5

    
      
    
    
Operator Example Meaning
= a = 5 a = 5
+= a += 5 a = a + 5
-= a -= 5 a = a - 5
*= a *= 5 a = a * 5
/= a /= 5 a = a / 5
%= a %= 5 a = a % 5
&= a &= 5 a = a & 5
|= a |= 5 a = a | 5
^= a ^= 5 a = a ^ 5
>>= a >>= 5 a = a >> 5
<<= a <<= 5 a = a << 5

    
      
    
Operator Name Example
== equal to x == y
!= not equal to x != y
> greater than x > y
< less than x < y
>= greater than or equal to x >= y
<= less than or equal to x <= y

    
      
    
    
Operator Name Example
== equal to x == y
!= not equal to x != y
> greater than x > y
< less than x < y
>= greater than or equal to x >= y
<= less than or equal to x <= y

    
      
    
    
Operator Name Example
== equal to x == y
!= not equal to x != y
> greater than x > y
< less than x < y
>= greater than or equal to x >= y
<= less than or equal to x <= y

    
      
    
Operator Name Description Example
&& logical AND returns true if all statements are true x < 10 && x > 3
|| logical OR returns true if one of the statements is true x > 100 || x < 30
! logical NOT return false if the statement is true and vice versa !(x > 100 || x < 30)

    
      
    
    
Operator Name Description Example
&& logical AND returns true if all statements are true x < 10 && x > 3
|| logical OR returns true if one of the statements is true x > 100 || x < 30
! logical NOT return false if the statement is true and vice versa !(x > 100 || x < 30)

    
      
    
    
Operator Name Description Example
and logical AND returns true if all statements are true x < 10 and x > 3
or logical OR returns true if one of the statements is true x > 100 or x < 30
not logical NOT return false if the statement is true and vice versa not(x > 100 or x < 30)

    
      
    

There is no identity operator in C.

There is no identity operator in C++.

Operator Description Example
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y

    
      
    

There is no membership operator in C.

There is no membership operator in C++.

Operator Description Example
in Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x not in y

    
      
    
Operator Name Example
& bitwise AND x & y
| bitwise OR x | y
^ bitwise XOR x ^ y
<< bitwise left shift x << y
>> bitwise right shift x >> y
~ bitwise NOT ~x

      
        
      
    
Operator Name Example
& bitwise AND x & y
| bitwise OR x | y
^ bitwise XOR x ^ y
<< bitwise left shift x << y
>> bitwise right shift x >> y
~ bitwise NOT ~x

      
        
      
    
Operator Name Example
& bitwise AND x & y
| bitwise OR x | y
^ bitwise XOR x ^ y
<< bitwise left shift x << y
>> bitwise right shift x >> y
~ bitwise NOT ~x

    
      
    

Syntax1 : array_type array_name[] = {content1, content2, content3};

Example:

int myNumber[] = {1,2,3,4,5};


      

Syntax2: array_type array_name[array_size];

Example:

int yourNumber[6];


    
      
    
    

Syntax1 : array_type array_name[] = {content1, content2, content3};

Example:

int myNumber[] = {1,2,3,4,5};


      

Syntax2: array_type array_name[array_size];

Example:

int yourNumber[6];


    
      
    
    

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] = 10



  

Tuples

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 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.

C++ uses the operator + to concatenate strings. Another way is to use append() function.

Syntax:

          
    variable_result = string1 + string2 + stringn;
    variable_result = string1.append(string2);  
          
          


      
        
      
    

The + operator can be used to concatenate strings.

Example code:

        
        myString1 = "hello"
        myString2 = "world"
        result = myString1 + myString2
        #result will be helloworld
        


    
      
    

String in C can be accessed just like an array by using the index number. We can then change the value of an element of the string.
Syntax: string1[index_number] = value;


      
        
      
    

String in C++ can be accessed just like an array by using the index number. We can then change the value of an element of the string.
Syntax: string1[index_number] = value;


      
        
      
    

String in C++ can be accessed just like a list (but not modifiable) by using the index number.
Syntax: print(string1[index_number])


    
      
    
Every C string has a null character inside them so the size of the string "some text" is not 9, but instead 10. We can use sizeof(variable_name) in the printf statement to know the array size.

    

    
      
    
  
To know a string length, we can use size() function or length() function.
Syntax: string1.size() or string1.length()

    
      
    
    

We can use the len() function to return the the length of a string or the amount of the characters in the string.
Syntax: len(string_name)


    
      
    

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
    }
        

Note:
the 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
        }
        

Note:
the 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
      

Note:
the 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;
      }
      


    
      
    
    

While

Syntax:


      while condition:
          #code block to be executed
      

Example:


      a = 1
      while(a < 5):
          print(f"a is {a}")
          a+=1
      


    
      
    

Syntax:


    for (statement 1; statement 2; statement 3) {
        // code block to be executed
    }
        

  • Statement 1 is the initialization of the loop condition.
  • Statement 2 is the condition that has to be met to enable the looping process.
  • Statement 3 is executed (every time) after a code block has been executed. Statement 3 is usually an increment or decrement of a value.

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
    }
        

  • Statement 1 is the initialization of the loop condition.
  • Statement 2 is the condition that has to be met to enable the looping process.
  • Statement 3 is executed (every time) after a code block has been executed. Statement 3 is usually an increment or decrement of a value.

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)

  • The start value is optional. If we don't specify it, then it wil start from 0 by default.
  • The end value is a must when using this function.
  • The step value is also optional. If we do not specify it, then it will use increment by 1 (by default).

Example:


        for i in range (3):
            print(i)
        


    
      
    

Syntax: printf("%p", &variable_name)

Example:


        #include<stdio.h>
        int main() {
            int myNum = 16;
            printf("%p", &myNum);
            return 0;
        }
        

Output:


        0x7ffc89b6e084
        


    
      
    
    

Syntax: std::cout << &variable_name;

Example:


        #include <iostream>

        int main(){
            int myNum = 16;
            std::cout << &myNum;
            return 0;
        }
                
        

Output:


        0x7ffe874a510c
        


    
      
    
    

There is no pointer in Python.

Syntax:


        variable_type variable_name1;
        variable_type* pointer_name1 = &variable_name1;
        


    
      
    
    

Syntax:


        variable_type variable_name1;
        variable_type* pointer_name1 = &variable_name1;
        


    
      
    
    

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.

Syntax:


  return_type function_name (data_type parameter_name){ 
      //line of codes to be executed
  }
        

Example:


        #include<stdio.h>
        total=10;
        void store (int a){
            total+=a;
        }
        int main() {
            int goods=10;
            store(goods);
            return 0;
        }
        


    
      
    
    

Syntax:


  return_type function_name (data_type parameter_name){  
      //line of codes to be executed 
  }
        

Example:


        #include<iostream>
        total=10;
        void store (int a){
            total+=a;
        }
        int main() {
            int goods=10;
            store(goods);
            return 0;
        }
        


    
      
    
    

Syntax:


      def function_name (parameters):  
          #line of codes to be executed 
      

Example:


      total=10
      def store(a):
          total+=a
      
      goods=10
      store(goods)
      


    
      
    

Syntax: function_name (parameters);

Example:


        #include<stdio.h>
        total=10;
        void store (int a){
            total+=a;
        }
        int main() {
            int goods=10;
            store(goods); //calling the function
            return 0;
        }
        


    
      
    
    

Syntax: function_name (parameters);

Example:


        #include<iostream>
        total=10;
        void store (int a){
            total+=a;
        }
        int main() {
            int goods=10;
            store(goods); //calling the function
            return 0;
        }
        


    
      
    
    

Syntax: function_name (parameters)

Example:


      total=10
      def store(a):
          total+=a
      
      goods=10
      store(goods)	#calling the function
      


    
      
    

Example:


        #include <stdio.h>
        void displayInfo(int age, int phone){
            printf("This is your age, %d", age);
            printf("\nThis is your phone number, %d", phone);
        }
        int main() {
            displayInfo(10, 9912);
            return 0;
        }
        

In this example, 10 and 9912 are the arguments, while age and phone are the parameters.


    
      
    
    

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.


    
      
    
    

Example:


      def displayInfo(age, phone):
          print(f"This is your age, {age}")
          print(f"This is your phone number, {phone}")
      
      displayInfo(10, 9912);
      

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 list

Example:


        #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;
        }
        


    
      
    
    

Syntax:


      lambda arguments : expression
      

Example:


      x = lambda a : a + 10
      print(x(5))                
      
The output will be 15.


    
      
    

C doesn't have any class properties.

Syntax:


    class class_name{
        access_specifier:
            //class members (attributes or methods)
    };
        

Example:


        #include<iostream>
        class MyClass {       // The class
            public:             // Access specifier
              int myNum;        // Attribute 
              string myString;  // Attribute 
        };

        int main() {
          return 0;
        }
        


    
      
    
    

Syntax:


      class MyClass:
          #lines of code            
      

Example:


      class MyClass:    #The class
          x = 5         #Attribute
      


  
    
  

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;
      }
        


    
      
    
    

Syntax: object_name = class_name()

To access the attributes of the class, we have to use the dot syntax (object_name.attribute).

Example:


        class MyClass:    #The class
            x = 5         #attribute
          
        myobj = MyClass()
        print(myobj.x)	#the output is 5
        


    
      
    

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.

Syntax:


        class_name (){
            //lines of code	
        }
        

Example:


      #include<iostream>
      class MyClass {     // The class
          public:           // Access specifier
            MyClass() {     // Constructor
              std::cout << "Hello World!";
          }
      };
        
      int main() {
          // Create an object of MyClass 
          //(this will call the constructor)  
          MyClass myObj;   
          return 0;
      }
        


    
      
    
    

Classes usually have the __init__ function. This function is always executed when an object is being initiated.

Example:


      class MyClass:
          def __init__(self, name, age):
              self.name = name
              self.age = age
      
      myobj = MyClass("John", "20")
      print(myobj.name)
      print(myobj.age)
      


  
    
  

C doesn't have any class properties.

Example:


        #include<iostream>
        class Cube {
            private:
              // Private attribute
              int side;
          
            public:
              // Setter
              void setSide(int s) {
                side = s;
              }
              // Getter
              int getSide() {
                return side;
              }
        };
          
        int main() {
            Cube myObj;
            myObj.setSide(5);
            std::cout << myObj.getSide();
            return 0;
        }
        


    
      
    
    

Setting a class as private member in Python can be do implicitly by adding two underscores before a variable name.

Example:


  class MyClass:
      def __init__(self, name, age):
          self.__name = name 
          self.__age = age
          #the attribute (name and age) is now private
      


  
    
  

C doesn't have any class properties.

Example:


        #include<iostream>

        // The base class
        class MySchool {     
            public:           
                int members;
                void welcome(){
                    std::cout<< "Welcome!";
                }
        };
        
        // The derived class
        class MyClass: public MySchool {     
            public:           				
                char name = 'b';
        };
          
        int main() {
            MyClass myObj;
            myObj.welcome();   
            return 0;
        }
        


    
      
    
    

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();
        }
        


    
      
    
    

Read in Python requires the read() function (to read the whole file) or a readline() function (to read a single line of text).

Example:


      #open a file
      f = open("myfile.txt", 'rt')

      #reading a single line
      print(f.readline())

      #reading a whole file
      print(f.read())
      
      #close the file
      f.close()
      


    
      
    

In C, to create a file, we can just declare a pointer type file and then use the fopen() function. After we use the fopen() function, it will automatically create a file for us.

Syntax:


        FILE *fptr
        fptr = fopen(filename, mode);
        


    
      
    
    

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 create a new file in Python, we just need to use the open() function.

Example:


      f = open("newfile.txt", 'xt')
      
Result: a new empty file will be created


    
      
    

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();
        }
        


    
      
    
    

To write something, we just need to use write() function.

Example:


      #open a file
      f = open("myfile.txt", 'wt')

      #write to the file
      f.write("Writing some text")

      #close the file
      f.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;
        }
        


    
      
    
    

The append mode uses the same write() function as the write mode.

Example:


      #open a file
      f = open("myfile.txt", 'at')

      #append to the file
      f.write("Adding some text")

      #close the file
      f.close()