Search This Blog

Wednesday, February 13, 2013

QUIZ

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
void showrecord(void);
void resetscr()
{float sc;
    char nm[20];
    FILE *f;
    f=fopen("score.txt","r+");
    fscanf(f,"%s%f",&nm,&sc);
    sc=0;
    fprintf(f,"%s,%5.2f",nm,sc);
    fclose(f);
}
void help()
    {
    printf("HELP");
    printf("\n\n\n\tThis test \"AAJMA LUCK\" is a game of luck and knowledge. You'll be asked");
    printf("\n\n\tsome I.Q.questions with 4 options and the right answer is to be chosen ");
    printf("\n\n\tamong them.you will be asked until you give incorrect answer.Your score ");
    printf("\n\n\twill be calculated at end and displayed. If you secure highest score, ");
    printf("\n\n\tyour score will be recorded and you will be awardedaccordlingly.");
    printf("\n\n\t*********************BEST OF LUCK*********************************");
    }
void editscore(float score, char plnm[20])
    {
    float sc;
    char nm[20];
    FILE *f;
    f=fopen("score.txt","r");
    fscanf(f,"%s%f",&nm,&sc);
    if (score>=sc)
      { sc=score;
        fclose(f);
        f=fopen("score.txt","w");
        fprintf(f,"%s\n%.2f",plnm,sc);
        fclose(f);
      }
    }
