Saturday 14 July 2012

Why C Language ?




C Programming language –
            C Programming language developed at Bell Laboratories of USA is a general purpose programming language initially developed by Dennis Ritchie in 1972 and later replaced programming languages of those times including PL/I, ALGOL etc.
There were few reasons why C became more popular as compared to programming languages of that time including FORTRAN, because it was reliable, simple and easy to code. One must learn C language before jumping to other object oriented programming languages such as C++, C#, Java because of the following reasons –
  1. One must learn the actual language elements before jumping to advance concepts including classes, objects, inheritance, polymorphism, templates, exception handling etc because learning these difficult elements without knowing the actual programming elements is learning the things in wrong order.
  2. Operating systems such as Windows, UNIX, and LINUX are all written in C language which itself defines its importance. Even today nothing can strike C when execution speed becomes a factor. Device driver programs are also written in C.


Floyd's Triangle in C

Floyds's triangle - 

 Its is a right-angled triangular array of natural numbers , used in computer science education. It is named after Robert Floyd. It is defined by filling the rows of the triangle with consecutive numbers, starting with a 1 in the top left corner: 

1
2 3
4 5 6
7 8 9 10



Sample Output -



Code -


/* C program to print Floyd's triangle:- This program prints Floyd's triangle. Number of rows of Floyd's triangle to print is entered by the user. First four rows of Floyd's triangle are as follows :-
1
2 3
4 5 6
7 8 9 10
It's clear that in Floyd's triangle nth row contains n numbers. */

#include<stdio.h>

#include<conio.h>

int main()
{
    int number_rows = 0, rows = 0, coloumn = 0, number = 1;

    printf("\n\n\t\t __ Program to print Floyd's Triangle in C __");

    printf("\n\n\n  Enter the number of Rows - ");

    scanf("%d",&number_rows);

    printf("\n\n");

    for(rows = 1; rows <= number_rows; rows++)
    {
        printf("\t");

        for(coloumn = 1; coloumn <= rows; coloumn++)
        {
            printf("%d ", number);
           
            number++;    //__ Number variable represents the numbers to be printed ___
        }

        printf("\n\n");
    }

    getch();

    return 0;

}



Friday 13 July 2012

Program to check for Vowel in C


Sample Output - 



Code - 


/* Program to check whether an input alphabet is a vowel or not */

/* Both if statement or switch case can be used */

#include<stdio.h>

#include<conio.h>

int main()
{
    char input_character;

    printf("\n\n\t __ Program to check for vowel or consonant (Using if Statement) __");

    printf("\n\n\n  Enter the Character - ");

    scanf("%c",&input_character);

    /*__ Another way of scanning the character is to use

        input_character = getchar();

    Note - a,e,i,o,u in english character set are known as Vowels */

    if ((input_character == 'o') || (input_character == 'O') || (input_character == 'a') || (input_character == 'A') || (input_character == 'e') || (input_character == 'E') || (input_character == 'i') || (input_character == 'I') || (input_character == 'u') || (input_character == 'U'))
    {
        printf("\n\n\t\t\t __ %c is a Vowel __ ",input_character);
    }
    else
    {
        printf("\n\n\t\t\t __ %c is a Consonant __",input_character);
    }

    getch();

    return 0;

    /* return 0 tells the compiler that the program has
   
                executed successfully without any error */
}




Sample Output - 



Code - 


/* Program to check whether an input alphabet is a vowel or not */

/* Both if statement or switch case can be used */

#include<stdio.h>

#include<conio.h>

int main()
{
    char input_character;

    printf("\n\n\t __ Program to check for vowel or consonant (Using Switch) __");

    printf("\n\n\n  Enter the Character - ");

    scanf("%c",&input_character);

    /*__ Another way of scanning the character is to use

        input_character = getchar();

    Note - a,e,i,o,u in english character set are known as Vowels */

    switch(input_character)
    {
   
    case 'a':
    case 'A':
    case 'e':
    case 'E':
    case 'i':
    case 'I':
    case 'o':
    case 'O':
    case 'u':
    case 'U': printf("\n\n\t\t\t __ %c is a Vowel __ ",input_character);
        break;

    default : printf("\n\n\t\t\t __ %c is a Consonant __",input_character);
   
    }

    getch();

    return 0;

    /* return 0 tells the compiler that the program has
   
                executed successfully without any error */
}



