Coding Practice
Showing posts with label Programming Language. Show all posts
Showing posts with label Programming Language. Show all posts

Project - Linux Toolbox | Based on Shell Script

Table of Content

Chapter 1 Introduction

  1.1 Introduction

  1.2 Design Goals/Objective

Chapter 2 Design/Development/Implementation of the Project

  2.1 Design

  2.2 Code Implementation

Chapter 3 Performance Evaluation

  3.1 Simulation Environment/ Simulation Procedure

  3.2 Results and Discussions

  3.3 Analysis and Outcome

  3.4 Limitations

Chapter 4 Conclusion

  4.1 Introduction

  4.2 Practical Implications

  4.3 Scope of Future Work

References

Chapter 1

Introduction

1.1 Introduction

Linux Toolbox is a tool for Linux operating systems, which allow to check the different type of system information. For example - date, time, device owner, disk usages, memory usages, CPU usages and etc. Another feature of Linux Toolbox is - it will show the current monthly calendar for any year, it can manage a huge of contact information, and it can create a notebook.

1.2 Design Goals/Objective

The sole intention behind the consideration of this project is to generate and manage to show some system information. This project has been developed considering note and contact information keeping the context of the user in mind. Here, the data has been stored in a few text files in the storage.

Chapter 2

Design/Development/Implementation of the Project

2.1 Design

To develop Linux Toolbox, we use Visual Studio Code IDE for code edit. The Linux Toolbox is a simple GUI-based application that has been developed in Shell Script. It is allowed to show system information, enables a store of notebook and contact information. Those are essentially databases that track all information for a user and a user can avail the benefits of using this application. Here, linux_toolbox.sh is the main file. There is also have a file calendar.sh that can show a month of calendar for the user.

2.2 Code Implementation

In this application, users can sign-up, log-in and see the monthly calendar. Also, users can use notebooks and add favorite contact information. We worked with Bash language and use Graphical User Interface via the YAD library. In the case of Bash/Shell Script, we have used some functions such as calendar, home, notebook, view_all_note, contact, and etc which have been used to reduce the code space. Click below to jump in the source code-

Source Code - Linux Toolbox
#!/bin/bash

FILE=$(pwd)/admin.log
LOGGEDIN=$(pwd)/loggedin.log

# bash functions start
#calendar window
function calendar(){
   yad --center --borders=10 --width=420 --title="Linux Toolbox - Calendar" --calendar --button=Back:0

   if [ ${?} -eq 252 ]; then
       echo "Linux Toolbox closed by user"
       exit
   fi
}

function view_all_note() {
    echo "View all note"

    # Get all note from file
    note_file=$(pwd)/notebook.txt

    if [ -f "$note_file" ]; then
        note_text=$(cat notebook.txt)
        notebook=$(yad --scroll --width=450 --height=500 --title="Linux Toolbox - Notebook" --borders=10 --center --separator="ㅤ" \
        --text-align=center \
        --text="<span><b><big><big>My Notes</big></big></b></span>" \
        --form \
        --field="$note_text":LBL \
        --button="Back:0" \
        )
        btn_click=$?

        if [ $btn_click == 0 ]; then
            echo "Back to Notebook"
        elif [ $btn_click == 252 ]; then
            echo "Linux Toolbox closed by user"
            exit
        fi
    else
        echo "No note found"
        notebook=$(yad --scroll --width=450 --height=500 --title="Linux Toolbox - Notebook" --borders=10 --center --separator="ㅤ" \
        --text-align=center \
        --text="<span><b><big><big>My Notes</big></big></b></span>" \
        --form \
        --field="No note found":LBL \
        --button="Back:0" \
        )
        btn_click=$?

        if [ $btn_click == 0 ]; then
            echo "Back to Notebook"
        elif [ $btn_click == 252 ]; then
            echo "Linux Toolbox closed by user"
            exit
        fi
    fi
}

function notebook(){

    while :
    do
        notebook=$(yad --width=450 --height=500 --title="Linux Toolbox - Notebook" --borders=10 --center --separator="ㅤ" \
        --text-align=center \
        --text="<span><b><big><big>Create Your Note</big></big></b></span>" \
        --form --field="<b>Title</b>": \
        --field="":TXT \
        --button="Add:2" \
        --button="View:3" \
        --button="Back:0" \
        )
        btn_click=$?

        if [ $btn_click == 0 ]; then
            echo "Back to home"
            break
        elif [ $btn_click == 2 ]; then
            title=$(echo $notebook | awk -F "ㅤ" '{print $1}')
            notebook=$(echo $notebook | awk -F "ㅤ" '{print $2}')
            break="\n----------------------------------------------------------------------------------------------------------\n"
            echo "Title: $title\nNote: $notebook $break" >> notebook.txt
            echo "Note added"
        elif [ $btn_click == 3 ]; then
            echo "View Note"
            view_all_note
        fi
    done
}

# contact window start
function add_contact(){

    contact_value=$(yad --form --center --borders=10 --width=380 --height=280 --title="Linux Toolbox" --separator='ㅤ' \
    --text-align=center --text="<span><b><big><big>Add Contact</big></big></b></span>"\
    --field="  <b>Name:</b>":LBL \
    --field="" \
    --field="  <b>Phone:</b>":LBL \
    --field="" \
    --field="  <b>Email:</b>":LBL \
    --field="" \
    --button=Add:0 \
    --button=Back:1 \ ) valid=${?}

    code=${?}

    if [ $code == 1 ]; then
        echo "Back to the contact window"
    elif [ $code == 0 ]; then
        echo "$contact_value"
        echo "Add contact"

        name=$(echo $contact_value | awk -F "ㅤ" '{print $2}')
        phone=$(echo $contact_value | awk -F "ㅤ" '{print $4}')
        email=$(echo $contact_value | awk -F "ㅤ" '{print $6}')
        break="------------------------------------------------"
        echo -e "Name: $name | Phone: $phone | Email: $email\n" >> contact_list.log
        add_contact
    fi
}

function phone_number_not_found(){
    echo "Phone number not found"
    $(yad --center --borders=10 --width=350 --height=300 --title="Linux Toolbox" --text="<span><b><big><big>Phone number not found</big></big></b></span>" \
    --button="Back":1 \ )
    code=${?}

    if [ $code == 1 ]; then
        echo "Back to home window"
    elif [ $code == 252 ]; then
        echo "Linux Toolbox closed by user"
        exit
    fi
}

function update_contact(){

    echo "Update contact"

    update_string=$(yad --form --center --borders=10 --width=350 --height=300 --title="Linux Toolbox" --separator='ㅤ' --text-align=center --text="<span><b><big><big>Update Contact</big></big></b></span>" \
    --field="<b>Old Phone:</b>":LBL \
    --field="" \
    --field="<b>New Name:</b>":LBL \
    --field="" \
    --field="<b>New Phone:</b>":LBL \
    --field="" \
    --field="<b>New Email:</b>":LBL \
    --field="" \
    --button="Update":0 \
    --button="Back":1 \ )

    code=${?}

    if [ $code == 1 ]; then
        echo "Back to home window"
    elif [ $code == 0 ]; then
        echo "Update string: $update_string"
        
        old_phone=""
        

        entry_phone=$(echo $update_string | awk -F "ㅤ" '{print $2}')
        full_string=$(grep -i "$entry_phone" contact_list.log)
    
        old_name=$(echo $full_string | awk '{print $2}')
        old_phone=$(echo $full_string | awk '{print $5}')
        old_email=$(echo $full_string | awk '{print $8}')

        echo "Full string: $full_string"
        echo "Old phone: $old_phone"
        echo "Entry phone: $entry_phone"

        if [ ! -z "$old_phone" ]; then
            if [ $entry_phone == $old_phone ]; then
                echo "Phone number found"

                new_name=$(echo $update_string | awk -F "ㅤ" '{print $4}')
                new_phone=$(echo $update_string | awk -F "ㅤ" '{print $6}')
                new_email=$(echo $update_string | awk -F "ㅤ" '{print $8}')

                if [ ! -z "$new_name" ]; then
                    sed -i "s/$old_name/$new_name/g" contact_list.log
                fi
                if [ ! -z "$new_phone" ]; then
                    sed -i "s/$old_phone/$new_phone/g" contact_list.log
                fi
                if [ ! -z "$new_email" ]; then
                    sed -i "s/$old_email/$new_email/g" contact_list.log
                fi
                echo "Contact Updated"
            else
                phone_number_not_found
            fi
        else
            phone_number_not_found
        fi
    elif [ $code == 252 ]; then
        echo "Linux Toolbox closed by user"
        exit
    fi
}