int main()
     {
     int countr;
     int r,i,n;
        float score;
     char choice;
     char playername[20];
     mainhome:
     printf("\n\n\n\n\t\t\t  W   L   O   E  T \n");
     printf("\t\t\t    E   C   M      O");
     printf("\n\n\n\t\t\t     AAJMA LUCK \n\n") ;
     printf("\n\t\t********************************");
     printf("\n\n\n\t\t # press 'S' to start the test       ");
     printf("\n\t\t # press 'V' to view high score  ");
     printf("\n\t\t # press 'R' to reset score");
     printf("\n\t\t # press 'H' for help            ");
     printf("\n\t\t # press 'Q' to quit             ");
     printf("\n\n\n\t\t********************************\n\n\t\t  ");
     choice=toupper(getch());
     if (choice=='V')
    {
    showrecord();
    goto mainhome;
    }
     else if (choice=='Q')
    exit(1);
     else if (choice=='H')
    {
    help();
    getch();
    goto mainhome;
    }
    else if (choice=='R')
    {resetscr();
    getch();
    goto mainhome;}
    else if(choice=='S'){


     printf("\n\n\n\t\t\tEnter your name...");
     gets(playername);

     home:
     countr=0;
     i=1;
     start:
     r=rand()%24;

     switch(r)
        {
        case 1:
        printf("\n\nSome months have 30 days, some months have 31 days. How many months have 28 days?");
        printf("\n\nA.4\tB.3\n\nC.1\tD.none\n\n");
        if (toupper(getch())=='C')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is C.1");

               break;}getch();
               goto go;

        case 2:
        printf("\n\n\nIf a doctor gives you 3 pills and tells you to take one pill every half hour,");
        printf(" how long would it be before all the pills had been taken?");
        printf("\n\nA.4\tB.1 and half\n\nC.3\tD.1\n\n");
        if (toupper(getch())=='D')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               printf("\n\nWrong!!! The correct answer is D.1");getch();
               goto go;
        break;

        case 3:
        printf("\n\n\nDivide 30 by half and add ten. What do you get? ");
        printf("\n\nA.25\tB.40\n\nC.30\tD.70\n\n");
        if (toupper(getch())=='D')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is D.70");getch();
               goto go;break;}


        case 4:
        printf("\n\n\nA farmer had 17 sheep. All but 9 died. How many live sheep were left?");
        printf("\n\nA.9\tB.17\n\nC.8\tD.0\n\n");
        if (toupper(getch())=='A')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is A.9");getch();
               goto go;break;}


        case 5:
        printf("\n\n\nTake 2 apples from 3 apples. What do you have? ");
        printf("\n\nA.1\tB.3\n\nC.2\tD.5\n\n");
        if (toupper(getch())=='C')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is C.2");
               getch();
               goto go;
               break;}

        case 6:
        printf("\n\n\nWhich syllabe is stressed in the word 'democracy'?");
        printf("\n\nA.1st\tB.2nd\n\nC.3rd\tD.4th\n\n");
        if (toupper(getch())=='B' )
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is B.2nd");getch();
               goto go;break;}


        case 7:
        printf("\n\n\nWhich country was the winner of Cricket World Cup 2011?");
        printf("\n\nA.Sri Lanka\tB.India\n\nC.Australia\tD.Pakistan\n\n");
        if (toupper(getch())=='B')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is B.India");getch();
               goto go;break;}


        case 8:
        printf("\n\n\nWhat is the height of Mount everest in meter?");
        printf("\n\nA.8648\tB.6648\n\nC.8884\tD.8848\n\n");
        if (toupper(getch())=='D')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is D.8848");getch();
               goto go;break;}


        case 9:
        printf("\n\n\nWhat is the capital of Denmark?");
        printf("\n\nA.Copenhagen\tB.Helsinki\n\nC.Rome\t\tD.Madrid\n\n");
        if (toupper(getch())=='A')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is A.Copenhagen");getch();
               goto go;break;}


        case 10:
        printf("\n\n\nWhich syllabe is stressed in the word 'instanteneous'?");
        printf("\n\nA.1st\tB.2nd\n\nC.3rd\tD.4th\n\n");
        if (toupper(getch())=='C')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is C.3rd");getch();
               goto go;break;}


        case 11:
        printf("\n\n\nWho was the only player to score 6 successive sixes in an over?");
        printf("\n\nA.Adam Gilchrist\tB.M.S.Dhoni\n\nC.Herschel Gibbs\tD.Sanath Jayasurya\n\n");
        if (toupper(getch())=='C')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is C.Herschel Gibbs");getch();
               goto go;break;}

        case 12:
        printf("\n\n\nWho was the only player to take 4 successive wickets?");
        printf("\n\nA.Malinga Bandara\tB.Lasith Malinga\n\nC.Bret Lee\tD.Murali Daran\n\n");
        if (toupper(getch())=='B')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is B.Lasith Malinga");getch();
               goto go;break;}

        case 13:
        printf("\n\n\nWhich country is hosting the Fifa World Cup 2010?");
        printf("\n\nA.South Africa\tB.Italy\n\nC.Argentina\tD.Spain\n\n");
        if (toupper(getch())=='A')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is A.South Africa");getch();
               goto go;break;}

        case 14:
        printf("\n\n\nWho is the author of 'Pulpasa Cafe'?");
        printf("\n\nA.Narayan Wagle\tB.Lal Gopal Subedi\n\nC.B.P. Koirala\tD.Khagendra Sangraula\n\n");
        if (toupper(getch())=='A')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is A.Narayan Wagle");getch();
               goto go;break;}

        case 15:
        printf("\n\n\nWhich country is Maria Sarapova from?");
        printf("\n\nA.Russia\tB.Switzerland\n\nC.Argentina\tD.Spain\n\n");
        if (toupper(getch())=='A')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is A.Russia");getch();
               goto go;break;}

        case 16:
        printf("\n\n\nWho was awarded the youngest player award in Fifa World Cup 2006?");
        printf("\n\nA.Wayne Rooney\tB.Lucas Podolski\n\nC.Lionel Messi\tD.Christiano Ronaldo\n\n");
        if (toupper(getch())=='B')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is B.Lucas Podolski");getch();
               goto go;break;}


        case 17:
        printf("\n\n\nWhat is the smallest district of Nepal?");
        printf("\n\nA.Lalitpur\tB.Kalikot\n\nC.Bhaktapur\tD.Gulmi\n\n");
        if (toupper(getch())=='C')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is C.Bhaktapur");getch();
               goto go;break;}

        case 18:
        printf("\n\n\nWhat is the headquarter of Western Development Region?");
        printf("\n\nA.Dhankuta\tB.birendranagar\n\nC.Dhangadhi\tD.Pokhara\n\n");
        if (toupper(getch())=='D')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is D.Pokhara");getch();
               goto go;break;}

        case 19:
        printf("\n\n\nWhich place is called 'The Cherrapunji of Nepal'?");
        printf("\n\nA.Dharan\tB.Kathmandu\n\nC.Pokhara\tD.Butwal\n\n");
        if (toupper(getch())=='C')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is C.Pokhara");getch();
               goto go;break;}

        case 20:
        printf("\n\n\nWhich city is known at 'The City of Seven Hills'?");
        printf("\n\nA.Rome\tB.Vactican City\n\nC.Madrid\tD.Berlin\n\n");
        if (toupper(getch())=='A')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is A.Rome");getch();
               goto go;break;}

        case 21:
        printf("\n\n\nWho was the F1 racing champion of 2006?");
        printf("\n\nA.Louis Hamilton\tB.Felipe Massa\n\nC.Fernando Alonso\tD.Michael Schumaker\n\n");
        if (toupper(getch())=='C')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is C.Fernanda Alonso");getch();
               goto go;break;}

        case 22:
        printf("\n\n\nWho won the Women Australian Open 2007?");
        printf("\n\nA.Martina Hingis\tB.Maria Sarapova\n\nC.Kim Clijster\tD.Serena Williams\n\n");
        if (toupper(getch())=='D')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is D.Serena Williams");getch();
               goto go;break;}

        case 23:
        printf("\n\n\nName the country where there no mosquito is found?");
        printf("\n\nA.Germany\tB.Spain\n\nC.Japan\tD.France\n\n");
        if (toupper(getch())=='D')
            {printf("\n\nCorrect!!!");countr++; break;}
        else
               {printf("\n\nWrong!!! The correct answer is D.France");getch();
               goto go;break;}



        }
    i++;
    if (i<=10) goto start;
    else
    score=(float)countr/10*100;
    score:
    score=(float)countr/10*100;
    printf("\n\n\nYour Score: %.2f",score);
    if (score==100) printf("\n\nCONGRATULATIONS...YOU WON THE FIRST PRIZE");
    else if (score>=80 && score<100) printf("\n\nVERY GOOD!!");
    else if (score>=60 &&score<80) printf("\n\nGOOD! BUT YOU NEED TO KNOW MORE.");
    else if (score>=40 && score<60) printf("\n\nSATISFACTORY RESULT, BUT THIS MUCH IS MUCH SUFFICIENT.");
    else printf("\n\nYOU ARE VERY POOR IN I.Q.,WORK HARD");
    puts("\n\nNEXT PLAY?(Y/N)");
    if (toupper(getch())=='Y')
        goto home;
    else
        {
        editscore(score,playername);
        goto mainhome;
        }
    }
     else
    {
    printf("\n\n\t\t  Invalid Entry\n\n\t\t  ");

    goto mainhome;
    }
    go:
    goto score;

      }