Thursday 12 July 2012

Program to calculate factorial of a number using recursion in C


Sample Output -




Code -



/* Program to calculate Factorial of a number using Recursion */

/* Recursion is a programming technique that allows the programmer to express operations in terms of themselves.

   In C/C++, this takes the form of a function that calls itself. */

#include<stdio.h>

#include<conio.h>

int factorial(int number);

int main()
{
int number = 0, result = 0;

printf("\n\n\t __ Program to calculate the factorial of a number using Recursion __");

printf("\n\n\n  Enter the Number - ");

scanf("%d",&number);

result = factorial(number);

printf("\n\n\t Factorial of %d = %d",number, result);

getch();

return 0;

/*___ return 0 tells the compiler that program has executed

successfully without any error */
}

int factorial(int number)
{
if (number == 1) //__ Condition that will stop the infinite looping __
{
return 1;
}
else
{
return number * factorial (number - 1); //__ Recursion __
}
}

Program to add Binary numbers in C




Sample Output -





Code - 



/* Program to add two binary numbers (No validation included) */

/* Program is a combination of 3 programs

1. Decimal to Binary
2. Binary to Deimal
3. Binary Numbers addition

*/

//___ Including header files ____

#include<stdio.h>

#include<conio.h>

#include<math.h>

int binary_decimal(int binary_number);

int decimal_binary(int decimal_number);

int main()
{
int bi_number_first = 0, bi_number_second = 0, de_number_first = 0, de_number_second = 0, sum = 0;

printf("\n\n\t\t  _____ Program to add two binary numbers_____");

printf("\n\n\t\t\t ___ No Validations included __");

printf("\n\n  Enter the first binary number  - ");

scanf("%d", &bi_number_first);

printf("\n\n  Enter the second binary number - ");

scanf("%d", &bi_number_second);

de_number_first = binary_decimal(bi_number_first);

de_number_second = binary_decimal(bi_number_second);

sum = de_number_first + de_number_second;

sum = decimal_binary(sum);

printf("\n\n\t\t  Sum of %d and %d is %d", bi_number_first, bi_number_second, sum);

getch();

return 0;
}

int binary_decimal(int binary_number)

//__ Function to convert binary number to decimal number __

{
int decimal_number = 0, remainder = 0, counter = 0;

while(binary_number != 0)
{
remainder = binary_number % 10; //___ Extracting the digits ____

binary_number = binary_number / 10; //__ Creating a new number ____

decimal_number = decimal_number + remainder * pow(2,counter);

          //___ Forming the decimal number __

counter++;
}

return decimal_number;

}

int decimal_binary(int decimal_number)

//__ Function to convert decimal number to binary number __

{
int remainder = 0, binary_number = 0, counter = 1;

while(decimal_number != 0)
{
remainder = decimal_number % 2;

decimal_number = decimal_number / 2;

binary_number = binary_number  + remainder * counter ;
 
                //__ Forming the binary number __

counter = counter * 10;
}

return binary_number;
}

Student Management System in C



Sample Output - 

First Screen (About System) - 




Navigational Menu - 





Stay Tuned will be updated every 15 minutes........

Code Coming later in the evening according to Indian Time.......

Program to convert Binary Number into Decimal Number in C


Sample Output - 





Code - 


/* Program to convert Binary number into Decimal number (No Validations Included)*/

//___ For Full Logic visit another post named "Convert Decimal to Binary/Binary to Decimal" ___

#include<stdio.h>

#include<conio.h>

#include<math.h> //__ Included for the pow(x,y) function __

/* To find out the implementation of the pow(x,y) function
check out post "One number raise to power another number in C" */