function view_contact(){
    
    echo "View contact"
    v_contact=$(nl -s '. ' -w 1 contact_list.log)

    $(yad --form --center --borders=10 --width=350 --height=300 --title="Linux Toolbox" --separator=' ' --text-align=center --scroll --text="<span><b><big><big>Contact List</big></big></b></span>"\
    --field="":LBL \
    --field="$v_contact":LBL \
    --button="Add":1 \
    --button="Update":2 \
    --button="Search":3 \
    --button="Delete":4 \
    --button="Back":0 \ )

    code=${?}
    
    if [ $code == 0 ]; then
        echo "Back to manage contact window"
    elif [ $code == 1 ]; then
        echo "Add contact"
        add_contact
    elif [ $code == 2 ]; then
        echo "Update contact"
        update_contact
    elif [ $code == 3 ]; then
        echo "Search contact"
        search_contact
    elif [ $code == 4 ]; then
        echo "Delete contact"
        delete_contact
    elif [ $code == 252 ]; then
        echo "Linux Toolbox closed by user"
        exit
    fi

}

function search_contact (){

    echo "Search contact"

    search_field=$(yad --form --center --borders=10 --width=350 --height=300 --title="Linux Toolbox" --separator=' ' --text-align=center --text="<span><b><big><big>Search Contact</big></big></b></span>" \
    --field="":LBL \
    --field="" \
    --button="Search":0 \
    --button="Back":1 \ ) code=${?}

    code=${?}

    if [ $code == 1 ]; then
        echo "Back to home window"
    elif [ $code == 0 ]; then
        echo "Search query: $search_field"
        contact_find $search_field
    elif [ $code == 252 ]; then
        echo "Linux Toolbox closed by user"
        exit
    fi
}

function contact_find {
    echo "Find contact"
    search=$(grep -i $1 contact_list.log)
    find_field=$(yad --form --center --borders=10 --width=450 --height=300 --scroll --title="Linux Toolbox" --separator=' ' --text-align=center --text="<span><b><big><big>Search Contact</big></big></b></span>"\
    --field="<b>Search Query:</b> $1\n\n<b>Result:</b>":LBL \
    --field="$search":LBL \
    --button="Back":1 \ ) code=${?}

    code=${?}

    if [ $code == 1 ]; then
        echo "Back to home window"
    elif [ $code == 252 ]; then
        echo "Linux Toolbox closed by user"
        exit
    fi
}

function delete_contact(){

    delete_string=$(yad --form --center --borders=10 --width=350 --height=300 --title="Linux Toolbox" --separator='ㅤ' --text-align=center --text="<span><b><big><big>Delete Contact</big></big></b></span>" \
    --field="<b>Enter Phone Number:</b>":LBL \
    --field="" \
    --button="Delete":0 \
    --button="Back":1 \ ) code=${?}


    if [ $code == 1 ]; then
            echo "Back to home window"
    elif [ $code == 0 ]; then

        echo "Delete string: $delete_string"
        
        entry_phone=$(echo $delete_string | awk -F "ㅤ" '{print $2}')
        full_string=$(grep -i "$entry_phone" contact_list.log)

        delete_via_phone=$(echo $full_string | awk '{print $5}')

        echo "Delete row: $delete_via_phone"

        if [ ! -z "$delete_via_phone" ]; then
                if [ $entry_phone == $delete_via_phone ]; then
                
                    sed -i -e "/$delete_via_phone/d" contact_list.log
                    echo "Contact deleted"
                else
                    phone_number_not_found
                fi
        else
            phone_number_not_found
        fi
    fi
}
# contact window end

function contact(){
    
    while :
    do
        contact=$(yad --form --center --borders=10 --width=350 --height=300 --title="Linux Toolbox" --separator=' ' --text-align=center --text="<span><b><big><big>Manage Contacts</big></big></b></span>"\
        --field="":LBL \
        --field="<b>Add:</b> Add contact information. i.e: Name, Email Address, and Phone Number.":LBL \
        --field="<b>Update:</b> Update a specific contact.":LBL \
        --field="<b>View:</b> View the contact list after adding one or more contact to list.":LBL \
        --field="<b>Search:</b> Search a specific contact.":LBL \
        --field="<b>Delete:</b> Delete a specific contact.":LBL \
        --button="Add":1 \
        --button="Update":2 \
        --button="View":3 \
        --button="Search":4 \
        --button="Delete":5 \
        --button="Back":0 \ ) code=${?}

        code=${?}
        
        if [ $code == 0 ]; then
            echo "Contact window closed by user"
            ./linux_toolbox.sh
            exit
        elif [ $code == 1 ]; then
            echo "Add contact"
            add_contact
        elif [ $code == 2 ]; then
            echo "Update contact"
            update_contact
        elif [ $code == 3 ]; then
            echo "View contact"
            view_contact
        elif [ $code == 4 ]; then
            echo "Search contact"
            search_contact
        elif [ $code == 5 ]; then
            echo "Delete contact"
            delete_contact
        elif [ $code == 252 ]; then
            echo "Linux Toolbox closed by user"
            exit
        fi
    done
}

function home(){

    date=$(date +'%A %B %d, %Y')
    time=$(date +'%l:%M:%S %p')
    user=$(whoami)
    email=$(awk -F ":" '{print $1}' admin.log)
    # cmd: lscpu 
    #memory_usage=$(free | awk 'FNR==2 {print $3/(1024*1024),"/ "$2/(1024*1024)" GB"}')
    swap_usage=$(free | awk 'FNR==3 {print $3/(1024*1024),"/ "$2/(1024*1024)" GB"}')
    free_disk=$(df | awk 'FNR==4 {print $3/(1024*1024),"/ "$2/(1024*1024)" GB"}')

    total_memory=$(cat /proc/meminfo | awk 'FNR==1 {print $2/(1024*1024)}')
    availabe_memory=$(cat /proc/meminfo | awk 'FNR==3 {print $2/(1024*1024)}')
    memory_usage=$(echo "$total_memory - $availabe_memory" | bc)

    swap_usage=$(free | awk 'FNR==3 {print $3/(1024) "  MB","/ "$2/(1024*1024)" GB"}')
    disk_usage=$(df | awk 'FNR==4 {print $3/(1024*1024) " GB","/ "$2/(1024*1024)" GB"}')

    processor=$(cat /proc/cpuinfo | awk -F ": " 'FNR==5 {print $2}')
    cache_size=$(cat /proc/cpuinfo | awk -F ": " 'FNR==9 {print $2}')
    total_processor=$(cat /proc/cpuinfo | grep processor | wc -l)
    os_type=$(lscpu | awk 'FNR==2 {print $4}')
    os_support=$(lscpu | awk 'FNR==2 {print $3,$4}')
    cpu_speed=$(lscpu | awk 'FNR==16 {print $3}' | sed 's/\..*//')
    cpu_min_speed=$(lscpu | awk 'FNR==18 {print $4}' | sed 's/\..*//')
    cpu_max_speed=$(lscpu | awk 'FNR==17 {print $4}' | sed 's/\..*//')
    total_task=$(ps -e | wc -l)

    yad --title="Linux Toolbox" --center --borders=10 --width=450 --height=500 --text-align=center --separator="" --text="<span><b><big><big>System Info</big></big></b></span>" \
    --field="":LBL \
    --form \
    --field="<b><u>Basic Info</u></b>":LBL \
    --field="<b>Date:</b> $date":LBL \
    --field="<b>Time:</b> $time":LBL \
    --field="<b>Username:</b> $user":LBL \
    --field="<b>Email:</b> $email":LBL \
    --field="":LBL \
    --field="<b><u>Memory Info</u></b>":LBL \
    --field="<b>Memory Usage: </b>$memory_usage GB / $total_memory GB":LBL \
    --field="<b>Memory Available: </b>$availabe_memory GB":LBL \
    --field="<b>Swap Usage: </b>$swap_usage":LBL \
    --field="<b>Disk Usage: </b>$disk_usage":LBL \
    --field="":LBL \
    --field="<b><u>CPU Info</u></b>":LBL \
    --field="<b>Processor: </b>$processor × $total_processor":LBL \
    --field="<b>OS Type: </b>$os_type":LBL \
    --field="<b>OS Support: </b>$os_support":LBL \
    --field="<b>Cache Size: </b>$cache_size":LBL \
    --field="<b>CPU Speed: </b>$cpu_speed MHz":LBL \
    --field="<b>CPU Min Speed: </b>$cpu_min_speed MHz":LBL \
    --field="<b>CPU Max Speed: </b>$cpu_max_speed MHz":LBL \
    --field="<b>Total Task: </b>$total_task":LBL \
    --field="Calendar":FBTN "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "./calendar.sh" \
    --button="Notebook":2 \
    --button="Contact":3 \
    --button="Refresh":1 \
    --button="Log out":4 \
    --button="Exit":0
    code=${?}

    if [ $code == 0 ]; then
        echo "Linux Toolbox closed by user"
        exit
    elif [ $code == 1 ]; then
        echo "Refresh Date: $date $time"
    elif [ $code == 2 ]; then
        echo "Notebook window"
        notebook
    elif [ $code == 3 ]; then
        echo "Contact window"
        contact
    elif [ $code == 4 ]; then
        echo "Logged out"
        rm loggedin.log
        ./linux_toolbox.sh
        exit
    elif [ $code == 252 ]; then
        echo "Linux Toolbox closed by user"
        exit
    fi
}