void showrecord()
    {
    char name[20];
    float s;
    FILE *f;
    f=fopen("score.txt","r");
    fscanf(f,"%s%f",&name,&s);
    printf("\n\n\t\t***********************************************");
    printf("\n\n\t\t %s has secured the Highest Score %.2f",name,s);
    printf("\n\n\t\t***********************************************");
    fclose(f);
    getch();
    }

Saturday, May 26, 2012

C Coding

Multiplication of two matrices

#include<stdio.h>
#include<conio.h>
int main(){
  int a[5][5],b[5][5],c[5][5],i,j,k,sum=0,m,n,o,p;
  printf("\nEnter the row and column of first matrix");
  scanf("%d %d",&m,&n);
  printf("\nEnter the row and column of second matrix");
  scanf("%d %d",&o,&p);
  if(n!=o){
      printf("Matrix mutiplication is not possible");
      printf("\nColumn of first matrix must be same as row of second matrix");
  }
  else{
      printf("\nEnter the First matrix->");
      for(i=0;i<m;i++)
      for(j=0;j<n;j++)
           scanf("%d",&a[i][j]);
      printf("\nEnter the Second matrix->");
      for(i=0;i<o;i++)
      for(j=0;j<p;j++)
           scanf("%d",&b[i][j]);
      printf("\nThe First matrix is\n");
      for(i=0;i<m;i++){
      printf("\n");
      for(j=0;j<n;j++){
           printf("%d\t",a[i][j]);
      }
      }
      printf("\nThe Second matrix is\n");
      for(i=0;i<o;i++){
      printf("\n");
      for(j=0;j<p;j++){
           printf("%d\t",b[i][j]);
      }
      }
      for(i=0;i<m;i++)
      for(j=0;j<p;j++)
           c[i][j]=0;
      for(i=0;i<m;i++){ //row of first matrix
      for(j=0;j<p;j++){  //column of second matrix
           sum=0;
           for(k=0;k<n;k++)
               sum=sum+a[i][k]*b[k][j];
           c[i][j]=sum;
      }
      }
  }
  printf("\nThe multiplication of two matrix is\n");
  for(i=0;i<m;i++){
      printf("\n");
      for(j=0;j<p;j++){
           printf("%d\t",c[i][j]);
      }
  }
  getch();
  return 0;
}


TO DELETE "THREE", "BAD" AND "TIME"


#include<stdio.h>
#include<string.h>
int main( )
{
char str[20];
FILE *ptvar1, *ptvar2;
ptvar1=fopen("data1.txt","r");
ptvar2=fopen("data2.txt","w");
while(!feof(ptvar1))
{
fscanf(ptvar1,"%s",str);
if(strcmp(str, "three")==0 || strcmp(str, "bad")==0 || strcmp(str, "time")==0);
continue;
else
fprintf(ptvar2,"%s",str);
}
fclose(ptvar1);
fclose(ptvar2);
return 0;
}

(*the alignments are not proper, please standardize the alignment to run the program)

TO COPY A FILE


#include <stdio.h>
#include <stdlib.h>

main()
{
char ch, source_file[20], target_file[20];
FILE *fp1, *fp2;

printf("Enter name of file to copy\n");
gets(source_file);

fp1 = fopen(source_file, "r");

if( fp1 == NULL )
{
printf("Error\n");
}

printf("Enter name of target file\n");
gets(target_file);

fp2= fopen(target_file, "w");

if( fp2 == NULL )
{
fclose(fp1);
printf("Error\n");
}

while( ( ch = fgetc(fp1) ) != EOF )
fputc(ch, fp2);

printf("File copied successfully.\n");

fclose(fp1);
fclose(fp2);

return 0;
}


To calculate the sum, difference, product, quotient and remainder

#include<stdio.h>
#include<conio.h>
void main()
{ int a,b,sum,dif,pro,q,r;
clrscr();
printf("input enter a first greater number ",a);
scanf("%d",&a);
printf("input enter a second smanller number ",b);
scanf("%d",&b);
sum=a+b;
dif=a-b;
pro=a*b;
q=a/b;
r=a%b;
printf("sum of two no= %d",sum);
printf("\ndiffferenceoftwo no= %d",dif);
printf("\nproductoftwo no= %d",pro);
printf("\nquotientoftwo no= %d",q);
printf("\nremainder of two no= %d",r);
getch();
}


To input any two numbers and finding out the greater one

#include<stdio.h>
#include<conio.h>
void main()
{ int num1, num2;
clrscr();
printf(“Enter the first and second number:\n”);
scanf(“%d%d”, &num1, &num2);
if(num1>num2)
printf(“\n%d is greater than %d”, num1, num2);
else
printf(“\n%d is greater than %d”, num2, num1);
getch();
}

To find out whether the number is odd or even

#include<stdio.h>
#include<conio.h>
void main()
{ int num;
clrscr();
printf(“Enter any number:\n”);
scanf(“%d”,&num);
if((num%2)==0)
printf(“\nThe given number is even”);
else
printf(“\nThe given number is odd”);
getch();
}

