Home / Archive by category 'C/C++'

C/C++

Program to let the user guess a number between 1 and 10 in C

#include <stdio.h>
int main()
{ 
int Magic=6, Guess;
   printf("Guess a number between 1 and 10: \n") ;
   scanf("%d",&Guess) ;
if( Guess==Magic)
        printf( " \nYour guess is correct. \n") ;
if( Guess! =Magic)
        printf( " \nYou have made a wrong guess. \n") ;
return 0;
}

Program to print the largest of three numbers in C

#include <stdio.h>
int main()
{ 
int a, b, c;
   printf( "Enter three numbers: \n") ;
   scanf( "%d%d%d", &a, &b, &c) ;
if( a>=b && a>=c)
        printf( " \n%d is the largest number.\n",a) ;
if( b>=a && b>=c)
        printf( " \n%d is the largest number.\n",b) ;
if( c>=a && c>=b)
        printf( " \n%d is the largest number.\n",c) ;
return 0;
}

Program to print the largest of two numbers in C

#include <stdio.h>
int main()
{ 
int x,y;
   printf("Enter two numbers: \n") ;
   scanf("%d%d", &x,&y) ;
if( x>=y)
   printf("\n%d is the greater number.\n", x) ;
if( x<y)
   printf("\n%d is the greater number.\n", y) ;
return 0;
}

Program to illustrate if statement in C language

#include <stdio. h>
int main( )
{ 
int x, y;
  x=3;
  y=5;
  if( x<y)
   y=x++;
  printf(ā€œ\n x = %d, y = %d. \nā€, x, y) ;
  return 0;
}

Advantages of using object properties in c++

Data encapsulation, data hiding:
Prevent direct manipulation of data elements. Avoid programming errors related to changing a data value incorrectly or at the wrong time.Example: Protecting list integrity in a multi-threaded program; e.g., transparently apply a lock or a critical section around code that manipulates the list.

Data validation, data value enforcement:
It’s a way for you to make your object self-correcting. Examples: Forcibly “pin” a data value so that it is guaranteed to be within a certain range of valid values. For instance, ensuring that a “percentage” variable will be between 0 and 100, inclusive. Make sure that a ZIP Code is exactly five or nine digits.

Transparent data manipulation:
The data itself might be stored in a form that is inconvenient for other parts of the program to use. The property logic does a conversion transparently.
Examples: Encrypt a password, Social Security Number, or other sensitive data when stored but have the clear-text value at hand when used in the program. Provide normalized handling for database NULL values. Transparently “escape” and “unescape” text that is to be displayed in an HTML page or used in an SQL query.

Data source transparency:
The programmer (and the rest of the system) does not need to know exactly how or from where the data was obtained. He just needs the value.
Example: The value is obtained through a COM-object method that might, in turn, access a database hosted on a remote system. But it looks like a local memory variable in the program code.

Invoke a function call to get or set the data by using simple assignment semantics. Hide the “dirty” low-level implementation. This is possibly the most commonly-cited value of properties.


Using #elif in C

#if STATUS == 1
      #define PERSON "Single"
#elif STATUS == 2
      #define PERSON "Married"
#elif STATUS == 3
      #define PERSON "Divorced"
#elif
      #define PERSON "Widowed"
#endif

Retrieve user specified lines from a text & store these lines to another destination file

