About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Wednesday, September 4, 2013

C Program to Create Your Own Header File in C Programming

Make Your Own Header File ?
Step1 : Type this Code 
int add(int a,int b)
{
return(a+b);
}
  • In this Code write only function definition as you write in General C Program
Step 2 : Save Code
  • Save Above Code with [.h ] Extension .
  • Let name of our header file be myhead [ myhead.h ]
  • Compile Code if required.
Step 3 : Write Main Program
#include
#include"myhead.h"
void main()
{
int number1=10,number2=10,number3;
number3 = add(number1,number2);
printf("Addition of Two numbers : %d",number3);
}
  1. Include Our New Header File .
  2. Instead of writing < myhead.h> use this terminology “myhead.h”
  3. All the Functions defined in the myhead.h header file are now ready for use .
  4. Directly  call function add(); [ Provide proper parameter and take care of return type ]
Note
  1. While running your program precaution to be taken : Both files [ myhead.h and sample.c ] should be in same folder.

C Program to Swap two numbers using XOR Operator

Generally Swaping two number requires three variables , Let’s Take look atProcedure of swaping two Number
For Swaping Two numbers following procedure is used -
x = x ^ y --> x^=y -- (1)
y = y ^ x --> y^=x -- (2)
x = x ^ y --> x^=y -- (3)
Now we will Explaining above three statements using example ….
Let x = 12 and y = 9 [ For our sake and simplicity consider number is of 4 bits ]
x = 1100
y = 1001

X-OR Table :
  A   B  A X-OR B
110
101
011
000
Step 1 : After : x = x ^ y
x   = 1100
y   = 1001
----------
x^y = 0101
----------
x   = 0101    ..... New Value of x
Step 2 : After y = y ^ x
x   = 0101    ..... New Value is taken
y   = 1001    ..... Old Value of Y
----------
y^x = 1100
----------
y   = 1100    ..... New Value of y = Initial x
Step 3 : After x = x ^ y
x   = 0101    ..... New Value from step 1
y   = 1100    ..... New Value of y from Step 2
----------
y^x = 1001
----------
x   = 1001    ..... New Value of x = Initial y
Here is Program for : [Swap / Interchange two variables [numbers] without using Third Variable]
#include
#include
void main()
{
int num1,num2;

printf("\nEnter First Number : ");
scanf("%d",&num1);

printf("\nEnter Second Number : ");
scanf("%d",&num2);

num1 = num1 ^ num2;
num2 = num1 ^ num2;
num1 = num1 ^ num2;

printf("\nNumbers after Exchange : ");
printf("num1 = %d and num2 = %d",num1,num2);

getch();
}
Output :
Enter First Number : 20
Enter Second Number : 40

Numbers after Exchange : num1 = 40 and num2 = 20

C Program to Demonstrate Nested Printf Statements

nested Printf statements : Example 1

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%d",printf("abcdefghijklmnopqrstuvwxyz"));
getch();
}

Output :
abcdefghijklmnopqrstuvwxyz26

How ?
  1. “abcdefghijklmnopqrstuvwxyz” will be first Printed while executing inner printf
  2. Total Length of the “abcdefghijklmnopqrstuvwxyz” is 26
  3. So printf will return total length of string
  4. It returns 26 to outer printf
  5. This outer printf will print 26

C Program to Demonstrate Printf inside Another Printf Statement

Printf inside printf in C : Example 1

#include
#include
void main()
{
int num=1342;
clrscr();
printf("%d",printf("%d",printf("%d",num)));
getch();
}

Output :
134241

How ?
  1. Firstly Inner printf is executed which results in printing 1324 
  2. This Printf Returns total number of Digits i.e  4 and second inner printf will looks like
  3. printf("%d",printf("%d",4));
  4. It prints 4 and Returns the total number of digits i.e 1 (4 is single digit number )
  5. printf("%d",1);
  6. It prints simply 1 and output will looks like 132441

Rule :
Inner printf returns Length of string printed on screen to the outer printf

C Program to Print Hello word without using semicolon

Part 1 : Printf Hello word in C without using semicolon [only ones ]

#include
void main()
{
   if(printf("Hello"))
   {
   }
}

Output :
Hello

Part 2 : Printf Hello word in C without using semicolon [infinite times]

#include
void main()
{
   while(printf("Hello"))
   {
   }
}

Part 3 : Printf Hello [Using Switch]

#include
void main()
{
   switch(printf("Hello"))
   {
   }
}