To generate the multiplication table

#include<stdio.h>
#include<conio.h>
void main()
{ int i, num;
clrscr();
printf(“Enter any number:”);
scanf(“%d”,&num);
for(i=1;i<=10;i++)
printf(“%d X %d = %d”,num,i,num*i);
getch();\
}


To calculate the percentage and division of a student

#include(stdio.h)
#include(conio.h)
void main()
{ float marks, per;
printf("\nEnter the total marks:");
scanf("%d,&marks);
per=marks/5;
if(per>=80)
{ printf("distinction"); }
else if(per>=60 && per<80)
{ printf("\n first division"); }
else if(per>=50 &&per<60)
{ printf("\nsecond division"); }
else if(per>=40 &&per<50)
{ printf("\n pass division"); }
else
{ printf("\n fail"); }
printf("\nThe percentage is %f",per);
getch();
}

To calculate the area and perimeter of a rectangle

#include<stdio.h>
#include<conio.h>
void main()
{ float l,b,area,perimeter;
printf("Enter length and breadth of rectangle");
scanf("%f%f",&l,&b);
area=l*b;
perimeter=2*(l+b);
printf("\nThe area of rectangle is %f\nThe perimeter of rectangle is
%f",area,perimeter);
getch();
}

To swap the values

#include<conio.h>
#include<stdio.h>
void main()
{ int temp, num1, num2;
clrscr();
printf(“Enter two numbers:\n”);
scanf(“%d%d”,&num1,&num2);
printf(“The given numbers are %d and %d”,num1,num2);
temp=num1;
num1=num2;
num2=temp;
printf(“The numbers after swapping are %d and %d”,num1,num2);
getch();
}

To swap the numbers using bubble sort method

#include<stdio.h>
#include<conio.h>
void main()
{ int i,j,n,temp;
intnum[]={4,9,3,7,1,8,6};
n=7;
clrscr();
for(i=0;i<n;i++)
{ for(j=0;j<n-1;j++)
{ if(num[j]>=num[j+1])
{ temp=num[j];
num[j]=num[j+1];
num[j+1]=temp;
}
}
}
for(i=0;i<n;i++)
printf(“%d\t”,num[i]);
getch();
}

To swap the numbers using selection sort method

#include<stdio.h>
#include<conio.h>
void main()
{ int i,j,n,p,temp,s=0;
intnum[]={4,9,3,7,1,8,6};
n=7;
clrscr();
for(i=0;i<n-1;i++)
{ s=num[i];
for(j=i;j<n;j++)
{ if(num[j]<=s)
{ s=num[j];
p=j;
}
}
temp=num[i];
num[i]=s;
num[p]=temp;
}
for(i=0;i<n;i++)
printf(“%d\t”,num[i]);
getch();
}


To arrange numbers in ascending order

#include<stdio.h>
#include<conio.h>
void main()
{ int i,k,int x[10],temp;
clrscr();
printf("\n Enter the numbers:\n");
for(i=0;i<10;i++)
scanf("%d",&x[i]);
for(i=0;i<10;i++)
{ for(k=0;k<10;k++)
{ if(x[k]>x[k+1])
{ temp=x[k];
x[k]=x[k+1];
x[k+1]=temp;
}
}
}
printf("\nThe numbers in ascending order are:\n”);
for(i=0;i<10;i++)
printf(“%d\t",x[i]);
getch();
}

To find HCF

#include<stdio.h>
#include<conio.h>
void main()
{ int num1,num2,temp;
printf("Enter two numbers:\n");
scanf("%d%d",&num1,&num2);
while(num2!=0)
{ temp=num1%num2;
num1=num2;
num2=temp;
}
printf("\nHCF is %d",num1);
getch();
}

To find the factorial of given number

#include<stdio.h>
#include<conio.h>
void main()
{ int n,i;
longint fact;
clrscr();
fact=1;
printf("enter the number");
scanf("%d", &n);
for(i=1; i<=n; i++)
fact=fact*i;
printf("The factorial of %d is %d", n,fact);
getch();
}

To find the Fibonacci series of given number

#include<stdio.h>
#include<conio.h>
void main()
{ clrscr();
int n, i=0, j=1, k , a;
printf("Enter the number:");
scanf("%d", &n);
printf("\nfibonacci series is 0 1");
for(a=3; a<=n; a++)
{ k=i+j;
i=j;
j=k;
printf("\t %d", k);
}
getch();
}

To reverse the user input integer

#include<stdio.h>
#include<conio.h>
void main()
{ int num, rem, temp=0;
clrscr();
printf(“Enter any number:\n”);
scanf(“%d”,&num);
while(num!=0)
{ rem=num%10;
temp=(temp*10)+rem;
num=num/10;
}
printf(“The reversed number is %d”,temp);
getch();
}

 To reverse the user input string

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{ char string1[20], temp;
int len,i,j;
clrscr();
printf(“Enter the string”);
scanf(“%s”,string1);
len=strlen(string1);
for(i=0,j=len-1;i<len,j>(len-1)/2;i++,j--)
{ temp=string1[i];
string1[i]=string1[j];
string1[j]=temp;
}
printf(“The reversed string is %s”,string1);
getch();
}

 To calculate the sum of two 2X2 matrices

#include<stdio.h>
#include<conio.h>
void main()
{ int a[2][2],b[2][2],c[2][2],i,j;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{ printf("Enter the number"); scanf("%d",&a[i][j]);
}
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf("%d\t",a[i][j]); printf("\n");
}
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{ printf("Enter the number"); scanf("%d",&b[i][j]);
}
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf("%d\t",b[i][j]); printf("\n");
}
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
{ c[i][j]=a[i][j]+b[i][j];
}
}
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf("%d\t",c[i][j]); printf("\n\n");
}
getch();
}