#include <stdio.h>
 #include <process.h>
 
 #define MAX 500
 void makendx(FILE *rfp, FILE *nfp)
 {
    long line=0, spot=0;
    int ch;
 
    /* leave space for storing total number of lines in file*/
    fseek(nfp,(long)sizeof(long),0);
 
    /* Write the position of the first line*/
    fwrite((char*)&spot, sizeof(long),1,nfp);
 
    /* loop to store the positions of the subsequent lines */
    while((ch=fgetc(rfp))!= EOF){
           ++spot;
           if(ch=='n'){
                  ++spot;
                  line++;
                  fwrite((char*)&spot,sizeof(long),1,nfp);
           }
    }
 
    /* Go to the top of the index file and store total lines*/
    rewind(nfp);
    fwrite((char*)&line,sizeof(long),1,nfp);
    fclose(nfp);
    return;
 }
 
 void makeout(FILE *rfp, FILE *wfp, FILE *nfp)
    {
    long lines,lineno,start,end;
    char chunk[MAX];
 
    /*reopen index  for reading*/
    if((nfp=fopen("tmp.ndx","rb+"))==NULL){
           fprintf(stderr,"Cannot open tmp.ndxn");
           exit(5);
    }
 
    /* read total numbers of lines in source*/
    fread((char*)&lines,sizeof(long),1,nfp);
 
    printf("Enter line numbers to retrieve one by one:n");
 
    /* loop to get desired line and store to destination*/
    while(1){
           scanf("%ld",&lineno);
           if(lineno==0)
                  return;
 
           if(lineno>lines)
                  continue;
 
           /* set file position indicator to get starting position*/
           fseek(nfp,lineno*sizeof(long),0);
 
           /* read starting position*/
           fread((char*)&start,sizeof(long),1,nfp);
 
           /* read starting position of next line to count number of
           characters in the current one*/
           fread((char*)&end,sizeof(long),1,nfp);
 
           /* position the indicator to the start of source*/
           fseek(rfp,start,0);
           /*read desired number of character*/
           fread((char*)&chunk,1,end-start-1,rfp);
 
           /* write the line to destination file*/
           fwrite((char*)&chunk,1,end-start-1,wfp);
 
    }
    return;
 }
 
 int main(int argc, char *argv[])
    {
    FILE *rfp, *wfp, *nfp;
    if(argc!=3){
           fprintf(stderr,"Usage : %s <source> <destination>n",argv[0]);
           exit(1);
    }
    if((rfp=fopen(*++argv,"r"))== NULL){
           fprintf(stderr,"Cannot open %s n",*argv);
           exit(2);
    }
    if((wfp=fopen(*++argv,"w"))==NULL){
           fprintf(stderr,"Cannot open %sn", *argv);
           exit(3);
    }
    if((nfp=fopen("tmp.ndx","wb+"))==NULL){
           fprintf(stderr,"Cannot open tmp.ndxn");
           exit(4);
    }
    makendx(rfp,nfp);
    makeout(rfp,wfp,nfp);
    fclose(rfp);
    fclose(wfp);
    fclose(nfp);
    return 0;
 }

Program listing for simulating the cat command in UNIX with error handling

#include <stdio.h>
 #include <process.h>
 
 void copyfile(FILE *,FILE *);
 
 int main(int argc, char *argv[])
 {
     FILE *fileptr, *fopen();
 
     if(argc>1)
         while(--argc>0)
             if((fileptr=fopen(*++argv, "r"))==NULL)
             {
                 fprintf(stderr,"cat : can't open %sn",*argv);
                 exit(1);
             }
             else{
                  copyfile(fileptr,stdout);
                  fclose(fileptr);
             }
     else
         copyfile(stdin, stdout);
     if(ferror(stdout))
     {
         fprintf(stderr, "cat : error in writing at stdoutn" );
         exit(2);
     }
     return(0);
 }
 /* Function to copy file from rfp to wfp */
 void copyfile(FILE *rfp, FILE *wfp)
 {
     int c;
 
     while((c=fgetc(rfp))!=EOF)
            fputc(c, wfp);
     return;
 }

Program listing for simulating the cat command in UNIX

#include <stdio.h>
 #include <process.h>
 
 void copyfile(FILE *, FILE *);
 
 int main(int argc,char *argv[])
 {
     FILE *fileptr,*fopen();
     if(argc>1)
         while(--argc>0)
             if((fileptr=fopen(*++argv, "r"))==NULL)
             {
                 printf("cat : can't open %sn",*argv);
                 exit(1);
             }
             else {
                 copyfile(fileptr,stdout);
                 fclose(fileptr);
             }
     else
        copyfile(stdin, stdout);
     return(0);
 }
 
 /* Function to copy file from rfp to wfp */
 void copyfile (FILE *rfp,FILE *wfp)
 {
     int c;
 
     while((c=fgetc(rfp))!=EOF)
          fputc(c, wfp);
     return;
 }

A File read-write example in C

#include <stdio.h>
 #include <process.h>
 
 int main()
 {
    FILE *rfp,*wfp;
    char buff[80];
    int lineno=0;
 
    /*Open input and output files*/
    if((rfp=fopen("inpfile.c","r"))==NULL)
    {
        printf("Cannot open inpfile.c for reading !n");
        exit(1);
    }
    if((wfp=fopen("outfile.c","w"))==NULL)
    {
        printf("Cannot open outfile.c for writing !n");
        exit(2);
    }
 
    /*File read and write*/
    while(fgets(buff,80,rfp)!= NULL)
    {
        fprintf(wfp, "%4d:",++lineno);
        fputs(buff,wfp);
    }
    fclose(rfp);
    fclose(wfp);
    return 0;
 }

