Blog

  • C Program to create a File & write Data in it

    This is a file tutorial where we will write a C program to create a file and write into it. Before that, you may go through the following C topics.

    Explanation: The program is based on the file system in C. The program opens the file system in writing mode, hence the “w”. If the file is not present with the name provided then the program will create a file on the same directory.

    The program will check if the file is Null or not. If not then, it will ask the user to enter data which later will be inserted into the file. Let us go through the program.

    Program to write into a file in C

    #include <stdio.h>
    #include <conio.h>
    
    void main()
    {
       FILE * fptr;
       char data[100];
    
       fptr = fopen("test.txt", "w");
    
       if (fptr == NULL)
       {
          printf("Error occured!");
          return;
       }
    
       printf("Enter the data: \n");
       fgets(data, 100, stdin);
    
       fputs(data, fptr);	//writing to a file
    
       printf("\nFile created and saved successfully.");
    
       fclose(fptr);
    }

    Output:

    write a file in C

    After successful execution of the program, a file named “test.txt” will be created (if not already created) in the same directory where you have stored the source code file. Open that file and you will see the data that you wrote on the program will be present there in the following way.

    This is simple2code.com


  • C++ Program to Write Date into a File

    In this tutorial, we will write a C++ program to write data into a file and store the information. In order to understand the program, you should have knowledge of the following topic in C++.

    Explanation:

    First, the program asks the user to enter the name of the file where they want to write. Then to write content into a file, you must first open the file in a write mode. Also, we will check if the file name entered by the user exists or not.

    If it does not exist then the file with the name entered is automatically created inside the current directory. And finally, the program will ask the user to enter the String to store in the file.


    C++ Program to Write Date into a File

    #include <iostream>
    #include <stdio.h>
    #include <fstream>
    using namespace std;
    
    int main()
    {
       string fname, str;
       fstream fp;
    
       cout << "Enter the file name: ";
       getline(cin, fname);
    
       fp.open(fname, fstream::out);
    
       if (!fp)
       {
          cout << "Error Occurred during execution!";
          return 0;
       }
    
       cout << "Enter the Data:\n";
       getline(cin, str);
    
       while (str.length() > 0)
       {
          fp << str;
          fp << "\n";
          getline(cin, str);
       }
    
       fp.close();
       cout << "Data written succefully.";
    
       return 0;
    }

    Output: Enter the data and press enter two times to exit the writing mode.

    write into C++

    After successful execution of the program, you can check that the test.txt file present in the current directory will have the exact following string in it.

    Hi! I am simple2code.com.
    Learn Tutorials.


  • C++ Program to Read a File

    In this tutorial, we will write a C++ program to read a file and display its contents. In order to understand the program, you should have knowledge of the topic in C++ below.

    Before writing a program: To read a file using C++ program, you first need to create a file and give it a name and save the file inside the current directory (i.e the directory where the C++ program will be saved).

    Consider a text file name test.txt is saved which has the following content in it.

    Hello! This is simple2code.com.

    Now let us write a program to read this file in C++.


    C++ Program to Read a File

    #include <iostream>
    #include <fstream>
    #include <stdio.h>
    using namespace std;
    
    int main()
    {
       ifstream file;
       char str[100], fname[100];
    
       cout << "Enter a file name: ";
       cin >> fname;
    
       file.open(fname);
    
       if (!file)
       {
          cout << "Error Occurred while opening file!";
          exit(0);
       }
    
       cout << "\n";
    
       while (file.eof() == 0)
       {
          file >> str;
          cout << str << " ";
       }
    
       file.close();
    
       return 0;
    
    }

    Output: After the execution, the following output will be displayed on the screen.

    read a file in C++

  • C++ Program to Find Largest of Two Numbers

    In this tutorial program, we will write a program to find the largest of two numbers in C++. We will discuss few ways to do so. We will check two ways:

    1. Using if-else satement
    2. Using conditional operator.

    To understand the program better, you should have knowledge of the following topics in C++.


    C++ Program to Find Largest of Two Numbers using if else statement

    The program takes a user input for the two numbers which are to be checked. Then using if else statement, t simply checks through the condition which one is greater and prints the result of the largest one.

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int num1, num2;
    
       cout << "Enter the 1st number: ";
       cin >> num1;
       cout << "Enter the 2nd number: ";
       cin >> num2;
    
       if (num1 > num2)
       {
          cout << num1 << " is the largest.";
       }
       else
       {
          cout << num2 << " is the largest.";
       }
    
       return 0;
    }

    Outputs:

    Enter the 1st number: 25
    Enter the 2nd number: 30
    30 is the largest.


    C++ Program to Find Largest of Two Numbers using conditional operator

    It is the same as the above, the difference is that instead of is else statement, we use the conditional operator. It works the same as the if else statement and makes the code clean and in a single line.

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int num1, num2, largest;
    
       cout << "Enter the 1st number: ";
       cin >> num1;
       cout << "Enter the 2nd number: ";
       cin >> num2;
    
       largest = (num1 > num2) ? num1 : num2;
    
       cout << largest << " is the largest of two.";
    
       return 0;
    }

    Outputs:

    Enter the 1st number: 45
    Enter the 2nd number: 13
    45 is the largest of two.


  • C++ Program to Print Multiplication Table of any Number

    In this tutorial, we will write a C++ program to generate a multiplication table for any number and also for the given range.

    In order to understand the program, you should go through the following topic in C++.


    C++ Program to Print Multiplication Table of any Given Number

    The program will print the table of the number entered by the user up to 10. The program uses for loop to iterate and print the number.

    #include <iostream>
    using namespace std;
    
    int main()
    {
        int n;
    
        cout << "Enter the number: ";
        cin >> n;
    
        for (int i = 1; i <= 10; ++i)
            cout << n << " * " << i << " = " << n*i << endl;
        
        return 0;
    }

    Output:

    Enter the number: 4
    4 * 1 = 4
    4 * 2 = 8
    4 * 3 = 12
    4 * 4 = 16
    4 * 5 = 20
    4 * 6 = 24
    4 * 7 = 28
    4 * 8 = 32
    4 * 9 = 36
    4 * 10 = 40


    C++ Program to Print Multiplication Table of any Number upto a given range

    This program will work as same as the above, the extra feature added here is the range. The above program displays the table of any number up to 10 but here it will print the table up to the user’s choice.

    The program takes user input for the number whose table needs to be displayed and also the range up to which number it should display.

    #include <iostream>
    using namespace std;
    
    int main()
    {
        int num, range;
    
        cout << "Enter the number: ";
        cin >> num;
        
        cout << "Enter range: ";
        cin >> range;
    
        for (int i = 1; i <= range; ++i)
            cout << num << " * " << i << " = " << num*i << endl;
        
        return 0;
    }

    Output:

    Enter the number: 6
    Enter range: 15
    6 * 1 = 6
    6 * 2 = 12
    6 * 3 = 18
    6 * 4 = 24
    6 * 5 = 30
    6 * 6 = 36
    6 * 7 = 42
    6 * 8 = 48
    6 * 9 = 54
    6 * 10 = 60
    6 * 11 = 66
    6 * 12 = 72
    6 * 13 = 78
    6 * 14 = 84
    6 * 15 = 90


  • C++ Program to Calculate Grade of Student

    In this tutorial, we will write a C++ program to find the grades of the student. Before that, you should have knowledge of the following topics in C++.

    The program takes the user input for a number of subjects and the marks obtained on each of the subjects. The marks of the subject is taken using for loop. Then the program finds the sum of the marks and finally the average of the marks.

    Then using an else-if ladder in C++, we will find the category of the marks it belongs to. and display the grade obtained by the student.


    C++ Program to Calculate Grade of Student

    C++ Program to Calculate Grade of Student using if else statement.

    #include<iostream>
    using namespace std;
    
    int main()
    {
       int num, i;
       float marks[10], avg = 0, sum = 0;
       
       cout << "Enter number of subject: ";
       cin >> num;
       
       cout << "Enter marks for " << num << " subjects:\n";
       for (i = 0; i < num; i++)
       {
          cin >> marks[i];
       }
    
       //find the sum and average
       for (i = 0; i < num; i++)
       {
          sum += marks[i];
       }
       avg = sum / num;
       cout << "Average obtained: " << avg;
       
       cout << "\nGrade obtained: ";
       if (avg > 90)
       {
          cout << "A grade";
       }
       else if (avg < 90 && avg >= 75)
       {
          cout << "B grade";
       }
       else if (avg < 75 && avg >= 50)
       {
          cout << "C grade";
       }
       else if (avg < 50 && avg >= 30)
       {
          cout << "D grade";
       }
       else
       {
          cout << "Fail";
       }
    
       return 0;
    }

    Output:

    Enter number of subject: 5
    Enter marks for 5 subjects:
    75
    84
    29
    63
    77
    Average obtained: 78.2
    Grade obtained: B grade

    Although, the range of average for each grade is up to the programmer. You can change the average range and grade according to the program you want to create.


  • C++ Program to Calculate the Sum of Digits of a Number

    We will write the sum of digits program in C++. Before that, you should have knowledge of the topics in C++ given below.

    The program takes a user input for the integer whose sum of the digits needs to be found. Then using while loop, we will iterate the number and extract each digits and add it to the following one.

    Lastly, we will display the sum of digits of that number. Let us go through the program.


    C++ Program to Find Sum of Digits of a Number

    In this program, we will use a while loop to iterate through the number. You can also do that using for loop.

    C++ program to display the sum of the digits using a while loop.

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int num, rem, sum = 0;
    
       cout << "Enter the Number: ";
       cin >> num;
    
       while (num > 0)
       {
          rem = num % 10;
          sum += rem;
          num /= 10;
       }
    
       cout << "Sum of Digits: " << sum;
    
       return 0;
    }

    Output:

    Enter the Number: 123
    Sum of Digits: 6


    C++ Program to Calculate the Sum of Digits of a Number using for loop

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int number, rem, sum = 0;
    
       cout << "Enter the Number: ";
       cin >> number;
    
       for (sum = 0; number > 0; number /= 10)
       {
          rem = number % 10;
          sum += rem;
       }
    
       cout << "Sum of Digits: " << sum;
    
       return 0;
    }

    Output: After successful execution of the above program, it will create the same output as the above one.


  • Arithmetic Mean Program in C++

    We will write a C++ Program to Calculate Arithmetic Mean. Before that, you should have knowledge of the topics in C++ given below.

    Arithmetic mean is the sum of a collection of numbers divided by the number of numbers in the collection. For example:

    arithmetic mean = (n1 + n2 +n3 + ... + nn)/n

    The program takes a number as an input from the user whose arithmetic mean is to be calculated. Then iterating that number through a for loop, we will calculate the sum of the number and then finally calculate the mean of the result of the sum of the number.

    Lastly, display the arithmetic mean of the entered number in C++.


    Arithmetic Mean Program in C++

    There is a use of an array to store the numbers entered by the user.

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int num, i, arr[50], sum = 0, armean;
    
       cout << "How many number you want to enter?: ";
       cin >> num;
    
       cout << "Enter " << num << " Number:\n";
       for (i = 0; i < num; i++)
       {
          cin >> arr[i];
          sum = sum + arr[i];
       }
    
       armean = sum / num;
    
       cout << "Arithmetic Mean: " << armean;
    
       return 0;
    }

    Output:

    How many number you want to enter?: 4
    Enter 4 Number:
    2
    3
    4
    1
    Arithmetic Mean: 2

    Also, you can change the data type according to your need. It could be float, double, etc.


  • C++ Program to Check Palindrome Number

    In this tutorial, we will write a C++ program to check whether a number is Palindrome or not. Before that, you may go through the following topic in C++.

    A number is said to be a Palindrome number if it remains the same when its digits are reversed or are the same as forward. It can be applied to the word, phrase, or other sequences of symbols.

    For example: 14141, 777, 272 are palindrome numbers as they remain the same even if they are reversed. If we take the example of ‘mam’ or ‘madam’, these are also palindrome words.


    Program to Check Palindrome Number or Not in C++

    C++ program to check for palindrome numbers without using fucntion. Here the program asks the user to give the input and then checks the number by iterating it through a while loop.

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int number, rev = 0, digit, temp;
    
       cout << "Enter the Number: ";
       cin >> number;
    
       temp = number;
       while (temp > 0)
       {
          digit = temp % 10;
          rev = (rev *10) + digit;
          temp /= 10;
       }
    
       if (rev == number)
          cout << number << " is a Palindrome Number";
       else
          cout << number << " is not a Palindrome Number";
    
       return 0;
    }

    Output:

    Enter the Number: 232
    232 is a Palindrome Number


  • C++ Program to Check Whether a Character is Vowel or Consonant

    In this tutorial, we will write a C++ Program to Check Vowel or Consonant. To understand the example, you need to have knowledge of the following topic in C++.


    There are total 26 alphabets together out of which 5 are the vowels (a, e, i, o, u) and the rest are the consonant.

    The program below will take character input from the user to check. The program makes sure the vowel entered are the uppercase and lowercase letters then check using if..else statement.

    Let us go through the program.


    C++ Program to Check Whether a Character is Vowel or Consonant

    #include <iostream>
    using namespace std;
    
    int main()
    {
       char ch;
    
       cout << "Enter an alphabet: ";
       cin >> ch;
    
       if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
          cout << ch << " is a Vowel";
       else if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
          cout << ch << " is a Vowel";
       else
          cout << ch << " is a Consonant";
    
       return 0;
    }

    Output:

    //Run 1
    Enter an alphabet: e
    e is a Vowel

    //Run 2
    Enter an alphabet: j
    j is a Consonant