To multiply two 2X2 matrices

#include<stdio.h>
#include<conio.h>
void main()
{ int a[2][2],b[2][2],c[2][2],i,j,k;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{ printf("Enter the number of matrix a");
scanf("%d",&a[i][j]);
}
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
printf("\n"); }
printf("\n\n");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{ printf("Enter the number of matrix b");
scanf("%d",&b[i][j]);
}
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf("%d\t",b[i][j]);
printf("\n"); }
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
{ c[i][j]=0;
for(k=0;k<2;k++)
{ c[i][j]=(c[i][j]+(a[i][k]*b[k][j]));
}
}
}
}
}
printf("\n\n");
printf("\nThe multiplication of matrix a and matrix b is:\n");
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
getch();
}

To find the power of user input number

#include<stdio.h>
#include<conio.h>
int power(int,int);
void main()
{ int n,p;
clrscr();
printf("enter the base number");
scanf("%d",&n);
printf("Enter the power number");
scanf("%d",&p);
printf("\n%d^%d is %d\n",n,p,power(n,p));
getch();
}
int power(intn,int p)
{ int i;
int c=n;
for(i=1;i<p;i++)
n=n*c;
return n;
}

 To display the user input sentences removing all the spaces

#include<stdio.h>
#include<conio.h>
void main()
{ char line[50],c;
int i=0;
printf(“Enter the sentence:\n”);
gets(line);
while((c=(line[i++]))!=‘.’)
{ if(c==‘ ’)
continue;
else
printf(“%c”,c);
}
printf(“.”);
getch();
}

To count the number of words in a sentence

#include<stdio.h>
#include<conio.h>
void main()
{ char line[80],c;
int i=0,j=1;
printf(“Enter the sentence:”);
gets(line);
while((c=(line[i++]))!=‘.’)
{ if(c==‘ ’)
j=j+1;
}
printf(“\n%d”,j);
getch();
}

Use of pointer passing by reference

#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
{ int a=6,b=10;
swap(&a,&b);
printf("The values after swapping are a=%d,b=%d",a,b);
getch();
}
void swap(int*a,int*b)
{ int *temp;
*temp=*a;
*a=*b;
*b=*temp;
}

Use of pointer passing by value

#include<stdio.h>
#include<conio.h>
void swap(int,int);
void main()
{ int a=6,b=10;
swap(a,b);
getch();
}
void swap(inta,int b)
{ int temp;
temp=a;
a=b;
b=temp;
printf("The value after swapping are a=%d and b=%d",a,b);
}

To enter the details of a book and display it using structure

#include<stdio.h>
#include<conio.h>
void main()
{ struct book
{ charbookname[1];
char author[1];
char publisher[1];
intrate,page;
};
int i;
struct book b1[1];
for(i=0;i<1;i++)
{ printf("\nenter the bookname:");
scanf("%s",b1[i].bookname);
printf("\nenter the author name");
scanf("%s",b1[i].author);
printf("\nenter the publisher name");
scanf("%s",b1[i].publisher);
printf("\nenter the rate");
scanf("%d",&b1[i].rate);
printf("\nenter the page no");
scanf("%d",&b1[i].page);
}
printf("\nbookname\tauthorname\tpublishername\trate\tpageno.");
for(i=0;i<1;i++)
printf("\n%s\t\t%s\t\t%s\t\t%d\t%d\t",b1[i].bookname,b1[i].author,b1[i].publ
isher,b1[i].rate,b1[i].page);
getch();
}

To enter the detail of a person and store the record in a file

#include<stdio.h>
void main()
{ FILE *file;
file=fopen(“abc.txt”, “a+”);
char name[15], add[15];
//reading the file
while(!feof(file))
{ fscanf(file, “\n%s”,name);
printf(“\n%s”,name);
fscanf(file,”\t\t%s”,add);
printf(“\t\t%s”,add);
}
// ading new record
printf(“\n\n Enter name”\n”);
scanf(“%s”,name);
fprintf(file,”\n%s”,name);
printf(“\n Enter addres:\n”);
scanf(“%s”,add);
fprintf(file,”\t\t%s”,add);
fclose(file);
}

To draw a line

#include<stdio.h>
#include<graphics.h>
void main()
{ int gd=DETECT,gm; initgraph(&gd,&gm,”c:\\tc\\bgi”);
line(200,100,150,300);
setcolor(WHITE);
getch();
closegraph();
}


To draw a Circle

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{ int gd=DETECT,gm;
initgraph(&gd,&gm,”c:\\tc\\bgi”);
circle(200,200,100);
setcolor(WHITE);
getch();
closegraph();
}

To draw a rectangle

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{ int gd=DETECT,gm;
initgraph(&gd,&gm,”c:\\tc\\bgi”);
rectangle(200,100,150,300);
setcolor(WHITE);
getch();
closegraph();
}