int main()
{
int decimal_number = 0, binary_number = 0, temp_number = 0, remainder = 0, counter = 0;

printf("\n\n\t   __ Program to convert Binary number into Decimal number __");

printf("\n\n\t\t\t __ No Validation Included __");

printf("\n\n\n  Enter the Binary Number - ");

scanf("%d",&binary_number); //__ Reading the binary number ___

temp_number = binary_number;

//__ Creating a copy of the binary_number inputted for diaplying purposes __

while(binary_number != 0)
{
remainder = binary_number % 10; //___ Extracting the digits ____

binary_number = binary_number / 10; //__ Creating a new number ____

decimal_number = decimal_number + remainder * pow(2,counter);
    
               //___ Forming the decimal number above __

counter++;
}

printf("\n\n  Decimal Conversion of Binary Number %d (BASE 2) is -- %d (BASE 10)", 

temp_number, decimal_number);

getch();

return 0;

/* return 0 tells the compiler that program has executed successfully without any errors */
}



Object Oriented Features (C++)



Objects -

In structured programming language a problem is approached by dividing it into functions however in object-oriented programming the problem is divided into objects. An object is a component of a program that can have its own set of data and can be used to perform more than a repeated task. Designing the system with objects allowed developer to model system after the real world.
For Example – The developer has created an object of the student class to store data associated with a single student using member data and can perform certain operations using this object such as adding a new student, listing a student, checking whether a particular student record exist or not using the member functions of the class.
The object has been defined using the class name and object name with the following format –
void student_module()
{
      student student_record;                  

// ............CREATING THE OBJECT OF THE STUDENT CLASS.............
     
      char ch,che;
      int count = 0;
There are many candidates that are treated as objects in the system which are students, books, and administrator.


Inheritance - 


As C++ allowed developer to create its own data types (classes) just like built in data types, C++ allowed the developer to use classes as building blocks of other classes using a concept called inheritance, new classes are built on top of the old ones. The new class referred to as a derived class, can inherit the data and functions of the original or the base class and can add its own data elements and functions.
For Example – The developer has designed a class named login as base class and inherited the class in the admin as well as student class as both student and admin need to login in the system. Data member for login class is a structure named login info having structure elements username and password, and a virtual member function system login. Both the admin and student class inherited login class and added its own data member’s admin name, structure student information etc.
The base class is inherited in the derived classes in following format –
Base Class –
class login
{
public:
            struct log_info{
                  int username;
                  char password[20];
            }log;

//__________PURE VIRTUAL FUNCTION______________ 

      virtual int system_login() = 0;    
     
};
Derived Classes –
class admin: public login          

//.........ADMIN CLASS INHERITING THE LOGIN CLASS..............
{
      private:
            char admin_name[20];
            char flag;
            fstream file;

      public:
            admin();
            int system_login(); //overriding
            void addrec();
};
class student: public login   //______INHERITANCE________
{
      public:
      struct student_information{

            char flag;
            int roll_number;
            char student_name[20];
            char course[20];
            char branch[16];
            int book_code;

            char issue_date[10], return_date[10];
            int fine;
            }b;

      private:
            fstream file;

      public:
            student();
            int system_login();
            void addrecUser();
            void addrec();
            void listrec();
            void delrec();
            void modrec();
            int check_record(int student_roll_number, int check_information);
            int check_exist( int student_roll_number);  //overloading 
            void Uprec();
            int  GetRoll();        
//______________FOR RANDOMLY GENERATING THE STUDENT ROLL NUMBER_____________

};




Wednesday 11 July 2012

Stacks - Linear Data Structure


Introduction - 

          Stack is an ordered collection of data items. It is a last in, first out (LIFO) abstract data type and linear data structure. In stack new items can be added and removed only at the top. Stack is similar to a pile of dishes where dishes can be added at the top and dish coming last would be removed first.

Remark - So, stack is a linear data structure where items are added or removed at one end only.



      Figure - Stack


Operations on Stack - 

                There are basically two primitive operations that can be carried out on a stack -

Push - Push operation is used to add a new node to the top of the stack.

Figure -  Push operation on Stack


Pop - Pop operation is used to remove an existing node from the top of the stack. 

Figure - Pop operation on Stack



Uses of Stacks - 

  • Stacks are used for evaluating Arithmetic expressions (and other sorts of expression).
  • Generally used for implementing function or method calls.
  • Implementing Recursion.


Linked List - Dynamic Data Structure


Introduction - 

         Linked list is a dynamic data structure i.e. data structure that grows and shrinks at run time. Linked List is a series of connected nodes where each node contains atleast 2 things -
    1. A piece of data
    2. Pointer (link) to the next node in the list


Figure - Linked List


Remark - Self - Referential structures (also referred as linked list) is a structure that contains a pointer to the structure of same type.

  Linked list are among the simplest and the most common data structures (and can be used to implement several other data structures such as stacks, queue which will discussed later on). Linked list allows insertion and removals anywhere in the list as compared to other data structures such as stacks which allows insertion and deletion only at the top of stack, queue where insertion take place at the back and removal from the front. Linked list uses a pointer variable header which stores the address of first node of the list and the last node pointer contains NULL value to show that there are no more elements in this list as shown in Figure above.

Benefits of Linked List (compared to an array) - 
  1. Linked do not need contiguous blocks of memory and Linked list storage need to be preallocated.
  2. Inserting or removing an element into a linked list requires one data update whereas in array it requires more updates. For Example -  Consider there are 10 elements in an array and currently 9 elements are present in the array and an element need to be inserted at 3 location. So, all the elements from array subscript 2 need to copied to the next location requiring 7 updates + one insertion at 3 location.
Note - Array Index starts from 0 not 1. So, 10 elements means that array subscript would be from 0 - 9.



Types of Linked List -


Singly Linked List - Begins with a pointer to the first node (header) and ends with a NULL in the pointer field of the last node. One of the limitation that singly list imposes over other linked list is that it can be traversed only in one direction.


Figure  - Singly Linked List

Circular Singly List - In circular singly linked list the pointer in the last node stores the address of the first node but still can be traversed only in one direction. However, in cases the linked list is empty we need a pointer to show that list is empty by setting its value to NULL.


Figure - Circular Singly Linked List


Doubly Linked List - Instead of using a single pointer doubly linked list make use of two start pointers, one to point the first element of the list, other to the last element. Each node has two pointers (forward pointer and backward pointer). The major benefit of this type of list over others is that it can traversed in both the directions forwards and backwards.


Figure - Doubly Linked List

Circular Doubly Linked List - In Circular doubly linked list the forward pointer of the last node points to the first node and the backward pointer of the first node points to the last node.


Figure - Circular Doubly Linked List




C Language

C Language Notes -

  • In a C program if a programmer assign a value to an array element whose subscript exceeds the size of the array, the program may crash. But the modern day compilers take care of this problem.
  • In C if the programmer passes an array name as an argument to a function the base address of the array will be passed.
  • (void *)0 represents a NULL pointer.
  • NULL Macro is defined in stdio.h and stddef.h header files.

Tuesday 10 July 2012

C Language


C Programming Basics



Reserved words - 

                Reserved words are keywords that identify language entities, such as statements, data types etc. and have special meaning to the compiler.

Remark - Must be used in the correct location and must be typed correctly and be used in the right context. 

C language is case sensitive and C keywords must be types fully in lowercase letters. Following are some of the keywords in C -

break, auto, do, char, const, enum, continue, default, if, double, signed, return, for, float, sizeof, int, else, switch, short, void, case, long, unsigned, union, goto, while, volatile, struct and more.

As it can be seen that all the keywords are in lowercase letters. If some uppercase letter appears then it is known as invalid keyword. For Example -  DOUBLE is an invalid keyword whereas double is a valid keyword.




Identifiers -

            Identifiers as the name itself suggests is something that is used to identify a certain entity. In Programming languages identifiers are also known as programmer defined words which are used to identify a variable, function, structure name etc.

There are certain rules that C follows for constructing identifiers such as -

  1. Identifiers can consist of the Capital letters from A to Z, lowercase letters from a to z, the digits 0 to 9 and the underscore character (_).
  2. The first character must a letter or an underscore i.e. an identifier name cannot start from a digit.
  3. There can be no embedded blanks.
  4. Reserved keywords cannot be used as identifiers.
  5. Identifiers are case sensitive i.e. Tax, tax are two different keywords.
For Example - gross_income, _grossincome, gross_income12 are valid identifiers whereas, 1gross_income, gross+income, gross income are invalid identifiers.




Encryption_Decryption in C


Key Mismatch -


Matching Key -






Code -

...... Encryption Decryption in C (logic told in another post) ........



//___ Program for Encryption and Decryption in C ___

/* Program will read the message and an encryption key (which should be of only 3 digits) and based on that key

data will be encrypted and for decryption the program will again read a number and if it is same as that of the number being inputted the first time

original message can be obtained */

/* Encrypted message in not printed but you can edit the code to watch the encrypted message */


//____ Including Header Files ___


#include<stdio.h>

#include<conio.h>

#include<string.h>

#include<stdlib.h> //__ Included for fflush(stdin) ___

char original_message[100];

int temp_variable = 0;

int encryption_message_key_scan();

int decryption_message_key_scan();

void message_encryption(char *original_message, int temp_key); //___ Function to encrypt the message ___

void message_decryption(char *original_message, int temp_key); //___ Function to decrypt the message ___

int main() //___ Main function from where the program execution starts ___
{
int temp = 0, counter = 0;



printf("\n\n\t\t__________ Encryption/Decryption in C _________\n\n");

printf("\n\n  1. Encryption will take place\n\n  2. Decryption will take place");

printf("\n\n\t Press Enter to Continue.....");

printf("\n\n________________________________________________________________________________");

while(getch() != 13)
{
}

fflush(stdin);

printf("\n\n  Encryption - ");

temp = encryption_message_key_scan();

message_encryption(original_message, temp++);

printf("\n\n________________________________________________________________________________");

printf("\n\n  Decryption - ");

temp = decryption_message_key_scan();

message_decryption(original_message, temp);

printf("\n\n  Your Message      -  ");

puts(original_message);

getch();

}

/* Function to scan the message and the encryption key based on which message will be encrypted */


int encryption_message_key_scan()
{

int encryption_key = 0;

printf("\n\n  Enter the Message -  ");

gets(original_message);

fflush(stdin);

printf("\n\n  Enter the Number  -  "); //___ Prompting the user to add the key ___

scanf("%d",&encryption_key); //__ Reading the three digit encryption key __

return encryption_key;

}

/* Function to scan the decryption key and the function return type is of integer i.e. it returns the decryption

key where the function is being called */

int decryption_message_key_scan()
{
int decryption_key = 0;

fflush(stdin);

printf("\n\n  Enter the Number  -  "); //___ Prompting the user to add the key ___

scanf("%d",&decryption_key); //__ Reading the three digit encryption key __

return decryption_key;

}

void message_encryption(char *original_message, int temp_key)
{
int encryption_key = 0, remainder = 0, first_digit = 0, last_digit = 0, string_length = 0, counter = 0;

char temp_character;

/* Counter in the while loop represents the place value

(0 place represents the ones/2 represents 100 place value) */

while(temp_key != 0)
{
remainder = temp_key % 10;

temp_key = temp_key / 10;


if(counter == 0 )
{
last_digit = remainder;
}
else if ( counter == 2)
{
first_digit = remainder;
}

counter++;
}

if (counter == 3) //___ if the number is of 3 digits then ___
{
string_length = 0; //___ String_length is used to count the number of characters in message ___

while(original_message[string_length] != '\0')

//___ Counting the number of characters in the message__

{
string_length++;
}



if (string_length%2 != 0) //__ According the algorithm if message length is odd, make it even ___
{
original_message[string_length] = 32;

original_message[string_length + 1] = '\0';

string_length++;
}

//___ Replacing the characters at the initial positions _____

temp_character = original_message[first_digit - 1];

original_message[first_digit - 1] = original_message[last_digit - 1];

original_message[last_digit - 1] = temp_character;

while((string_length >= first_digit * 2) && (string_length >= last_digit * 2))

/* The loop will continue till any of the condition is false i.e. if any of the digit is becomes greater

than message length loop will stop */
{
first_digit = first_digit * 2;

last_digit = last_digit * 2;

temp_character = original_message[first_digit - 1];

original_message[first_digit - 1] = original_message[last_digit - 1];

original_message[last_digit - 1] = temp_character;

}

counter = 0;

while(counter!= string_length) //__ Replacing the spaces will'@' __
{
if (original_message[counter] == ' ')
{
original_message[counter] = '@';
}
counter = counter + 1;
}
}
else
{
printf("\n\n\t\t __ 3 Digit Only __");
}
}

void message_decryption(char *original_message, int temp_key)
{
char temp_character;

int decryption_key = 0, string_length = 0, remainder = 0, counter = 0, previous_first = 0, previous_last = 0,last_digit = 0, first_digit = 0, original_first = 0, original_last = 0;

while(temp_key != 0)
{
remainder = temp_key % 10;

temp_key = temp_key / 10;

if (counter == 0 )
{
last_digit = remainder;
}
else if ( counter == 2)
{
first_digit = remainder;
}

counter++;
}

if (counter == 3)
{
string_length = 0;

while(original_message[string_length] != '\0')

//___ Counting the number of characters in the message__

{
string_length++;
}

original_first = first_digit;

original_last = last_digit;

counter = 0;

while(original_message[counter] != '\0') //__ Replacing '@' with space __
{
if (original_message[counter] == '@')
{
original_message[counter] = 32;
}
counter++;
}


while((first_digit <= string_length) && (last_digit <= string_length))
{
previous_first = first_digit;

previous_last = last_digit;

first_digit = first_digit * 2;

last_digit = last_digit * 2;
}

while((previous_first != original_first) && (previous_last != original_last))
{

temp_character = original_message[previous_first - 1];

original_message[previous_first - 1] = original_message[previous_last - 1];

original_message[previous_last - 1] = temp_character;

previous_first = previous_first/2;

previous_last = previous_last/2;

}

temp_character = original_message[previous_first - 1];

original_message[original_first - 1] = original_message[original_last - 1];

original_message[original_last - 1] = temp_character;

}
else
{
printf("\n\n\t\t __ 3 Digit only __");
}
}

Follow Us on - Assignment Hub

Program to hold the output till Enter Key is pressed in C


Code - 



/* Program to hold the output till Enter Key is pressed */

/* Logic - ASCII value of Enter Key is 13 and compare the input character with 13.

   If the character inputted in 13 then come out of the loop else loop continues */

//__ Including Header Files __

#include<stdio.h>

#include<conio.h>

int main()
{
printf("\n\n\t __ Program to hold the output till enter key is pressed __");

printf("\n\n\n\t\t  Press \" Enter key \" to end the Program ...");

while(getch() != 13) //__ Comparing ASCII Value ___
{
}

return 0;
}

Follow Us on Facebook - Assignment Hub

Program to compare two numbers in C++


Code -


/* Program to compare two numbers in C++ */

//__ "\n" is used for new line and "\t" for a tab (spaces) ___

//__ cin is to take the input and cout is used to dispaly the output ___

#include<iostream>

//___ Header file in C++ where the standard input/output functions are defined ___

#include<conio.h>

using namespace std;

int main()
{
int first_number = 0, second_number = 0;

cout << "\n\t\t __ Program to compare two numbers in C++ ___";

cout << "\n\n  Enter the First number  - ";

cin >> first_number;

cout << "\n\n  Enter the Second number - ";

cin >> second_number;

cout << "\n\n\n\t\t       ____  ";

if (first_number > second_number) //_ If first number is greater than second _
{
cout << first_number << " is greater than " << second_number;
}
else if (second_number > first_number) //_ If second number is greater than first _
{
cout << second_number << " is greater than " << first_number;
}
else //__ if both numbers are equal __
{
cout << first_number << " is equal to " << second_number;
}

cout << " ____";

getch();

return 0;

/*____ return 0 tells the compiler that program

has executed successfully without any error ____ */

}

Program to multiply two numbers in C++


Code -



/* Program to multiply two numbers in C++ */

//__ "\n" is used for new line and "\t" for a tab (spaces) ___

//__ cin is to take the input and cout is used to dispaly the output ___

#include<iostream>

//___ Header file in C++ where the standard input/output functions are defined ___

#include<conio.h>

using namespace std;

int main()
{
int first_number = 0, second_number = 0, multiply = 0;

cout << "\n\t\t __ Program to multiply two numbers in C++ ___";

cout << "\n\n  Enter the First number  - ";

cin >> first_number;

cout << "\n\n  Enter the Second number - ";

cin >> second_number;

multiply  = first_number * second_number;

cout << "\n\n\t\t    ___  Multiplication of " << first_number << " and " << second_number << " is " << multiply << " ____";

getch();

return 0;

/*____ return 0 tells the compiler that program

has executed successfully without any error ____ */

}