Modes for Operating a File in C

Mode Description
ā€œrā€ Opens a file for reading
ā€œwā€ Creates a file for writing or truncate to zero length
ā€œaā€ Opens a file for writing at end or create for writing
ā€œr+ā€ Opens an existing file for reading/writing
ā€œw+ā€ Truncates to zero length or create file for updating
ā€œa+ā€ Opens for updating at end
ā€œrbā€ Opens a binary file for reading
ā€œwbā€ Opens a binary file for writing
ā€œabā€ Opens a binary file for writing at end
ā€œrb+ā€ Opens an existing binary file for reading/writing
ā€œwb+ā€ Creates a binary file for updating/writing
ā€œab+ā€ Opens a binary file for appending at end

An example of bit fields in structures in C

The declaration specifies a variable called flags with four one-bit fields. The bit-field width is specified by specifying the width of the field as an integer after a colon, following the member variable identifier.

struct {
      int sign:1;
      int carry:1;
      int zero:1;
      int parity:1;
}flags;

Program to illustrate typedef in C

#include <stdio.h>
#include  <string.h>
 
typedef struct {
      char title[20];
      char publisher[25];
      char author[20];
      int no_of_pages;
      float cost;
}  books;
 
int main()
{
   books book1;
 
   strcpy(book1.title,"C tutorials");
   strcpy(book1.publisher,"sdfsdf");
   strcpy(book1.author,"xxxxhjh");
   book1.no_of_pages=281;
   book1.cost=72.00;
   printf("Book Title: %sn",book1.title);
   printf("Book Publisher: %sn",book1.publisher);
   printf("Book Author: %sn",book1.author);
   printf("No. of Pages: %dn",book1.no_of_pages);
   printf("Cost: %fn",book1.cost);
   return 0;
}

Program to demonstrate usage of unions in C

#include <stdio.h>
 
union item {
    char cvalue;
    int ivalue;
    float fvalue;
    double dvalue;
};
int main()
{
    union item value;
 
    value.cvalue='C';
    printf("cvalue=%c, address=%un",value.cvalue,&value.cvalue);
 
    value.ivalue=58;
    printf("ivalue=%d, address=%un",value.ivalue,&value.ivalue);
 
    value.fvalue=79.0;
    printf("fvalue=%f, address=%un",value.fvalue,&value.fvalue);
 
    value.dvalue=3849.273;
    printf("dvalue=%g, address=%un",value.dvalue,&value.dvalue);
 
    printf("nNew Values...n");
 
    printf("cvalue=%c, address=%un",value.cvalue,&value.cvalue);
    printf("ivalue=%d, address=%un",value.ivalue,&value.ivalue);
    printf("fvalue=%f, address=%un",value.fvalue,&value.fvalue);
    printf("dvalue=%g, address=%un",value.dvalue,&value.dvalue);
 
    return 0;
}

Program to demonstrate arrays of structures in C

#include <stdio.h>
# define limit 20
struct pair{
   int first;
   int second;
   float average;
};
 
void findavg(struct pair *,int);
 
int main()
{
   struct pair triplet[limit];
   int i;
 
   printf("Enter the integer pairs (a,b):n");
   for(i=0;i<limit;i++)
      scanf("%d,%d",&triplet[i].first,&triplet[i].second);
 
   findavg(triplet,limit);
 
   for(i=0;i<limit;i++)
      printf("%d,%d - %fn",(triplet+i)->first,
            (triplet+i)->second,(triplet+i)->average);
   return 0;
}
 
void findavg(struct pair *ptr,int lim)
{
   while(--lim>=0)
  {
       ptr->average=(float)(ptr->first + ptr->second)/2;
       ++ptr;
  }
}

Create a structure and access it using pointers to structures in C

#include <stdio.h>
 
struct point{
   float abscissa;
   float ordinate;
};
struct point mid(struct point,struct point);
 