To draw a triangle

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{ int gd=DETECT,gm;
initgraph(&gd,&gm,”c:\\tc\\bgi”);
line(200,100,200,300);
line(200,100,400,300);
line(200,300,400,300);
setcolor(WHITE);
getch();
closegraph();
}



MORE………………..



Switch case statement


 Switch case statement

The switch-case  statement is a multi way decision that tests whether an expression matches one of the number of constant expression and branches accordingly. switch case statements are a substitute for long if statements. The basic format for using switch case is outlined below.
Switch (expression or variable)               
{               
 case constant-expr1:          
   statement sequence;         
  break;       
 case constant-expr2:          
   statement sequence;
  break;               
 case : constant-expr3: 
  statement sequence;
  break;       
  ...          
 default:              
  statement sequence;  
}
The expression or variable has a value. The case says that if the expression or variable has value which  is after that cases then execute the statements that  follows the colon until the break is reached. Only one case is executed since only one value holds for expression or variable inside switch. The break is used to break out of the case statements. Break is a keyword that breaks out of the code block .The break prevents the
program from testing the next case statement also.

            Below is a sample program, in which not all of the proper functions are actually declared, but which shows how one would use switch case in a program.
#include <stdio.h>     
#include <conio.h>     
void main()
{        
  int input;     
  printf("1. Play game");      
  printf("2. Load game");      
  printf("3. Play multiplayer");      
  printf("4. Exit");   
  scanf(“%d”,&input);   
  switch (input)       
  {        /*switch block starts */
   case 1: printf(“Play game is choosen”);  /*note use of  : and ; */
           break;       
   case 2:
           printf(“Load game is choosen”);     
        break; 
   case 3:              
         printf(“Play multiplayer is choosen”);
          break;       
   case 4:
         exit(0);
  default:       
        printf(“Error, bad input “);  
  }         /* end of switch */
  }        /* end of main() */

Another example:
/* this program takes input a alphabetic character and determines that either the character is vowel or consonant  and if other character is found than letter it gives appropriate message */

#include<stdio.h>
void main()
{
 char ch;
 printf(“\nEnter  a character:”);
 scanf(“%c”,&ch);
 if((ch>=’A’&&ch<=’Z’)||(ch>=’a’&&ch<=’z’))
 {
  printf(“This is alphabetic character.”);
  switch(ch)
  {
   case ‘A’: case ‘a’:
   case ‘E’: case ‘e’:
   case ‘I’: case ‘i’:
   case ‘O’: case ‘o’:
   case ‘U’: case ‘u’:
    printf(“\nThe letter is vowel “);
   break;
   default: printf(“\nThe letter is consonant.”);
  }    /* end switch */
 } /*end if */
 else printf(“The character is not alphabetic.”);
}   /*end main() */

String


STRINGS
WHAT IS A STRING?
A string is a group of characters, usually letters of the alphabet. In order to format our printout in such a way that it looks nice, has meaningful names and titles to output of our program, we need the ability to output text data.
·         A complete definition of a string is a series of char type data terminated by a null character.
·         In C there is no special data types for strings, strings are just the array of characters terminated by null ‘\0’ character with ASCII value 0
·         For example, to hold a string of six characters, we need to declare an array of
      type char with seven elements. Arrays of type char are declared like arrays of
      other data types. For example, the statement char string[7]; used to hold six char
When C is going to use a string of data in some way, either to compare it with another string, output it, copy it to another string, or whatever, the functions are set up to do what they are called to do until a null, is detected.
Initializing Character Arrays (String)
·         Like other C data types, character arrays can be initialized when they are
           declared. Character arrays can be assigned values element by element, as shown
           here:
char string[10] = { `K', `a', `t', `h',  `m', `a', ‘n’, ‘d’, ‘u’,`\0' };
·         It's more convenient to use a literal string, which is a sequence of characters enclosed in double quotes:
char string[10] = "Kathmandu"; which is same as above.
·         If you don't specify the number of subscripts when you declare an array, the compiler calculates the size of the array for you. Thus, the following line creates and initializes an six-element array:
char string[] = "Patan";
Strings and Pointer
Since strings are stored in arrays of type char, with the end of the string marked by the null character. So the name of string always points the beginning of the string. We can use array name to access that string. To pass a string to any functions, we pass the array name. The same is true of the string display functions printf() and puts()

Allocating Memory for string:
Static allocation: Declaring string as array
Dynamic Allocation : Declaring string as pointer.

The start of a string is indicated by a pointer to a variable of type char. So we can declare the string with pointer as:
char *str;
This statement declares a pointer to a variable of type char named str. It doesn't point to anything now, but what if we changed the pointer declaration to read
char *str = "This is a string declaration.";
When this statement executes, the string "This is a string declaration." (with a terminating null character) is stored somewhere in memory, and the pointer str is initialized to point to the first character of the string. We needn't worry where in memory the string is stored; it's handled automatically by the compiler.
The preceding declaration/initialization is equivalent to the following, and the two notations *str and str[] also are equivalent; they both mean "a pointer to.".
The malloc() Function
The malloc() function is one of C's memory allocation functions. When we call malloc(), we pass it the number of bytes of memory needed. malloc() finds and reserves a block of memory of the required size and returns the address of the first byte in the block. We don't need to worry about where the memory is found; it's handled automatically. The malloc() function returns an address, and its return type is a pointer to type void. A pointer to type void is compatible with all data types. Because the memory allocated by malloc() can be used to store any of C's data types, the void return type is appropriate.
#include <stdlib.h>
void *malloc(size_t size);
malloc() allocates a block of memory that is the number of bytes stated in size. By allocating memory as needed with malloc() instead of all at once when a program starts, we can use a computer's memory more efficiently. When using malloc(), we need to include the STDLIB.H header file. Some compilers have other header files that can be included; for portability, however, it's best to include STDLIB.H.
malloc() returns a pointer to the allocated block of memory. If malloc() was unable to allocate the required amount of memory, it returns null. Whenever we try to allocate memory, we should always check the return value, even if the amount of memory to be allocated is small.
An example:
#include <stdlib.h>
#include <stdio.h>
void main()
{
   /* allocate memory for a 100-character string */
   char *str;
   if (( str = (char *) malloc(100)) == NULL)
   {
     printf( "Not enough memory to allocate \n");
     exit(1);
   }
   printf( "String was allocated!"\n );
}


Displaying Strings
String display is usually done with either the puts() function or the printf() function.
The puts() Function
The puts() function puts a string on-screen--hence its name. A pointer to the string to be displayed is the only argument puts() takes. puts() can be used to display literal strings as well as string variables. The puts() function automatically inserts a newline character at the end of each string it displays, so each subsequent string displayed with puts() is on its own line.
/* Demonstrates displaying strings with puts(). */

  #include <stdio.h>

  char *message1 = "C";
  char *message2 = "is the";
  char *message3 = "best";
  char *message4 = "programming";
  char *message5 = "language!!";

  main()
  {
     puts(message1);
     puts(message2);
     puts(message3);
     puts(message4);
     puts(message5);

    return 0;
 }

output
C
is the
best
programming
language!!
The printf() Function
            The printf() function can be used to display literal strings as well as string variables but it prints all the string in one line until the \n character is encountered. It takes the argument either literal string or control character %s and corresponding string variable(pointer)
            Example
 char *str = "A message to display";
printf("%s", str);
or
printf(“A message to display “);

Inputting Strings Using the gets() Function
The gets() function gets a string from the keyboard. When gets() is called, it
reads all characters typed at the keyboard up to the first newline character (which we generate by pressing Enter). This function discards the newline, adds a null character, and gives the string to the calling program. The string is stored at the location indicated by a pointer to type char passed to gets(). A program that uses gets() must #include the file STDIO.H.
an example.
 /* Demonstrates using the gets() library function. */

  #include <stdio.h>

  /* Allocate a character array to hold input. */

  char input[81];

  main()
 {
     puts("Enter some text, then press Enter: ");
     gets(input);
     printf("You entered: %s\n", input);
     puts(input);

     return 0;
 }
output
Enter some text, then press Enter:
This is a test
You entered: This is a test
This is a test
Inputting Strings Using the scanf() Function
To read a string, include the specifier %s in scanf()'s format string. Like gets(), scanf() is passed a pointer to the string's storage location.
scanf(“%s”, str);  equivalent to  gets(str);
We can read in multiple strings with scanf() by including more than one %s in the format string. For each %s in the format string, scanf() uses the same  rules as printf() to find the requested number of strings in the input.
For example:
scanf("%s%s%s", s1, s2, s3);

Some useful String Handling functions in C library:
 Header file: <string.h>

  • strlen(s) returns the length of string ‘s’ without taking into account the terminal ‘\0’
  • srtcpy(s1,s2): copies the string s2 to string s1.
/* Demonstrates strlen() and  strcpy().  */
  #include <stdlib.h>
  #include <stdio.h>
  #include <string.h>
  char source[] = "The source string.";
 void  main()
 {
    char dest1[80];    /*array declaration */
     char dest2;      /* Pointer declaraction */
    printf("\nsource: %s", source );
    printf(“\n Length of source string is %d”, strlen(source));
/*must allocate memory for dest2 since declaration is pointer type */
  /* Copy to dest1 is okay because dest1 points to  80 bytes of allocated space. */
     strcpy(dest1, source);
     printf("\ndest1:  %s", dest1);

     /* To copy to dest2 you must allocate space. */
    dest2 = (char *)malloc(strlen(source) +1);
     strcpy(dest2, source);
     printf("\ndest2:  %s\n", dest2);

}
Output
source: The source string.
Length of Source string is  18
dest1:  The source string.
dest2:  The source string.
  • strcat(s1,s2) : appends string ‘s2’ at the end of  ‘s1’. It also called concatenation. So strcat(s1,s2) concats the strings s1 and s2.
/* Demonstration of the strcat() function. */

  #include <stdio.h>
  #include <string.h>
  char str1[27] = "a";
  char str2[2];
 void main()
 {
     int n;
     /* Put a null character at the end of str2[]. */
     str2[1] = `\0';
     for (n = ‘b’; n<=’z’; n++)
     {
         str2[0] = n;
         strcat(str1, str2);
         puts(str1);
     }
}
The output:
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
abcdefghij
abcdefghijk
abcdefghijkl
abcdefghijklm
abcdefghijklmn
abcdefghijklmno
abcdefghijklmnop
abcdefghijklmnopq
abcdefghijklmnopqr
abcdefghijklmnopqrs
abcdefghijklmnopqrst
abcdefghijklmnopqrstu
abcdefghijklmnopqrstuv
abcdefghijklmnopqrstuvw
abcdefghijklmnopqrstuvwx
abcdefghijklmnopqrstuvwxy
abcdefghijklmnopqrstuvwxyz
  • strcmp(s1, s2) : Compares two strings ‘s1’ and ‘s2’ and returns negative, zero or positive if  ‘s1’ is less than , equal or greater then the string ‘s2’ . It compares all the characters of one string one by one with character of other string. If all the characters of both string  are same, returns 0 . if at any point the characters are different,  it returns the difference of two characters.
  • strncpy(s1,s2,n) : copies first n characters from string s2 to string s1. If string s2 is less than n characters, then the entire string s2 will be copied to s.