export -f calendar home notebook view_all_note contact add_contact view_contact search_contact contact_find update_contact phone_number_not_found delete_contact
# bash functions end

if [ -f "$FILE" ]
then
    while :
    do
        
        if [ -f "$LOGGEDIN" ]
        then
            old_usr_pass=$(cat admin.log)
            log_usr_pass=$(cat loggedin.log)

            if [ $old_usr_pass == $log_usr_pass ]
            then
                # If the user has already logged in, redirected in home page
                echo "User already logged in"
                home
            else
                rm loggedin.log
                echo "User not logged in"
            fi
        else
            # login window start
            echo "Login window..."
            # login window
            login=$(yad --form --center --borders=10 --width=400 --height=300 --title="Linux Toolbox - Login" --separator=' ' \
                --button="Calendar":"bash -c calendar" \
                --button=Exit:1 \
                --button=Login:0 \
                --field="Email":\
                --field="Password":\') valid=${?}

            if [ $valid -eq 0 ]; then

                email=$(echo $login | awk '{print $1}') 
                password=$(echo $login | awk '{print $2}')

                echo "Email = $email"

            elif [ $valid -eq 1 ]; then
                echo "Linux Toolbox closed by user"
                exit
            fi
            # login window end

            echo -e "$email:$password" >> temp.log

            old_usr_pass=$(cat admin.log)
            crnt_usr_pass=$(cat temp.log)

            if [ $old_usr_pass == $crnt_usr_pass ]
            then
                rm temp.log
                echo "Login Successful"
                echo "$email:$password" >> loggedin.log
                # login success window start
                home
                # login success window end
            else
                rm temp.log
                # login failed window start
                echo "Login Failed!"
                echo "Wrong email or password"
                # login failed window end
            fi

        fi

    done

else
    # create admin.log file start
    echo "Signup window..."

    # signup window
    signup=$(yad --form --center --borders=10 --width=350 --height=300 --title="Linux Toolbox - Signup" --separator=' ' --text-align=center --text="<span><b><big><big>Signup</big></big></b></span>"\
        --field="":LBL \
        --button="Calendar":"bash -c calendar" \
        --button=Exit:1 \
        --button=Signup:0 \
        --field="Email":\
        --field="Password":\') valid=${?}

    if [ $valid -eq 0 ]; then

        email=$(echo $signup | awk '{print $1}') 
        password=$(echo $signup | awk '{print $2}')

        echo "Email = $email"
        # echo "Password = $password"

        echo "$email:$password" >> admin.log
        # create admin.log file end

        ./linux_toolbox.sh

    elif [ $valid -eq 1 ]; then
        echo "Linux Toolbox closed by user"
        exit
    fi
    
fi
Source Code - Calendar
echo "Calendar window"

yad --center --borders=10 --width=420 --title="Linux Toolbox - Calendar" --calendar --button=Back:0

if [ ${?} -eq 252 ]; then
    echo "Linux Toolbox closed by user"
    exit
fi

Chapter 3 Performance

Evaluation

3.1 Simulation

We have been able to meet the goals we set for ourselves in this project. Our code worked properly and was able to run Linux Toolbox. Also, the additional functions we added for user interaction all worked the way we initially expected. Each step along the way we tested our code to make sure everything was properly mapped.

3.2 Results and Discussions

After running Linux Toolbox, it will show the Sign-up window for the first time. Once the user has successfully signed up, the user will be shown a login window. And then the user needs to log in to use Linux Toolbox. Here users can use a blank email and password when signing up.

Sign-up window
Sign-in window

Figure-1: Sign-up and Login Window

After successful login, users will be able to view system information, add notebooks, and manage contact information.

System Information Window

Figure-2: System Information Window

Calendar Window

Figure-3: Calendar Window

Create Notebook Window

Figure-4: Create Notebook Window

Notebook Window

Figure-5: Notebook Window

Manage Contacts Window

Figure-6: Manage Contacts Window

Update Contacts Window
Search Contacts Window

Figure-7: Update and Search Contacts Window

Search Contacts Window

Figure-8: Search Contacts Window

Figure-9: Contact List Window

3.3 Analysis and Outcome

Our goal was to see the monthly calendar, add notes, manage contact, and view system information. In this project, our code worked properly and was able to successfully run Linux Toolbox. Also, the additional functions we added for user interaction all worked the way we initially expected. Each step along the way we tested our code to make sure everything was properly mapped.

3.4 Limitations

Although Linux Toolbox runs properly, there is some limitation for this application.

  1. In the Manage Contact part, the user can add multiple strings like a name but can’t update multiple strings as a name.
  2. The user can’t modify/update, search and delete Notebook.
  3. There may be other bugs in the Linux toolbox.

Chapter 4

Conclusion

4.1 Introduction

In this project, we gained a lot of knowledge and experience working with the Linux operating system. We learned how to work Bash language. Also, we learned more about the basic principles of Linux application. Our team members have made improvements in various areas such as developing a structured information pathway for all types of software and understanding more about state machines. Although this is a YAD base project, it was a great experience in developing software. The principle behind constructing a Linux Toolbox is to effectively retrieve and implement any information. All the information related to a particular people can be linked and archived only to be retrieved later when they are required most.

4.2 Practical Implications

Linux Toolbox is one of the useful applications used to show the system information. This type of software can be used to note down user information and create contact and also manage the contact information.

4.3 Scope of Future Work

In the future, we have planned to add more features for Linux Toolbox. For example, users can manage background applications such as kill or end process for Linux/GNU operating system. It would be handy for all Linux users. We have a plan to increase the limit of features. And we will upgrade it with many more facilities in the future.

Write a Java program to generate unique random numbers

Generate Unique Random Numbers
Sample Output
Enter a limit of random number: 10
1
5
2
4
9
3
10
6
8
7
Source Code
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class Main {

    public static boolean isDuplicate(ArrayList<Integer> numbers, int randomNumber){
        
        for (int i = 0; i < numbers.size(); i++) {
            
            if (numbers.get(i) == randomNumber) {
                
                return true;
            }
        }
        
        return false;
    }
    
    public static void main(String args[]) {

        Random random = new Random();

        int uniqueNumberCount = 0, randomNumber, limit;
        
        ArrayList<Integer> pastNumber = new ArrayList<>();
        
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter a limit of random number: ");
        limit = in.nextInt();
        
        for (int i = 0; uniqueNumberCount < limit; i++) {
            
            randomNumber = random.nextInt(limit) + 1;
            
            if (!isDuplicate(pastNumber, randomNumber)) {
                
                System.out.println(randomNumber);
                
                pastNumber.add(uniqueNumberCount++, randomNumber);
            }
        }

    }
}
Sample Output
Enter a limit of random number: 5
5
4
2
1
3

Write a C program to convert Binary to Decimal number system

Convert Binary to Decimal number system
Sample Output
Enter binary number: 1111111

Decimal Number: 127
Source Code
// Convert Binary to Decimal number system

#include<stdio.h>
#include<string.h>
#include<math.h>

int main()
{
    int i, bin_length, power, decimal_number = 0;
    char binary_number[100];

    printf("Enter binary number: ");
    scanf("%s", binary_number);

    // Length of binary_number string
    for(i = 0; binary_number[i] != '\0'; i++);
    bin_length = i;

    /*
    Decimal to Binary
    Example:
    Binary number = 1001

    2^3     2^2     2^1     2^0
    1       0       0       1
    8           +           1

    Decimal number = 9

    */

    for(i = 0, power = (bin_length - 1); i < bin_length; i++, power--)
    {
        if(binary_number[i] == '1')
        {
            decimal_number += pow(2, power);
        }
    }

    printf("\nDecimal Number: %d\n\n", decimal_number);

    return 0;
}
Sample Output
Enter binary number: 01101110

Decimal Number: 110

Write a C program to convert Binary to Octal number system

Convert Binary to Octal number system
Sample Output
Enter binary number: 11010

Octacl Number: 32
Source Code
// Convert Binary to Octal number system

#include<stdio.h>
#include<string.h>
#include<math.h>

int main()
{
    int i, bin_length, dec_length, remainder[100];
    int power, decimal_number = 0, octal_number, temp;
    char binary_number[100];

    printf("Enter binary number: ");
    scanf("%s", binary_number);

    // Length of binary_number string
    for(i = 0; binary_number[i] != '\0'; i++);
    bin_length = i;

    /*
    Decimal to Binary
    Example:
    Binary number = 1001

    2^3     2^2     2^1     2^0
    1       0       0       1
    8           +           1

    Decimal number = 9

    */

    for(i = 0, power = (bin_length - 1); i < bin_length; i++, power--)
    {
        if(binary_number[i] == '1')
        {
            decimal_number += pow(2, power);
        }
    }

    i = 0;
    while(decimal_number != 0)
    {
        remainder[i] = (decimal_number % 8);
        decimal_number /= 8;

        i++;
    }
    dec_length = i;

    for(i = (dec_length - 1); i >= 0; i--)
    {
        octal_number +=  (remainder[i] * pow(10, i));
    }

    printf("\nOctacl Number: %d\n\n", octal_number);

    return 0;
}
Sample Output
Enter binary number: 1111111

Octacl Number: 177

Write a C program to find two's complement of a binary number

Find two's complement of a binary number
Sample Output
Enter binary number: 01101110

One's Complement: 10010001
Two's Complement: 10010010
Source Code
// Find two's complement of a binary number

#include<stdio.h>
#include<string.h>

int main()
{
    int i, bin_length;
    char carry = '1', binary_number[100], ones_comp[100], twos_comp[100];
input:
    printf("Enter binary number: ");
    scanf("%s", binary_number);

    // Length of binary_number string
    for(i = 0; binary_number[i] != '\0'; i++);
    bin_length = i;

    for(i = 0; i < bin_length; i++)
    {
        if(binary_number[i] == '0')
        {
            ones_comp[i] = '1';
        }
        else if(binary_number[i] == '1')
        {
            ones_comp[i] = '0';
        }
        else
        {
            printf("Unexpected character! Please enter a valid input...\n\n");
            goto input;
        }
    }
    ones_comp[i] = '\0'; // End of string

    for(i = (bin_length - 1); i >= 0; i--)
    {
        if(ones_comp[i] == '1' && carry == '1')
        {
            twos_comp[i] = '0';
        }
        else if(ones_comp[i] == '0' && carry == '1')
        {
            twos_comp[i] = '1';
            carry = '0';
        }
        else if(carry == '0')
        {
            twos_comp[i] = ones_comp[i];
        }
    }

    printf("\nOne's Complement: %s\nTwo's Complement: %s\n\n", ones_comp, twos_comp);

    return 0;
}
Sample Output
Enter binary number: 00010100    

One's Complement: 11101011
Two's Complement: 11101100

Write a C program to find one's complement of a binary number

Find one's complement of a binary number
Sample Output
Enter binary number: 110101

Binary Number: 110101
One's Complement: 001010
Source Code
// Find one's complement of a binary number

#include<stdio.h>
#include<string.h>

int main()
{
    int i, bin_length;
    char binary_number[100], ones_comp[100];
input:
    printf("Enter binary number: ");
    scanf("%s", binary_number);

    // Length of binary_number string
    for(i = 0; binary_number[i] != '\0'; i++);
    bin_length = i;

    for(i = 0; i < bin_length; i++)
    {
        if(binary_number[i] == '0')
        {
            ones_comp[i] = '1';
        }
        else if(binary_number[i] == '1')
        {
            ones_comp[i] = '0';
        }
        else
        {
            printf("Unexpected character found! Please enter a valid input...\n\n");
            goto input;
        }
    }
    ones_comp[i] = '\0'; // End of string by creating a NULL value.

    printf("\nBinary Number: %s\nOne's Complement: %s\n\n", binary_number, ones_comp);

    return 0;
}
Sample Output
Enter binary number: 1010

Binary Number: 1010
One's Complement: 0101

Write a C program to print Fibonacci series up to n terms

Print Fibonacci series up to n terms
Sample Output
Enter a limit: 10

Fibonacci series: 0 1 1 2 3 5 8 13 21 34
Source Code
// Print Fibonacci series up to n terms

#include<stdio.h>

int main()
{
    int i, limit, first = 0, second = 1, last;

    /*
    FirstNum + LastNum = LastNum
    Fibonacci series: 0 1 1 2 3 5 8 13. . .
    */

    printf("Enter a limit: ");
    scanf("%d", &limit);

    printf("\nFibonacci series: ");
    for(i = 1; i <= limit; i++)
    {
        printf("%d ", first);

        last = first + second;
        first = second;
        second = last;
    }
    printf("\n\n");

    return 0;
}
Sample Output
Enter a limit: 11

Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55

Write a C program to print all Strong numbers between 1 to n

Print all Strong numbers between 1 to n
Sample Output
Enter a limit for Strong numbers: 150

All Strong numbers between 1 to n: 1 2 145
Source Code
// Print all Strong numbers between 1 to n

#include<stdio.h>
#include<math.h>

int main()
{
    int i, j, limit, number, numberClone, digit, sum = 0, factorial = 1;

    printf("Enter a limit for Strong numbers: ");
    scanf("%d", &limit);

    printf("\nAll Strong numbers between 1 to n: ");
    for(i = 1; i <= limit; i++)
    {
        number = numberClone = i;

        while(number != 0)
        {
            digit = (number % 10);
            number = (number / 10);

            // Sum of the factorial of the individual digits
            for(j = 1; j <= digit; j++)
            {
                factorial = (factorial * j);
            }
            sum = (sum + factorial);

            factorial = 1; // Reset value
        }

        if(numberClone == sum)
        {
            printf("%d ", numberClone);
        }

        sum = 0; // Reset value
    }
    printf("\n\n");

    return 0;
}
Sample Output
Enter a limit for Strong numbers: 50000

All Strong numbers between 1 to n: 1 2 145 40585

Write a C program to check whether a number is Strong number or not

Check whether a number is Strong number or not
Sample Output
Enter a number: 145

145 is a Strong number!
Source Code
// Check whether a number is Strong number or not

#include<stdio.h>
#include<math.h>

int main()
{
    int i, number, numberClone, digit, sum = 0, factorial = 1;

    printf("Enter a number: ");
    scanf("%d", &number);

    numberClone = number;

    while(number != 0)
    {
        digit = (number % 10);
        number = (number / 10);

        // Sum of the factorial of the individual digits
        for(i = 1; i <= digit; i++)
        {
            factorial = (factorial * i);
        }
        sum = (sum + factorial);

        factorial = 1; // Reset value
    }
    
    if(numberClone == sum)
    {
        printf("\n%d is a Strong number!\n\n", numberClone);
    }
    else
    {
        printf("\n%d is not a Strong number.\n\n", numberClone);
    }

    return 0;
}
Sample Output
Enter a number: 40585

40585 is a Strong number!

Write a C program to print all Armstrong numbers between 1 to n

Print all Armstrong numbers between 1 to n
Sample Output
Enter a limit for armstrong numbers: 900

All armstrong numbers 1 to 900: 1 2 3 4 5 6 7 8 9 153 370 371 407
Source Code
#include<stdio.h>
#include<math.h>

//Print all Armstrong numbers between 1 to n

int main()
{
    int i, limit, number, numberClone, digit, count = 0, newNumber = 0;

    printf("Enter a limit for armstrong numbers: ");
    scanf("%d", &limit);

    printf("\nAll armstrong numbers 1 to %d: ", limit);
    for(i = 1; i <= limit; i++)
    {
        number = i;
        numberClone = number;
        while(number != 0)
        {
            digit = (number%10);
            number /= 10;
            count++;
        }

        number = numberClone;
        while(number != 0)
        {
            digit = (number%10);
            number /= 10;

            newNumber += pow(digit, count);
        }

        if(numberClone == newNumber)
        {
            printf("%d ", newNumber);
        }

        count = 0;
        newNumber = 0;
    }
    printf("\n\n");

    return 0;
}
Sample Output
Enter a limit for armstrong numbers: 900

All armstrong numbers 1 to 900: 0 1 2 3 4 5 6 7 8 9 153 370 371 407

Write a C Code to find total marks from given input...

Write a C Code to find total marks from given input: Attendance, Class test, Quiz test, Assignment, Midterm and Final Exam and find the grade using the following method:

  1. If Total mark >=80 then A+
  2. If Total mark >=70 then A
  3. If Total mark >=60 then A
  4. If Total mark >=50 then B
  5. Else Grade = F

Sample Input

Enter Attendance, Class test, Quiz test, Assignment, Midterm and Final Exam: 2.5 7.5 3.5 7 21.5 33

Sample Output

Total Mark: 75 & Grade: A

Sample Output
Enter Attendance, Class test, Quiz test, Assignment, Midterm and Final Exam: 2.5 7.5 3.5 7 21.5 33
Total Mark: 75.000000 & Grade: A
Source Code
#include<stdio.h>

int main()
{
    float attendance, ct, qt, assignment, mid_mark, final_mark, total_mark;

    printf("Enter Attendance, Class test, Quiz test, Assignment, Midterm and Final Exam: ");
    scanf("%f %f %f %f %f %f", &attendance, &ct, &qt, &assignment, &mid_mark, &final_mark);
    //Input: 2.5 7.5 3.5 7 21.5 33

    total_mark = (attendance + ct + qt + assignment + mid_mark + final_mark);

    if(total_mark >= 80 && total_mark <= 100)
    {
        printf("Total Mark: %f & Grade: A+\n\n", total_mark);
    }
    else if(total_mark >= 70 && total_mark <= 79)
    {
        printf("Total Mark: %f & Grade: A\n\n", total_mark);
    }
    else if(total_mark >= 60 && total_mark <= 69)
    {
        printf("Total Mark: %f & Grade: A-\n\n", total_mark);
    }
    else if(total_mark >= 50 && total_mark <= 59)
    {
        printf("Total Mark: %f & Grade: B\n\n", total_mark);
    }
    else
    {
        printf("Total Mark: %f & Grade: F\n\n", total_mark);
    }

    return 0;
}
Sample Output
Enter Attendance, Class test, Quiz test, Assignment, Midterm and Final Exam: 2.5 7.5 3.5 7 21.5 33
Total Mark: 75.000000 & Grade: A

Write a C Code to calculate D = 𝒃^𝟐 − 𝟒𝐚𝐜 and...

Write a C Code to calculate D = 𝒃^𝟐 − 𝟒𝐚𝐜 and show the result according to following conditions:

a. D>0 then Calculate X1, X2. Where 𝒙𝟏 = (−𝒃+√𝒃^𝟐−𝟒𝒂𝒄)/𝟐𝒂 and 𝒙𝟐 = (−𝒃−√𝒃^𝟐−𝟒𝒂𝒄)/𝟐𝒂

        b. D =0 then calculate X. Where 𝐱 = 𝒃^𝟐/𝟐𝒂

        c. D<0 then print “No Solution”.

Sample Input

        Enter a, b & c: 5 6 1

Sample Output

    X1: -0.2

    X2: -1
Sample Output
Enter a, b, & c: 5 6 1
X1: -0.200
x2: -1.000
Source Code
#include<stdio.h>
#include<math.h>

int main()
{
    float D, b, a, c, x, x1, x2;

    printf("Enter a, b, & c: ");
    scanf("%f %f %f", &a, &b, &c);

    D = ((b*b) - 4*a*c);

    if(D > 0)
    {
        x1 = (-b + sqrt(D))/(2*a);
        x2 = (-b - sqrt(D))/(2*a);

        printf("X1: %.3f\nx2: %.3f\n\n", x1, x2);
    }
    else if(D == 0)
    {
        x = (b*b)/(2*a);

        printf("X: %f\n\n");
    }
    else if(D < 0)
    {
        printf("No Solution\n\n");
    }
    return 0;
}
Sample Output
Enter a, b, & c: 5 6 1
X1: -0.200
x2: -1.000

Write a C program to solve the Drake equation...

Write a C program to solve the Drake equation N = R*fp*ne*fl*fi*fc*L. Where R, ne and L must be discrete value.

Sample Input

    Enter R, F(p), n(e), f(l), f(i), f(c), L: 5 0.25 20 0.2 0.15 0.11 150

Sample Output

    The number of communicative civilizations within the Milky Way today: 12.375

Sample Output
Enter R, F(p), n(e), f(l), f(i), f(c): 5 0.25 20 0.2 0.15 0.11 150
The number of communicative civilizations within the Milky Way today: 12.375
Source Code
#include<stdio.h>
#include<math.h>

int main()
{
    float N, fp, fl, fi, fc;
    int R, ne, L;

    printf("Enter R, F(p), n(e), f(l), f(i), f(c): ");
    scanf("%d %f %d %f %f %f %d", &R, &fp, &ne, &fl, &fi, &fc, &L); //Input: 5 0.25 20 0.2 0.15 0.11 150

    float n = (float)R*ne*L;
    N = n*fp*fl*fi*fc;

    printf("The number of communicative civilizations within the Milky Way today: %.3f\n\n", N);

    return 0;
}
Sample Output
Enter R, F(p), n(e), f(l), f(i), f(c): 5 0.25 20 0.2 0.15 0.11 150
The number of communicative civilizations within the Milky Way today: 12.375

Project Contact Management System | Based on C Language

 TABLE OF CONTENTS

1. Introduction

2. Background

3. Requirements & Design

4. Implementation

5. Result and Evaluation

6. Conclusion

7. References

8. Source Code

1. Introduction

Contact Management System is a simple console application that is developed in C Language. This program enables to store data and manage contact information. Those are essentially databases that track all (i.e. Name, Phone Number and Email address) information and communication based on user contacts.

2. Background

Features for this application: Login, Show Contact List, Insert/Add Contact, Delete Contact, Search Contact, Security Settings, Change Username and Password, Sort Contact, Log Out, Login Again or Exit program. For this project, all of the contents based on C Language.

3. Requirements & Design

Contact Management System is console base project without graphics. It is similar to the contact manager in cell phones. This mini project use file handling and data structures. For design this project I used array, function, if...else, for loop, nested loop, switch, case, and etc. Basically, this is an easy and fundamental level mini project for learning purposes. We used simple design for this project.

4. Implementation

Describe the program code in below for understanding this project-

4.1 Set Username and Password

If user run this project for first time, Set Username and Password is mandatory option to manage contact. After set Username and Password, this is not required for next time.

Sample output:

4.2 Login to manage contacts

After set Username and Password, Login to manage contacts is another mandatory option to manage contacts.

Sample output:

4.3.1 See Contact List

See Contact List can help to show all contact.

Sample output:

4.4.2 Add Contact

Add Contact can add Name, Phone Number and Email Address in Contact list.

Sample output:

4.5.3 Delete Contact

Delete Contact can delete Name, Phone Number and Email Address in Contact list on specific position. 

Sample output:

4.5.4 Search Contact

Search Contact can search by Name or Phone Number in Contact list for easily find people. 

Sample Output:

4.5.5 Sort Contact

Sort Contact can sort by Name or Phone Number on Contact list.

Sample Output:

4.5.6 Security Setting

For this project, the user can change Username and Password by Security Setting.

Sample Output:

4.5.8 Log Out

The user can log out from all features by Log Out option.

Sample Output:

5. Result and Evaluation

After run this project, we can see many features and add Name, Phone Number and Email address as Contact Management System. Here, the data will be stored in the ContactList.txt file. If the file is deleted, the user must lost his/her all data.

6. Conclusion

The principle behind constructing a Contact Management System is to effectively retrieve and implement any information. All the information related to a particular people can be linked and archived only to be retrieved later when they are required most.

7. References

This project based on Data Structure.

Source Code
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>

int size = 0, i = 0, j, position, option, isFound = 0, m, n;
FILE *fp;
char search[20];

struct contact
{
    char name[20], phone[20], email[30], username[20], password[20];

} list[100], temp;

int fileOpenRead();
int fileOpenWrite();
int readFile();
int mainMenu();
int main();
int forgetUserPass();

int optionMenu()
{
    printf("\n\n1. Main Menu\n\nEnter a following option: ");
    scanf("%d", &option);

    system("cls");

    switch(option)
    {
    case 1:
        mainMenu();
        break;

    default:
        printf("Invalid Input for Main Menu!\n\n");
        mainMenu();
        break;
    }
}

int aboutAuthor()
{
    printf("Rakibul Islam\n\n");

    optionMenu();
    system("cls");
}

int contactList()
{
    printf("Contact List");
    printf("\n------------\n\n");

    fileOpenRead();

    for(j = 0; j < size; j++)
    {
        printf("Name: %s\nPhone: %s\nEmail: %s\n\n", list[j].name, list[j].phone, list[j].email);
    }
    fclose(fp);

    optionMenu();
}

int optionMenuTwo()
{
    printf("\n\n1. Contact List\n2. Main Menu\n\nEnter a following option: ");
    scanf("%d", &option);

    system("cls");

    switch(option)
    {
    case 1:
        contactList();
        break;

    case 2:
        mainMenu();

    default:
        printf("Invalid Input for Main Menu!\n\n");
        mainMenu();
        break;
    }
}

int addContact()
{
    readFile();

    printf("Add New Contact");
    printf("\n---------------\n\n");

    fp = fopen("ContactList.txt", "wb");

    printf("Enter Name: ");
    scanf("%s", list[i].name);

    printf("Enter Phone Number: ");
    scanf("%s", list[i].phone);

    printf("Enter Email: ");
    scanf("%s", list[i].email);

    size++;
    i++;

    fileOpenWrite();
    readFile();
    printf("\n\n1. Contact List\n2. Add New Contact\n3. Main Menu\n\nEnter a following option: ");
    scanf("%d", &option);
    printf("\n");

    system("cls");

    switch(option)
    {
    case 1:
        contactList();
        break;

    case 2:
        addContact();
        break;

    case 3:
        mainMenu();
        break;

    default:
        printf("Invalid Input for Main Menu!\n\n");
        mainMenu();
        break;
    }
}

int deleteContact()
{
    printf("Delete Contact");
    printf("\n--------------\n\n");

    readFile();
    fileOpenRead();

    for(j = 0; j < size; j++)
    {
        printf("%d. Name: %s\nPhone: %s\nEmail: %s\n\n", j + 1, list[j].name, list[j].phone, list[j].email);
    }
    fclose(fp);

    printf("Enter a position to delete: ");
    scanf("%d", &position);

    if(position <= j && position > 0)
    {
        fileOpenRead();

        fp = fopen("ContactList.txt", "wb");

        for(j = position; j < size; j++)
        {
            strcpy(list[j - 1].name, list[j].name);
            strcpy(list[j - 1].phone, list[j].phone);
            strcpy(list[j - 1].email, list[j].email);
        }
        size--;
        i--;
        j--;

        fileOpenWrite();
        readFile();

        system("cls");

        printf("Deleted!");
        optionMenuTwo();
    }
    else
    {
        system("cls");

        printf("Invalid Position!");
        optionMenu();
    }
}

int searchContact()
{
    printf("Search Contact");
    printf("\n--------------\n\n");

    fileOpenRead();

    printf("Enter Name or Number: ");
    scanf("%s", search);
    printf("\n");

    for(j = 0; j < size; j++)
    {
        if((strcmp(search, list[j].name) == 0))
        {
            printf("Name: %s\nPhone: %s\nEmail: %s\n\n", list[j].name, list[j].phone, list[j].email);
            isFound = 1;
        }
        else if((strcmp(search, list[j].phone) == 0))
        {
            printf("Name: %s\nPhone: %s\nEmail: %s\n\n", list[j].name, list[j].phone, list[j].email);
            isFound = 1;
        }
    }
    fclose(fp);

    if(isFound == 1);
    else
    {
        printf("Not Found!\n\n");
    }
    optionMenu();
}

int SortByName()
{
    fileOpenRead();

    fp = fopen("ContactList.txt", "wb");

    for(m = 0; m < size - 1; m++)
    {
        for(n = 0; n < size - m - 1; n++)
        {
            if(strcmp(list[n].name, list[n + 1].name) > 0)
            {
                temp = list[n];
                list[n] = list[n + 1];
                list[n + 1] = temp;
            }
        }
    }
    fileOpenWrite();
    readFile();
    printf("Sorted!");
    optionMenuTwo();
}

int SortByNumber()
{

    fileOpenRead();
    fp = fopen("ContactList.txt", "wb");

    for(m = 0; m < size - 1; m++)
    {
        for(n = 0; n < size - m - 1; n++)
        {
            if(strcmp(list[n].phone, list[n + 1].phone) > 0)
            {
                temp = list[n];
                list[n] = list[n + 1];
                list[n + 1] = temp;
            }
        }
    }
    fileOpenWrite();
    readFile();
    printf("Sorted!");
    optionMenuTwo();
}

int SortContact()
{
    printf("Sort Contact");
    printf("\n--------------\n\n");

    readFile();

    printf("1. Sort by Name\n2. Sort by Number\n3. Main Menu\n\nEnter a following option: ");
    scanf("%d", &option);

    system("cls");

    switch(option)
    {
    case 1:
        SortByName();
        break;

    case 2:
        SortByNumber();
        break;

    case 3:
        mainMenu();
        break;

    default:
        printf("Invalid Input for Main Menu!\n\n");
        mainMenu();
        break;
    }
}

int changeUsername()
{
    readFile();

    printf("Change Username");
    printf("\n------------\n\n");

    fileOpenRead();
    fp = fopen("ContactList.txt", "wb");

    printf("New Username: ");
    scanf("%s", list[1].username);

    printf("Password: ");
    scanf("%s", list[1].password);

    if(strcmp(list[1].password, list[0].password) == 0)
    {
        system("cls");

        strcpy(list[0].username, list[1].username);

        printf("Username changed successfully!");
        printf("\n\n");

        fileOpenWrite();
        fclose(fp);
        readFile();
        optionMenu();
    }
    else
    {
        fclose(fp);
        system("cls");

        printf("Wrong password!\n\n");
        forgetUserPass();
    }
}

int changePassword()
{
    readFile();

    printf("Change Password");
    printf("\n---------------\n\n");

    fileOpenRead();

    printf("Password: ");
    scanf("%s", list[1].password);

    if(strcmp(list[1].password, list[0].password) == 0)
    {

        printf("New Password: ");
        scanf("%s", list[2].password);

confirmNewPass:

        fp = fopen("ContactList.txt", "wb");

        printf("Confirm New Password: ");
        scanf("%s", list[3].password);

        if(strcmp(list[2].password, list[3].password) == 0)
        {
            strcpy(list[0].password, list[3].password);

            fileOpenWrite();
            fclose(fp);
            system("cls");

            printf("Password changed successfully!");
            printf("\n\n");

            readFile();
            optionMenu();
        }
        else
        {
            system("cls");

            printf("New Password and Confirm New Password are not same!");
            printf("\n\n");

            //printf("Password: %s\nNew Password: %s\n", list[1].password, list[2].password);
            printf("New Password: %s\n", list[2].password);
            goto confirmNewPass;
        }
    }
    else
    {
        fclose(fp);
        readFile();
        system("cls");

        printf("Wrong password!\n\n");
        forgetUserPass();
    }
}

int securitySetting()
{
    printf("Security Setting");
    printf("\n-------------------\n\n");

    printf("\n\n1. Change Username\n2. Change Password\n3. Main Menu\n\nEnter a following option: ");
    scanf("%d", &option);

    system("cls");

    switch(option)
    {
    case 1:
        changeUsername();
        break;

    case 2:
        changePassword();
        break;

    case 3:
        mainMenu();
        break;

    default:
        printf("Invalid Input for Main Menu!\n\n");
        mainMenu();
        break;
    }

    readFile();


}

int LoggedOutPage()
{
    printf("Logged Out!\n\n");
loginOption:
    printf("1. Login\n2. Exit\n\nEnter a following option: ");
    scanf("%d", &option);

    system("cls");

    switch(option)
    {
    case 1:
        main();
        break;

    case 2:
        printf("Exiting...\n\n");
        exit(0);
        break;

    default:
        printf("Invalid Input!\n\n");
        goto loginOption;
        break;
    }
}

int forgetUserPass()
{
    printf("Forget Username or Passwowrd");
    printf("\n---------------------------\n\n");

    printf("\n\n1. Show Username\n2. Show Password\n3. Main Menu\n\n\nEnter a following option: ");
    scanf("%d", &option);

    system("cls");

    switch(option)
    {
    case 1:
        printf("Username: %s", list[0].username);
        optionMenu();
        break;

    case 2:
        printf("Password: %s", list[0].password);
        optionMenu();
        break;

    case 3:
        mainMenu();
        break;

    default:
        system("cls");

        printf("Invalid Input!\n\n");
        mainMenu();
        break;
    }
}

int mainMenu()
{
    printf("Contact Managmenet System");
    printf("\n-------------------------\n\n\n");
    printf("1. See Contact List\n\n");
    printf("2. Add Contact\n\n");
    printf("3. Delete Contact\n\n");
    printf("4. Search Contact\n\n");
    printf("5. Sort Contact\n\n");
    printf("6. Security Setting\n\n");
    printf("7. About Author\n\n");
    printf("8. Log Out\n\n");

    printf("Enter a following option: ");
    scanf("%d", &option);
    printf("\n");

    system("cls");
    switch(option)
    {
    case 1:
        contactList();
        break;

    case 2:
        addContact();
        break;

    case 3:
        deleteContact();
        break;

    case 4:
        searchContact();
        break;

    case 5:
        SortContact();
        break;

    case 6:
        securitySetting();
        break;

    case 7:
        aboutAuthor();
        break;

    case 8:
        LoggedOutPage();
        break;

    default:
        printf("Invalid Input! Please Enter 1 to 6:\n\n");
        break;
    }
}


int main()
{
    SetConsoleTitle("Contact Managment System");

    //Default Password and Username.
    //strcpy(list[0].username, "0");
    //strcpy(list[0].password, "0");

    readFile();
    fileOpenRead();

    if(strcmp(list[0].username, "") == 0 && strcmp(list[0].password, "") == 0)
    {
        fp = fopen("ContactList.txt", "wb");

        printf("\t\t\t\tSet Username and Password\n");
        printf("\t\t\t\t------------------------\n");

        printf("\t\t\t\tEnter username: ");
        scanf("%s", list[0].username);

        printf("\n\t\t\t\tEnter password: ");
        scanf("%s", list[0].password);
        printf("\n");

        fileOpenWrite();
        readFile();
        fclose(fp);

        system("cls");
    }
    fclose(fp);
login:
    readFile();
    fileOpenRead();

    printf("\t\t\t\tLogin to manage contacts\n");
    printf("\t\t\t\t------------------------\n");
    printf("\t\t\t\tEnter username: ");
    scanf("%s", list[1].username);

    printf("\n");
    printf("\t\t\t\tEnter password: ");
    scanf("%s", list[1].password);
    printf("\n");

    if(strcmp(list[1].username, list[0].username) == 0 && strcmp(list[1].password, list[0].password) == 0)
    {
        fclose(fp);

        system("cls");
        printf("\t\t\t\tLogin successful!\n\n");
        printf("\n\n");
        readFile();

        while(1) //1 for infinite loop.
        {
            mainMenu();
        }
    }
    else
    {
invalid:

        system("cls");

        printf("Wrong useraname or password!\n\n");

        printf("1. Forget Useraname or Password\n2. Login\n\nEnter a following option: ");
        scanf("%d", &option);

        system("cls");

        switch(option)
        {
        case 1:
            printf("After few second it's automatically go Login page.\n\n");
            printf("Username: %s\nPassword: %s\n\nPlease wait...", list[0].username, list[0].password);

            Sleep(5000);
            system("cls");

            goto login;
            break;

        case 2:
            goto login;
            break;

        default:
            printf("Invalid Input!\n\n");
            goto invalid;
            break;
        }
    }

}

int fileOpenRead()
{
    fp = fopen("ContactList.txt", "rb");

    fread(&list, sizeof(list), 1, fp);
    fread(&size, sizeof(size), 1, fp);
    fread(&i, sizeof(i), 1, fp);
}

int fileOpenWrite()
{
    fwrite(&list, sizeof(list), 1, fp);
    fwrite(&size, sizeof(size), 1, fp);
    fwrite(&i, sizeof(i), 1, fp);
    fclose(fp);
}

int readFile()
{
    fileOpenRead();

    for(j = 0; j < size; j++)
    {
        list[j].name;
        list[j].phone;
        list[j].email;
    }
    fclose(fp);
}

Write a C/JAVA program to implement CRC

Implement CRC

The program will take a sequence of binary data bits, and a divider as input. And gives the resultant data with CRC as output. (Where, divider < binary data bits)

Sample Input:
Data: 10110
Divider: 1101

Sample Output:
Modified data: 10110000
Data Send: 10110101
CRC bit: 101

Sample Output
Enter data: 1001
Enter divisor: 1011

Input Data With Zero(s): 1001000

CRC Bit: 110

Modified Data: 1001110
Source Code
#include<stdio.h>
#include<stdlib.h>

void main()
{
    int i, j, k, l, numOfZero, dataLen;
    char divisor[100], data[100], remainder[100], divisorClone[100], dataClone[100], crc[100];

    printf("Enter data: ");
    scanf("%s", data);
    printf("Enter divisor: ");
    scanf("%s", divisor);

    for(i = 0; data[i] != '\0'; i++);
    dataLen = i;
    for(i = 0; divisor[i] != '\0'; i++);
    numOfZero = i;

    for(i = 0; i < numOfZero-1; i++)
    {
        data[dataLen+i] = '0';
    }
    printf("\nInput Data With Zero(s): %s\n", data);
    strcpy(dataClone, data);

    for(i = 0; i < dataLen; i++)
    {
        strcpy(divisorClone, divisor);
        if(data[i] < divisor[0])
        {
            for(l = 0; l < numOfZero; l++)
            {
                divisor[l] = '0';
            }
            divisor[l] = '\0';
        }
        for(j = i, k = 0; j < numOfZero+i; j++, k++)
        {
            if(data[j] == divisor[k])
            {
                remainder[j] = '0';
            }
            else
            {
                remainder[j] = '1';
            }
        }
        strcpy(divisor, divisorClone);
        remainder[j] = dataClone[j];
        remainder[j+1] = '\0';
        strcpy(data, remainder);
    }
    strcpy(data, remainder);

    for(i = dataLen, j = 0; i < dataLen+numOfZero; i++)
    {
        dataClone[i] = data[i];
        crc[j++] = data[i];
    }
    crc[j-1] = '\0';
    dataClone[i-1] = '\0';

    printf("\nCRC Bit: %s\n\nModified Data: %s\n\n", crc, dataClone);
}
Sample Output
Enter data: 10111011
Enter divisor: 1001

Input Data With Zero(s): 10111011000

CRC Bit: 110

Modified Data: 10111011110

Java Datatypes | HackerRank

Java Datatypes | HackerRank

Java has 8 primitive data types; char, boolean, byte, short, int, long, float, and double. For this exercise, we'll work with the primitives used to hold integer values (byte, short, int, and long):

  • A byte is an 8-bit signed integer.
  • A short is a 16-bit signed integer.
  • An int is a 32-bit signed integer.
  • A long is a 64-bit signed integer.

Given an input integer, you must determine which primitive data types are capable of properly storing that input.

To get you started, a portion of the solution is provided for you in the editor.

Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Input Format

The first line contains an integer, T, denoting the number of test cases.

Each test case, T, is comprised of a single line with an integer, n, which can be arbitrarily large or small.

Output Format

For each input variable n and appropriate primitive dataType, you must determine if the given primitives are capable of storing it. If yes, then print:

n can be fitted in:
* dataType

If there is more than one appropriate data type, print each one on its own line and order them by size (i.e.: byte < short < int < long).

If the number cannot be stored in one of the four aforementioned primitives, print the line:

n can't be fitted anywhere.

Sample Output
5
-150
150000
1500000000
213333333333333333333333333333333333
-100000000000000
-150 can be fitted in:
* short
* int
* long
150000 can be fitted in:
* int
* long
1500000000 can be fitted in:
* int
* long
213333333333333333333333333333333333 can't be fitted anywhere.
-100000000000000 can be fitted in:
* long
Source Code
import java.util.*;
import java.io.*;

class Solution{
    public static void main(String []argh)
    {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();

        for(int i = 0; i < t; i++)
        {
            try
            {
                long x = sc.nextLong();

                System.out.println(x + " can be fitted in:");
                if(x >= -128 && x <= 127){
                    System.out.println("* byte");
                }
                if(x >= -32768 && x <= 32767){
                    System.out.println("* short");
                }
                if(x >= -2147483648 && x <= 2147483647){
                    System.out.println("* int");
                }
                if(x >= -9.22337204e18 && x <= 9.22337204e18){
                    System.out.println("* long");
                }
            }
            catch(Exception e)
            {
                System.out.println(sc.next() + " can't be fitted anywhere.");
            }

        }
    }
}
Sample Output
5
-150
150000
1500000000
213333333333333333333333333333333333
-100000000000000
-150 can be fitted in:
* short
* int
* long
150000 can be fitted in:
* int
* long
1500000000 can be fitted in:
* int
* long
213333333333333333333333333333333333 can't be fitted anywhere.
-100000000000000 can be fitted in:
* long

Write a Java program to check whether a number is Armstrong number or not

Check whether a number is Armstrong number or not
Sample Output
Check whether a number is Armstrong number or not.

Enter a number: 371
371 is an Armstrong number!

Java-Source Code
//package loopinjava;

import java.util.Scanner;
import static java.lang.Math.pow;

public class Main {

    public static void main(String[] args) {

        int i, j, digit, number, numberClone, count = 0, newNumber = 0, temp;

        Scanner input = new Scanner(System.in);

        System.out.println("Check whether a number is Armstrong number or not.\n");

        System.out.print("Enter a number: ");
        number = input.nextInt();

        numberClone = number;
        
        while (number != 0) {
            digit = (number % 10);
            number /= 10; /// Or, number = number / 10;
            count++;
        }

        number = numberClone;
        while (number != 0) {
            digit = (number % 10);
            temp = (int) pow(digit, count);
            newNumber += temp;
            number /= 10; /// Or, number = number / 10;
        }

        number = numberClone;
        
        if (newNumber == number) {
            
            System.out.println(number + " is an Armstrong number!\n\n");
            
        } else {
            
            System.out.println(number + " is not an Armstrong number.\n\n");
        }
    }
}
Sample Output
Check whether a number is Armstrong number or not.

Enter a number: 372
372 is not an Armstrong number.

Write a Java program to print all Perfect numbers between 1 to n

Print all Perfect numbers between 1 to n
Sample Output
Print all Perfect numbers between 1 to n.

Enter a number: 10000
6
28
496
8128
Java-Source Code
//package loopinjava;

import java.util.Scanner;

public class Main33 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int i, j, number, newNumber = 0;
        System.out.println("Print all Perfect numbers between 1 to n.\n");

        System.out.print("Enter a number: ");
        number = input.nextInt();

        for (i = 1; i < number; i++) {
            newNumber = 0;

            for (j = 1; j < i; j++) {
                
                if (i % j == 0) {
                    newNumber = newNumber + j; //Or, newNumber += j;
                }
            }
            if (i == newNumber) {
                System.out.println(i);
            }
        }
    }
}
Sample Output
Print all Perfect numbers between 1 to n.