Part 4 : Using Else-if Ladder

#include
void main()
{
   if(printf(""))
      {
      }
   else if (printf("Hello"))
      {
      }
   else
      {
      }
}

Part 5 : Printf Hello [Using While and Not]

#include
void main()
{
    while(!printf("Hello"))
    {
    }
}

Part 6 : Using #define

#include
#define PRINT printf("Hello")
void main()
{
    if(PRINT)
    {
    }
}

C Program to Accept Paragraph using scanf

Accept Paragraph using scanf in C
#include
void main()
{
char para[100];
printf("Enter Paragraph : ");
scanf("%[^t]",para);
printf("%s",para);
}

Output :[Press Tab to Stop Accepting Characters ]
Enter Paragraph : C Programming is very easy to understand
C
Language
is backbone of
C++
Language

How ?
scanf("%[^t]",para);
  1. Here scanf will accept Characters entered with spaces.
  2. It also accepts the Words , new line characters .
  3. [^t]  represent that all characters are accepted except tab(t) ,whenever t will encountered then the process of accepting characters will be terminated.
Drawbacks :
  1. Paragraph Size cannot be estimated at Compile Time
  2. It’s vulnerable to buffer overflows.
How to Specify Maximum Size to Avoid Overflow ?
//------------------------------------
// Accepts only 100 Characters
//------------------------------------
scanf("%100[^t]",para);

C Program to Input Password for Validation of User name

How to Input Password in C ?
#include< stdio.h>
#include< conio.h>

void main()
{
char password[25],ch;
int i;

clrscr();
puts("Enter password : ");

while(1)
    {
    if(i<0)
         i=0;
    ch=getch();

    if(ch==13)
        break;

    if(ch==8) /*ASCII value of BACKSPACE*/
        {
        putch('b');
        putch(NULL);
        putch('b');
        i--;
        continue;
        }

   password[i++]=ch;
   ch='*';
   putch(ch);
   }

password[i]='';
printf("\nPassword Entered : %s",password);
getch();
}
Output :
Enter password : ******
Password Entered : rakesh

Explain ?
ch=getch();
  • Accept Character without Echo [ without displaying on Screen ]
  • getch will accept character and store it in “ch”
if(ch==13)
        break;
  • ASCII Value of “Enter Key” is 13
  • Stop Accepting Password Characters after “Enter” Key.
if(ch==8) /*ASCII value of BACKSPACE*/
        {
        putch('b');
        putch(NULL);
        putch('b');
        i--;
        continue;
        }
  • ASCII Value of “BACKSPACE” is 8
  • After hitting “backspace”following actions should be carried out -
    • Cursor Should be moved 1 character back.
    • Overwrite that character by “NULL”.
    • After Writing NULL again cursor is moved 1 character ahead so again move cursor 1 character back .
    • Decrement Current Track of Character. [i]
password[i++]=ch;
   ch='*';
  • Store Accepted Character in String array .
  • Instead of Displaying Character , display Asterisk (*)

C Program to Write inline assembly language code in C Program

Add Two Numbers Using Inline Assembly Language ???
#include<stdio.h>
void main()
{
int a=3,b=3,c;

   asm {
       mov ax,a
       mov bx,a
       add ax,bx
       mov c,ax
      }

printf("%d",c);
}

  1. Assembly Language can be Written in C .
  2. C Supports Assembly as well as Higher Language Features so called“Middle Level Language”.
  3. As shown in above Program , “asm” Keyword is written to indicate that“next followed instruction is from Assembly Language”.
asm mov ax,a
  1. Opening Curly brace after “asm” keyword tells that it is the “Start of Multiple Line Assembly Statements”  i.e “We want to Write Multiple Instructions”
  2. Above Program Without “Opening and Closing Brace” can be written as – ["asm" keyword before every Instruction ]
asm mov ax,a
asm mov bx,a
asm add ax,bx
asm mov c,ax

What above Program Actually Does ?
  1. In 8086 Assembly Program for Storing Values AX,BX,CX,DX registers are used called General Purpose Registers .
asm mov ax,a
  1. Move Instruction Copies content of Variable “a” into Register “AX”
  2. Add Instruction adds Content of two specified Registers and Stores Result in “ax” in above example.
  3. Copy Result into Variable “c”

C Program to Swap two no’s without using third variable

#include<stdio.h>
#include<conio.h>