/* demo of strncpy() */
#include <stdio.h>
#include <string.h>

  char dest[] = "##########################";
  char source[] = "abcdefghijklmnopqrstuvwxyz";

void  main()
 {
     int  n;
     while (1)
     {
         puts("Enter the number of characters to copy (1-26)");
         scanf("%d", &n);
         if (n > 0 && n< 27)
             break;
     }
    printf("\nBefore strncpy destination = %s", dest);
    strncpy(dest, source, n);
     printf("\nAfter strncpy destination = %s\n", dest);
  }
Enter the number of characters to copy (1-26)
15
Before strncpy destination = ##########################
After strncpy destination = abcdefghijklmno###########

  • strncat(s1,s2,n) : concatenates first n characters of string s2 with string s1.
/* The strncat() function. */

  #include <stdio.h>
  #include <string.h>
  char str2[] = "abcdefghijklmnopqrstuvwxyz";
  main()
  {
     char str1[27];
     int n;
     for (n=1; n< 10; n++)
     {
         strcpy(str1, "");
         strncat(str1, str2, n);
         puts(str1);
     }
 }
The output:
a
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
  • strncmp(s1,s2,n): compares at most n characters of string s2 with string s1.

  • srdup(s): The library function strdup() is similar to strcpy(), except that strdup()
performs its own memory allocation for the destination string with a call     
to malloc().

/* The strdup() function. */
  #include <stdlib.h>
  #include <stdio.h>
  #include <string.h>
  char source[] = "The source string.";
  main()
  {
     char *dest;
     if ( (dest = strdup(source)) == NULL)
     {
         printf( "Error allocating memory.");
         exit(1);
     }
     printf("The destination = %s\n", dest);
     return(0);
 }

The destination = The source string.
ANALYSIS: In this program  strdup() allocates the appropriate memory for dest. It then makes a copy of the passed string, source. Line 18 prints the duplicated string.

The Scope and life time of variables in functions


The Scope and life time of variables in functions:
What is scope and lifetime ?
                 The scope of a variable refers that to which different parts of a program have access to the variable in  other words, where the variable is visible. When speaking about scope, the term variable refers to all C data types: simple variables, arrays, structure, pointers, and so forth. It also refers to symbolic constants defined with the const keyword.
The life time of variable refers that how long the variable persists in memory, or when the variable's storage is allocated and de-allocated. Depending upon the scope and lifetime of variable, C has its  four storage classes for variables used in any functions.
  1. Automatic variables
  2. External variables
  3. Static variables
  4. Register variables
The variables may broadly categorized , depending upon the place of their declaration as: internal(local) or External(global).
·         The internal(local) variables are those which are declared inside the function.
·         The external(global) variables are those which are declared outside the  function.
Automatic variables:
            An automatic variable is defined inside the main() or function program. It is created when the function is called and get distroyed when the function segment is exited. Thus the visibility and lifetime of automatic variable is limited to the function execution. The key word ‘auto’ is used to declare the automatic variable. It is declared as:
auto  data_type  variable_name;
            Generally the keyword auto maybe dropped out. The variable declared inside function are default automatic if not any other keywords are used. These are also called local variables.
e.g.
            main()
           {
               int num;        /* num is automatic variable */
                ……..
            }
External variable:
            The external variables are declared outside the main or function block. These variables are set up memory immediately on the declaration and remain active for the entire period of program execution. Its visibility(scope) is that of the source file. It they are not initialized then they are automatically initialized to zero values. External variables are accessed by all the functions in the program. These variables are also known as global variables.
            The keyword ‘extern’ is used  to declare these variables. But it is optional. We can use extern to avoid confusion.
  extern  data_type  variable_name;
e.g.   int  sum,difference;        /* external variable */
         char name[10];
         main()
  {
     ……..
  }

Static variable:
            Static variables are generally defined inside main() or function block with keyword ‘static’ prefixed to it. They are sometimes called static auto variables as they have visibility of local (or auto) variables  and lifetime of external ( or global ) variables. Static variables are initialized once during the first function call.  These variables are declared as
static data_type  variable_name;
e.g. static int counter;

Register variables:
            If we want to tell the compiler that a variable should be kept in one of the machine’s register instead of keeping in the memory( where normal variables are stored), variables should be declared as register. The register access is much faster than memory. So keeping frequently access variables in register makes the execution of program faster. The declaraction is done as:
 register  data_type variable_name;
e.g.  register int count;
Only a few variables can be stored in register. However C compiler converts register variables into non register variables once the limit is reached.