int main()
{
   struct point p1,p2,pm;
 
   printf("Enter coordinates of two points:n");
   printf("tFor the first point (x1,y1) : ");
   scanf("%f,%f",&p1.abscissa,&p1.ordinate);
   fflush(stdin);
   printf("tFor the second point (x2,y2) : ");
   scanf("%f,%f",&p2.abscissa,&p2.ordinate);
   pm=mid(p1,p2);
   printf("The middle point is :
                            (%f,%f).n",pm.abscissa,pm.ordinate);
   return 0;
}
 
struct point mid(struct point a,struct point b)
{
   a.abscissa=(a.abscissa+b.abscissa)/2;
   a.ordinate=(a.ordinate+b.ordinate)/2;
   return a;
}

Illustrate structure member passing to and from functions in C

#include  <string.h>
 
struct books{
       char title[20];
       char publisher[25];
       char author[20];
       int no_of_pages;
       float cost;
};
 
float modify_cost(float);
 
int main()
{
   struct books book1,*pb=&book1;
 
   strcpy(pb->title,"C tuts");
   strcpy((*pb).publisher,"xxxxxx");
   strcpy(pb->author,"xxxxxxx");
   pb->no_of_pages=281;
   pb->cost=72.00;
   printf("Book Title: %sn",pb->title);
   printf("Book Publisher: %sn",pb->publisher);
   printf("Book Author: %sn",pb->author);
   printf("No. of Pages: %dn",pb->no_of_pages);
   printf("Cost: %fn",pb->cost);
   pb->cost=modify_cost(pb->cost);
   printf("New Cost: %fn",pb->cost);
   return 0;
}
 
float modify_cost(float cost)
{
   struct books temp;
   temp.cost=++cost;
   return temp.cost;
}

Create a structure and access it using pointers to structures in C

#include <stdio.h>
#include <string.h>
 
struct books{
       char title[20];
       char publisher[25];
       char author[20];
       int no_of_pages;
       float cost;
};
int main()
{
   struct books book1,*pb=&book1;
 
   strcpy(pb->title,"C tutorials");
   strcpy((*pb).publisher,"xxxx");
   strcpy(pb->author,"xxxx");
   pb->no_of_pages=281;
   pb->cost=72.00;
 
   printf("Book Title: %sn",pb->title);
   printf("Book Publisher: %sn",pb->publisher);
   printf("Book Author: %sn",pb->author);
   printf("No. of Pages: %dn",pb->no_of_pages);
   printf("Cost: %fn",pb->cost);
 
   return 0;
}

Program to create a structure and access it in C

 
#include <stdio.h>
#include <string.h>
 
struct books{
       char title[20];
       char publisher[25];
       char author[20];
       int no_of_pages;
       float cost;
};
 
int main()
{
  struct books book1;
 
  strcpy(book1.title, "C tutorials");
  strcpy(book1.publisher, "some publisher");
  strcpy(book1.author, "some author");
  book1.no_of_pages=211;
  book1.cost=71.00;
 
  printf("Book Title: %sn",book1.title);
  printf("Book Publisher: %sn",book1.publisher);
  printf("Book Author: %sn",book1.author);
  printf("No. of Pages: %dn",book1.no_of_pages);
  printf("Cost: %fn",book1.cost);
 
  return 0;
}

Check the validity of a date supplied from the command line in C

#include <stdio.h>
 
void convert(char **,int*,int*,int*);
int valid(int,int,int);
 
int main(int argc,char *argv[])
{
  int d,m,y
  char *progname=argv[0];
 
  if(--argc>0)
  {
      convert(++argv,&d,&m,&y);
      printf("The date %s is %sn",*argv,
               (valid(d,m,y))?"validn": "invalidn");
  }
  else
      printf("Usage: %s dd-mm-yyyyn",progname);
  return 0;
}
void convert(char **ptrarr,int *pd,int *pm,int *py)
{
    char *curptr,c;
    int n;
 
    /*Points to the date string */
    curptr=*ptrarr;
 
    for(n=0;((c=*curptr)>='0' && c<='9');curptr++)
        n=10*n + (c-'0');
    *pd=n;
    ++curptr;
 
    for(n=0;((c=*curptr)>='0' && c<='9');curptr++)
        n=10*n + (c-'0');
    *pm=n;
    ++curptr;
 
    for(n=0;((c=*curptr)>='0' && c<='9');curptr++)
        n=10*n + (c-'0');
    *py=n;
}
int valid(int d,int m,int y)
{
    int   leap;
 
    if(d<0 || d>31 || m<=0 || m>12 || y<=0 || y>5000)
        return 0;
    if((m==4 || m==6 || m==9 || m==11) && d>30)
        return 0;
    if(m==2 && d>29)
     return 0;
  leap= (y%4==0 && y%100!=0) || y%400==0;
  if(m==2 && leap==0 && d>28)
     return 0;
  return 1;
}