void main()
{
int a,b;

clrscr();

printf("\nEnter value for num1 & num2 : ");
scanf("%d %d",&a,&b);

a=a+b;
b=a-b;
a=a-b;

printf("\nAfter swapping value of a : %d",a);
printf("\nAfter swapping value of b : %d",b);

getch();
}
Output :
Enter value for num1 & num2 : 10 20

After swapping value of a : 20
After swapping value of b : 10

C Program to Sort Structures on the basis of Structure Element

Sorting Two Structures on the basis of any structure element and Display Information

Program Statement – Define a structure called cricket that will describe the following information
  1. Player name
  2. Team name
  3. Batting average
Using cricket, declare an array player with 10 elements and write a program to read the information about all the 10 players and print a team wise list containing names of players with their batting average.
#include<stdio.h>

struct cricket
{
char pname[20];
char tname[20];
int avg;
}player[10],temp;

void main(){
  int i,j,n;
  clrscr();

 for(i=0;i<10;i++)
  {
  printf("\nEnter Player Name : ");
  scanf("%s",player[i].pname);
  printf("\nEnter Team Name : ");
  scanf("%s",player[i].tname);
  printf("\nEnter Average : ");
  scanf("%d",&player[i].avg);
  printf("\n");
  }
  n=10;

  for(i=1;i< n;i++)
      for(j=0;j< n-i;j++){
           if(strcmp(player[j].tname,player[j+1].tname)>0)
           {
              temp = player[j];
              player[j] = player[j+1];
              player[j+1] = temp;
           }
      }

  for(i=0;i< n;i++)
      printf("\n%s\t%s\t%d",player[i].pname,player[i].tname,player[i].avg);
  getch();
}
Output :
Enter Player Name : Sehwag
Enter Team Name : India
Enter Average : 78

Enter Player Name : Ponting
Enter Team Name : Australia
Enter Average : 65

Enter Player Name : Lara
Enter Team Name : WI
Enter Average : 67

Ponting Australia  65
Sehwag  India      78
Lara    WI         67

Explanation of C Program :

Step 1 : Accept Data

for(i=0;i<10;i++)
  {
  printf("\nEnter Player Name : ");
  scanf("%s",player[i].pname);
  printf("\nEnter Team Name : ");
  scanf("%s",player[i].tname);
  printf("\nEnter Average : ");
  scanf("%d",&player[i].avg);
  printf("\n");
  }

Step 2 : Sorting two Structures

if(strcmp(player[j].tname,player[j+1].tname)>0)
     {
       temp = player[j];
       player[j] = player[j+1];
       player[j+1] = temp;
     }

C Program to Calculate Size of Structure using Sizeof Operator

#include<stdio.h>
#include<conio.h>
struct stud
{
int roll;
char name[10];
int marks;
};

void main()
{
int size;
struct stud s;
clrscr();
size = sizeof(s);
printf("\nSize of Structure : %d",size);
getch();
}

Explanation :

  1. Structure is Collection of elements of the Different data Types.
  2. Size of the Structure Can be Evaluated using “sizeof Operator”
size = sizeof(s);

Formula for Calculating Size of Structure :

Size of Structure 'S' = sizeof(roll) + sizeof(name) + sizeof(mark)
                      = 2 + 10 + 2
                      = 14
Remember :
  • Sizeof is Operator not function
  • Sizeof Operator Takes any Variable as Parameter.

C program to Use structure within union & display the contents of structure elements

Problem Statement :Create one Structure and declare it inside union.Then accept values for structure members and display them.

Write a program to use structure within union , display the contents of structure elements

#include<stdio.h>
#include<conio.h>

void main()
{
  struct student
    {
     char name[30];
     char sex;
     int rollno;
     float percentage;
    };

    union details
     {
     struct student st;
     };
     union details set;

clrscr();
printf("Enter details:");
printf("\nEnter name : ");
scanf("%s", set.st.name);

printf("\nEnter rollno: ");
scanf("%d", &set.st.rollno);

flushall();

printf("\nEnter sex: ");
scanf("%c",&set.st.sex);

printf("\nEnter percentage: ");
scanf("%f",&set.st.percentage);

printf("\nThe student details are:n");
printf("Name : %s", set.st.name);
printf("\nRollno : %d", set.st.rollno);
printf("\nSex : %c", set.st.sex);
printf("\nPercentage : %f", set.st.percentage);

getch();
}
Output :
Enter details:
Enter name : Pritesh
Enter rollno: 10
Enter sex: M
Enter percentage: 89

The student details are:
Name : Pritesh
Rollno : 10
Sex : M
Percentage : 89.000000