Enter a number: 100
6
28

Write a Java program to check whether a number is Perfect number or not

Check whether a number is Perfect number or not
Sample Output
Check whether a number is Perfect number or not.

Enter a number: 6
6 is a perfect number.

Java-Source Code
//package loopinjava;

import java.util.Scanner;
import static java.lang.Math.pow;

public class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int n, number, newNumber = 0;
        System.out.println("Check whether a number is Perfect number or not.\n");
        
        System.out.print("Enter a number: ");
        number = input.nextInt();

        for (n = 1; n < number; n++) {
            if (number % n == 0) {
                newNumber = newNumber + n; //Or, newNumber += n;
            }
        }
        if (number == newNumber) {
            System.out.println(number + " is a perfect number.\n");
        } else {
            System.out.println(number + " is not a perfect number.\n");
        }
    }
}
Sample Output
Check whether a number is Perfect number or not.

Enter a number: 5
5 is not a perfect number.

Write a Java program to find all prime factors of a number

Find all prime factors of a number
Sample Output
Find all prime factors of a number.

Enter a number: 15
Prime factors of 15: 3 5 
Java-Source Code
//package loopinjava;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        int i, j, number, isPrime;

        Scanner input = new Scanner(System.in);

        System.out.println("Find all prime factors of a number.\n");

        System.out.print("Enter a number: ");
        number = input.nextInt();

        System.out.print("Prime factors of " + number + ": ");
        for (i = 1; i <= number; i++) {

            if (number % i == 0) {
                isPrime = 1;
                for (j = 2; j < i; j++) {
                    if (i % j == 0) {
                        isPrime = 0;
                    }
                }
                if (isPrime == 1) {
                    if (i == 1) {
                        /**
                         * 1 is not a prime number
                         */
                    } else {
                        System.out.print(i + " ");
                    }
                }
            }
        }
        System.out.println();
    }
}
Sample Output
Find all prime factors of a number.

Enter a number: 10
Prime factors of 10: 2 5
Change Theme
X