Have a Read!

Hi Everyone.
The idea for this page is to provide new c users simple c tutorials to learn how to develop the logic and more importantly correct way to write syntax.
ENJOY !!!

Sunday, February 6, 2011

How to use sscanf

#include<stdio.h>
int main()
{
char s[]="123 45.32 4";
int x;
double y;
int c;
puts(s);
sscanf(s,"%d%lf%d",&x,&y,&c);
printf("%d\n%lf\n%d\n",x,y,c);
}

How to use sprintf

#include<stdio.h>
int main ()
{ int x;
  char s[80];
  double y;
  printf("ENTER\n");
  scanf("%d%lf",&x,&y);
  sprintf(s,"integer:%6d\ndouble:%.2f\n",x,y);
  puts(s);
}

How to get string input way2

#include<stdio.h>
int main ()
{ int i=0;
  char c;   
  char a[80];
  printf("ENTER\n");
  while ((c=getchar())!='\n') {a[i++]=c;}
  a[i]='\0';
  puts(a); 
}

How to get a string input way1

#include<stdio.h>
int main()
{
char s[50];
printf("enter\n");
fgets(s,50,stdin);
printf("%s",s);
}

How to use strtol

#include<stdio.h>
#include<stdlib.h>
int main () {
const char *string="21.3% are good" ;
long d;
char *stringptr;
d=strtol(string,&stringptr,0);
printf("%s\n%ld\n%s\n",string,d,stringptr);
}

How to use strod

#include<stdio.h>
#include<stdlib.h>
int main () {
const char *string="21.3% are good" ;
double d;
char *stringptr;
d=strtod(string,&stringptr);
printf("%s\n%.2f\n%s\n",string,d,stringptr);
}

How to use atol

#include<stdio.h>
#include<stdlib.h>
int main() {
long i;
char s[20]={"23.56 this is"};
i=atol(s);
printf("%ld\n",i);
}

How to use toupper and tolower

#include<stdio.h>
#include<ctype.h>
int main() { char c,a;
printf("ENTER\n");
scanf("%c",&c);
a=toupper(c);
printf("%c\n",a);
a=tolower(c);
printf("%c\n",a);
}

How to use ctype.h functions

The following codes shows how to use isdigit(), isalpha(), isalnum(), isxdigit(), isspace(), iscntrl(), ispunct(), isprint(), isgraph(),
#include<stdio.h>
#include<ctype.h>
int main()
{int i;
char f;
printf("enter character\n");
scanf("%c",&f);
i=isdigit(f);
if(i==0)printf("not digit\n");else printf("is digit\n");
i=isalpha(f);
if(i==0)printf("not alpha\n");else printf("is alpha\n");
i=isalnum(f);
if(i==0)printf("not digit or aplha\n");else printf("is digit or alpha\n");
i=isxdigit(f);
if(i==0)printf("not xdigit\n");else printf("is xdigit\n");
i=isspace(f);
if(i==0)printf("not space\n");else printf("is space\n");
i=iscntrl(f);
if(i==0)printf("not cntrl\n");else printf("is cntrl\n");
i=ispunct(f);
if(i==0)printf("not punct\n");else printf("is punct\n");
i=isprint(f);
if(i==0)printf("not print\n");else printf("is print\n");
i=isgraph(f);
if(i==0)printf("not graph\n");else printf("is graph\n");
}

How to use strlen

#include<stdio.h>
#include<string.h>
int main ()
{
  const char *s="abcdefghijklmnopqrstuvwxyz";
   int y;
   y=strlen(s);
   printf("%d\n",y);
}

How to use memset

#include<stdio.h>
#include<string.h>
int main()
{ char s[]="ggggggggggg";
  memset(s,'G',5);
puts(s);
}

How to use memmove

#include<stdio.h>
#include<string.h>
int main ()
{
char x[]="home sweet home";
memmove(x,&x[5],10);
puts(x);
}

How to use memcpy

#include<stdio.h>
#include<string.h>
int main()
{char s[17];
char x[]="Thats how it is done";
memcpy(s,x,17);
puts(s);
}

How to use strstr

#include<stdio.h>
#include<string.h>
int main()
{
const char *s="scorecard";
const char *y="e";
printf("%s\n",strstr(s,y));
}

How to use strrchr

#include<stdio.h>
#include<string.h>
int main()
{
const char *s="the camera is zooming";
int c='a';
printf("%s\n",strrchr(s,c));
}

How to use strpbrk

#include<stdio.h>
#include<string.h>
int main()
{
const char *s="best of luck";
const char *x="o";
printf("%c\n",*strpbrk(s,x));
}

How to use strchr

#include<stdio.h>
#include<string.h>
int main()
{
const char *s="Thats how it is done";
char c='u';
if (strchr(s,c)!=NULL)
{printf ("found\n");}
else
{printf("not found\n");}
}

How to use strcmp

#include<stdio.h>
#include<string.h>
int main()
{
const char *x="memm";
const char *y="mmea";
int c;
c=strcmp(x,y);
if(c==0) {printf("0\n");}
if(c<0)  {printf("-1\n");}
if (c>0) {printf("1\n");}
}

How to use strcpy & strncpy

#include<stdio.h>
#include<string.h>
int main()
{
char x[]="HOW TO USE THIS";
  char y[25];
  char z[15];
strcpy(y,x);
puts(y);
strncpy(z,x,6);
puts(z);
}

C Program for Finding maximum entry in data

#include<stdio.h>
void array(int a[4][3]);
int locater(int b[4][3],int c);
int main()
{
    int marks,i;
    int record[4][3]={{12,25,67},{32,30,65},{15,34,70},{20,40,79}};
    printf("\n\n\n");
    array(record);
    for(i=0;i<3;i++)
        {
            marks=locater(record,i);
            if(i==0)
            {
            printf("\nThe Maximum lowest marks in all sections are %d\n",marks);
            }
            if(i==1)
            {
            printf("The Maximum Average in all sections are %d\n",marks);
            }
            if(i==2)
            {
            printf("The Maximum Highest marks in all sections are %d\n\n\n\n",marks);
            }
        }
    return 0;
}
void array(int a[4][3])
{
            int i,j;
            printf("Sections    Lowest Average Highest\n");
            printf("        marks  marks    marks\n"   );
                for(i=0;i<4;i++)
                    {   
                    printf("Section %d\t",i+1);
                    for(j=0;j<3;j++)
                        {
                            printf("%d\t",a[i][j]);
                        }   
                    printf("\n");
                    }
}
int locater(int a[4][3],int c)
{
            int x;
            for(x=0;x<4;x++)
            {
                if(a[x][c]>=a[1][c] && a[x][c]>=a[2][c] && a[x][c]>=a[3][c])
                               {   
                return a[x][c];       
                            }   
            }
}

C Program for Searching and Sorting Data

#include<stdio.h>
#include<stdlib.h>
void sorter(int b[],int size);
void searcher(int b[],int size);
int main()
{
    int a[40],i;
    printf("\n\n\nTHE DATA SET CONTAINS 40 VALUES WHICH ARE AS FOLLOW:");
    printf("\n");
    for(i=0;i<40;i++)
    {a[i]=rand()%40;
    printf("%d ",a[i]);
    }
    sorter(a,40);
    searcher(a,40);
    return 0;
}
void sorter(int b[],int size)
{
    int i,j,k,temp;
    for(i=0;i<size;i++)
        {
        for(j=0;j<size-1;j++)
        {
            if(b[j]>b[j+1])
            {temp=b[j];
                 b[j]=b[j+1];
                 b[j+1]=temp;
            }
         }
        }
    printf("\n\n\nTHE DATA IS BEING SORTED AS FOLLOW:\n");
    for(k=0;k<40;k++)
    {printf("%d ",b[k]);}
    printf("\n\n");
    }
void searcher(int b[],int size)
{
    int key,found,low,mid,high;
    printf("\nWhat value you want to locate=");
    scanf("%d",&key);
    low=0;
    high=size-1;
    while(low<=high)
    {   
    mid=(low+high)/2;
    if(b[mid]==key)
    {
    found=1;
    break;
    }
    else if(b[mid]>key)
    {
    high=mid-1;
    }
    else
    {
    low=mid+1;
    }
    }
    if(found==1)
    printf("%d is in the data set\n",key);
    else printf("%d is not in the data set\n",key);
}

C Program for int type function

#include<stdio.h>
int function(int);
int main ()
{
int x=10,y;
y=function(x);
printf("%d\n",y);
return 0;
}
int function(int a)
{return a*a;}

C Code for void type fuction

#include<stdio.h>
void function(int);
int main()
{
int x=10;
function(x);
return 0;
}
void function(int a)
{printf("%d\n",a);}

C Program for array of characters/string

#include<stdio.h>
int main ()
{
char a[]="Hello";
int x;
for (x=0;x<6;x++)
    {printf("%c",a[x]);} //printing character wise
printf("\n");
//printing string directly
printf("%s\n",a);
return 0;
}

C Program for initializing 2d array

#include<stdio.h>
int main ()
{
int a[10][10]={0};
int x,y;
for (x=0;x<10;x++)
    for (y=0;y<10;y++)
        {printf("%d\n",a[x][y]);}
return 0;
}

C Program for initializing and printing array

#include<stdio.h>
int main()
{
int a[10]={0};
int x;
for (x=0;x<10;x++)
  {
    printf("%d\n",a[x]);
  }
return 0;
}

Sunday, January 30, 2011

C PROGRAM FOR A BAKERY

The following represents a simple bakery program that keeps the update of sales made.Run it first then you will have a better understanding of whats going on  in the code.
#include<stdio.h>//standard input
int main()//entry to main fuction
{
int bread=15; // initial bread available
int breadsold,remainingbread=15,breadprofit=0; // variables for bread
int egg=72; // initial egg available
int eggsold,remainingegg=72,eggprofit=0; // variables for egg
int butter=25;//initial butter available
int buttersold,remainingbutter=25,butterprofit=0;//variables for bread
int milk=50; // initial milk
int milksold,remainingmilk=50,milkprofit=0;//variables for milk
int item,x,profit1=0,profit2=0,profit3=0,profit4=0,megaprofit=0;//variables for profit and items selected
printf("\n\n*******************************************************************************\n");
printf("\t\t\t      WELCOME TO BAKERY\n ");
printf("\t     CURRENTLY WE HAVE THE FOLLOWING ITEMS IN QUANTITY\n");
printf("\t        BREAD         EGG        BUTTER        MILK\n");
printf("\t         %d            %d         %dkg          %dl\n\n\n",bread,egg,butter,milk);
printf("Current Market Rates for Respected Items are as Follow:\nBread=40Rs\nEgg=4Rs\nButter=50Rs/kg\nMilk=50Rs/ltr\n\n\n\n");
printf("What would you like to sell\n");  // Here user selects what to sell
printf("1 for Bread\n");
printf("2 for Egg\n");
printf("3 for Butter\n");
printf("4 for Milk\n");
printf("Your choice:");
scanf("%d",&item);
if(item>4 || item<=0)
   {printf("Not a valid entry"); }
else{
for(x=0;x!=6;x)  // Only loop so that user can sell more
{
   if (item==1) // 'Bread if'
      {
         printf("\nhow much bread u want to sell\n");
         scanf("%d",&breadsold);
            if (breadsold>remainingbread || breadsold<0)
            {printf("We dont have this much Bread to sell kindly keep it less or equal to quanitiy available\n");}
            else
            {remainingbread=bread-breadsold; //tracker of bread available for next entry in the loop
            bread=remainingbread;
            profit1= breadsold*40;//calculates profit of this sale
            breadprofit=profit1 + breadprofit;//for total megaprofit
            printf("\nThe quantity of Bread u have sold is %d\nThe profit for this sale is %dRs\nNow you have %d bread remaining to sell\n\n",breadsold,profit1,remainingbread);
             megaprofit=breadprofit+eggprofit+butterprofit+milkprofit ;}
      }// 'End Bread if'
  if (item==2) //"Egg if"
     {
       printf("how much Egg u want to sell\n");
       scanf("%d",&eggsold);
        if(eggsold>remainingegg || eggsold<0)
           {printf("We dont have this much Egg to sell kindly keep it less or equal to quantity available\n");}
         else{
         remainingegg=egg-eggsold;//traker for egg available
         egg=remainingegg;
         profit2=eggsold*4;//profit of this sale
         eggprofit=profit2+eggprofit;//total eggprofit for megaprofit
         printf("\nThe quantity of Egg u have sold is %d\nThe profit for this sale is %dRs\nNow you have %d Egg remaining to sell\n\n",eggsold,profit2,remainingegg);
         megaprofit=breadprofit+eggprofit+butterprofit+milkprofit ;}
    } // End " Egg if"
  if (item==3)//"Butter if"
  {
       printf("how much Butter u want to sell\n");
       scanf("%d",&buttersold);
          if(buttersold>remainingbutter || buttersold<0 )
           {printf("We dont have this much Butter to sell kindly keep it less or equal to quantity available\n");}
          else {
           remainingbutter=butter-buttersold;//tracker of butter available
           butter=remainingbutter;
           profit3=buttersold*50;//profit for this sale
           butterprofit=profit3+butterprofit;//total profit ofbutter for megaprofit
           printf("\nThe quantity of Butter u have sold is %dkg\nThe profit for this sale is %dRs\nNow you have %dkg Butter remaining to sell\n\n",buttersold,profit3,remainingbutter);
           megaprofit=breadprofit+eggprofit+butterprofit+milkprofit ;}
  } //End "butter if"
  if (item==4) // " Milk if"
  {
  printf("how much Milk u want to sell\n");
  scanf("%d",&milksold);
     if(milksold>remainingmilk || milksold<0)
     {printf("We dont have this much Milk to sell kindly keep it less or equal to quantity available\n");}
     else {
      remainingmilk=milk-milksold;//tracker of milk availabe
      milk=remainingmilk;
      profit4=milksold*50;//this sale profit
      milkprofit=profit4+milkprofit;//for megaprofit
      printf("\nThe quantity of Milk u have sold is %dltr\nThe profit for this sale is %dRs\nNow you have %dltr Milk remaining to sell\n\n",milksold,profit4,remainingmilk);
      megaprofit=breadprofit+eggprofit+butterprofit+milkprofit ;}
  } //End "Milk if"
if (item==5)
{printf("Profit earned uptill now is %dRs",megaprofit);}
printf("\n\n\nWhat would you like to sell\n"); // portion for sale after another or end
printf(" 1 for Bread\n");
printf(" 2 for Egg\n");
printf(" 3 for Butter\n");
printf(" 4 for Milk\n");
printf("OR\n");
printf(" 5 to view Profit earned uptill now\n");
printf(" 6 if you are willing to Exit sale\n");
printf("Your choice:");
scanf("%d",&item); // end portion
if( item<=0 || item>6)
{printf("\nNOTE : There is no such choice\nPlease select again\n");}
if(item==6) // if 6 is entered the loop ends
{ x=6;
megaprofit=breadprofit+eggprofit+butterprofit+milkprofit ; //calculates the profits of all sales made
printf("\n\n\nThe Profit you earned for today's sale is %dRs\n You have\n %d BREAD\n %d EGG\n %dkg Butter \n %dltr MIlk left to sale\n\n\n \t\t\tHAVE A GOOD DAY\n\n\n",megaprofit,remainingbread,remainingegg,remainingbutter,remainingmilk); }
//displays the total profit
}//end For loop
}
printf("\n\n*******************************************************************************\n");
return 0;} //end main funtion

Saturday, January 29, 2011

C PROGRAM FOR SQUARE/RECTANGLE

#include<stdio.h>
int main()
{
    int x,y,h,w;
    printf("ENTER THE HEIGHT AND WIDTH OF SQUARE/RECTANGLE\n\n");
    scanf("%d%d",&h,&w);
    for(y=1;y<=h;y++)
    {
        for(x=1;x<=w;x++)
        {
            printf("^");
        }
        printf("\n");
    }
return 0;
}

C PROGRAM FOR DIAMOND

#include<stdio.h>
int main()
{
    int counter,x,y,z;
    int count,a,b,c,input;
    printf("PLEASE ENTER the width");   
    scanf("%d",&input);
    counter=0;
    for(x=input;x>=1;x--)
    {
        for(y=1;y<=x;y++)
        {
            printf(" ");
        }
                counter=counter+1;
            for(z=1;z<=counter;z++)
                {printf("* ");}
                printf("\n");}
    count=input;
    for(a=1;a<=input;a++)
    {
        printf(" ");
        for(b=1;b<=a;b++)
        {
            printf(" ");
        }
        count=count-1;
        for(c=1;c<=count;c++)
        {
            printf("* ");
        }
        printf("\n");
    }
return 0;
}

C PROGRAM FOR PYRAMID

#include<stdio.h>
int main()
{
    int counter,x,y,z;
        counter=0;
    for(x=15;x>=1;x--)
    {
        for(y=1;y<=x;y++)
        {
            printf(" ");
        }
                counter=counter+1;
            for(z=1;z<=counter;z++)
                {printf("* ");}
                printf(" \n");}
return 0;
}

C PROGRAM FOR HOLLOW TRIANGLE

#include<stdio.h>
int main()
{
    int x,y,z;
    printf("*\n");   
    for(x=1;x<10;x++){
                     printf("*");
                           for(y=1;y<=x;y++){
                            printf(" ");
                                           }
          printf("*\n");
                         }
        for(z=1;z<=10;z++)
        {printf("*");}
    printf("**");
    printf("\n");
return 0;
}

C PROGRAM FOR TRIANGLE

#include<stdio.h>
int main()
{
int x,y,h;
printf("ENTER HEIGHT OF TRIANGLE:\n");
scanf("%d",&h);
for(x=1;x<=h;x++){
for(y=1;y<=x;y++){
printf("^");
}
printf("\n");
}
return 0;
}

C PROGRAM FOR FACTORIAL OF A NUMBER

#include<stdio.h>
int main () {
int i,num,factorial=1;
printf("ENTER THE NUMBER");
scanf("%d",&num);
if(num<0)
printf("Factorial not possible");
else
{
  for (i=1;i<=num;i++)
  {factorial=factorial*i;}
  printf("\nFACTORIAL=%d\n",factorial);      
}
return 0;
}

C PROGRAM FOR ARMSTRONG NUMBER UPTO LIMIT

#include<stdio.h>
int main () {
int num,n,sum,r,limit;
printf("ENTER THE LIMIT\n");
scanf("%d",&limit);
printf("Armstrong numbers upto given limit are:\n");
for(num=1;num<limit;num++)
{
    n = num;
    sum = 0 ;
    while (n!=0)
        {
            r=n%10;
            sum=sum+(r*r*r);
            n=n/10;
        }
    if(sum==num)
        {printf("%7d\n",num);}
}
return 0;
}

C PROGRAM FOR ARMSTRONG NUMBER

#include<stdio.h>
int main () {
int num,n,sum,r;
printf("ENTER THE NUMBER\n");
scanf("%d",&num);
n=num;
sum=0;
while(n!=0)
  {
    r=n%10;
    sum=sum+(r*r*r);
    n=n/10;
  }
if(sum==num)
   {printf("\n%d is armstrong number\n",num);}
else
   {printf("\n%d is not armstrong number\n",num);}
return 0;
}  

C PROGRAM FOR FIBONACCI SERIES

#include<stdio.h>
int main () {
int a,b,n,next,count;
printf("how many terms are required 2<=n<=24\n");
scanf("%d",&n);
a=0;
b=1;
printf("\n\nFIBNONACCI TERMS ARE:\n");
printf("%8d%8d",a,b);
count=2;
while (count<n)
    {
        next=a+b;
        printf("%8d",next);
        a=b;
        b=next;
        count++;
    }
printf("\n");
return 0;
}

Thursday, January 27, 2011

C PROGRAM FOR SUM OF EVEN AND ODD NUMBERS UPTO LIMIT

#include<stdio.h>
int main ()
{
int n,i,sumeven=0,sumodd=0;
printf("ENTER THE LIMIT\n");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
    if ((i%2)==0)
     {sumeven=sumeven+i;}
    else
      {sumodd=sumodd+i;}
}
printf("\n\nSUM OF EVEN NUMBERS UPTO %d is %d\n",n,sumeven);
printf("\n\nSUM OF ODD NUMBERS UPTO %d is %d\n",n,sumodd);
return 0;
}

C PROGRAM FOR NTH TERM OF FIBONACCI SERIES

#include<stdio.h>
int main()
{
int x=0,y=1,z,nth,i;
printf("\n\nPlease Enter The Term Number:");
scanf("%d",&nth);
for(i=1;i<=nth;i++)
{z=x+y;
x=y;
y=z;
}
printf("\nthe %dth term of Fibonacci Series is is %d\n\n\n",nth,z);
return 0;
}

C PROGRAM FOR COMPLETE SQUARE TRIANGLE

The following code will print upto 20 the triangle whos hypotenuse is a complete square. You can extend the limits by doing some changes in the code to your desire.
#include <stdio.h>  
#include <math.h>    // for sqrt root function
int main ()         
{
int b,p;             // initialization
int h;           // initialization
printf("All the Applicable Triangles are:\n");
printf("Base \t Perp \t   Hyp \n"); // to represent sides of triangle which are satisfied by pythagoras theorem
  for(b=1;b<=19;b++)   // first loop starts with one side from 1-19
     { for (p=1; p<=19;p++) // second loop starts with b=loop state untill p=19
             { for (h=sqrt((p*p)+(b*b));h==sqrt((p*p)+(b*b));h++) // 3rd loop takes the first input only and becomes false for nxt loop so no further execution occurs
               if (h>=20)   // if hyp is more than 20 sides wont be printed
               break;
               else  
               {printf(" %d \t  %d \t   %d \n",b,p,h); // sides printed if h^2=b^2+p^2 ans is integer
             } // end of third loop
      } // end of second loop
    } //end of first loop
return 0;
} //end main

C PROGRAM FOR PRIME FACTORS OF A NUMBER

#include<stdio.h>
int main()
{ int x,q,no,s;
  printf("Enter the Number: "); // the number to be operated
  scanf("%d",&no);
  printf("\nThe Prime Factors of %d Follow:\n" ,no);
  for ( x=2;(no/x)>=1;x++) // entry to only loop which lets only prime    factors to be printed
      { if ((no%x)==0)        // prints the factor if mod is 0
         {printf("%d  ",x);
          s=(no/x);           
          no=s;          // changes the number for entry into loop again
          x=x-1;        // it makes the x same when entered again in the loop
         }
      }// loop end 
  printf("\n");
  return 0;
}

C PROGRAM FOR PRIME NUMBER way2

//This one is a little complicated
#include<stdio.h>
int main()
{ int x,q,no,s,originalno;
  printf("Enter the Number: ");
  scanf("%d",&no);
  originalno=no;
  for ( x=2;(no/x)>=1;x++)
      { if ((no%x)==0)      
         {
      if (x==originalno)
          {printf("%d is a PRIME number\n",originalno);}
      s=(no/x);           
          no=s;         
          x=x-1;       
         }
      }
if(x!=originalno)
  {printf("%d is not a prime number\n",originalno);}
  return 0;
}

C PROGRAM FOR PRIME NUMBER way1

#include <stdio.h>
int main()
{
int x,y,z,a=0;
printf("enter the number: ");
scanf("%d",&x);
for (y=2;y<x;y++)
      { if (x%y==0)
            {a=y;}   
    }// loop end
if(a==0)
{printf("Number is Prime\n");}
else
{printf("Number is not Prime\n");}
return 0;
}

C PROGRAM FOR FACTORS OF A NUMBER

#include <stdio.h>
int main()
{
int x,y,z;
printf("enter the number: ");
scanf("%d",&x);
printf("The factors are as follow:\n");
for (y=1;y<=x;y++)
      { if (x%y==0)
        printf("%d\n",y);}// loop end
return 0;
}

C PROGRAM FOR PRINTING MULTIPLICATION TABLE OF No

#include<stdio.h>
int main() {
int i,num;
printf("ENTER THE NUMBER");
scanf("%d",&num);
for (i=0;i<=10;i++)
{printf("%d * %2d = %d\n",num,i,num*i);}
return 0;
}

C PROGRAM FOR SUM OF N NUMBERS USING while,Do while & for Loop

I guess it is enough with the simple examples of if .So the examples below illustrate the use of while , do while and for loop all are doing the same thing. I have made the same code just to show the differences among these loops.I myself prefer for loop as it is summed up in just a single line.Anyways this is the code.
// WHILE LOOP

#include<stdio.h>
int main()
{
int n,i=1,sum=0;
printf("ENTER THE VALUE OF N:");
scanf("%d",&n);
printf("First %d numbers are\n",n);
    while (i<=n)
    {
      printf("%7d ",i); //%7 to print the digit within 7 slots
       sum = sum +i;
       i++;
    }
printf("\nSum = %d\n",sum);
return 0;
}

// DO WHILE LOOP
 
#include<stdio.h>
int main ()
{
int n,i=1,sum=0;
printf("ENTER THE VALUE OF N:");
scanf("%d",&n);
printf("First %d numbers are\n",n);
do
{
  printf("%7d,",i);
  sum=sum+i;
  i++;
  }
while(i<=n);
printf("\n\nSum=%d\n",sum);
return 0;
}

//FOR LOOP
 
#include<stdio.h>
int main()
{
int n,i=1,sum=0;
printf("ENTER THE VALUE OF N:");
scanf("%d",&n);
printf("First %d numbers are\n",n);
for(i=1;i<=n;i++)
    {
        printf("%7d",i);
        sum=sum+i;
    }
printf("\n\nSum = %d",sum);
return 0;
}

C PROGRAM FOR SOLVING QUADRATIC EQUATION

#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c,r1,r2,img1,img2,disc;
printf("\nENTER THE Co-officients\n");
scanf("%f%f%f",&a,&b,&c);
if (a==0)
    {
      if (b==0)
          printf("Equation is Degenerate\n");
       else
     {
        printf("Linear equation has single root");
        r1=-c/b;
            printf("\nRoot=%.2f",r1);
      }
      }
    else
      {
         disc=(b*b)-(4*a*c);
           if(disc>0)
        {
            printf("Real and disctinct roots\n");
            r1=(-b+sqrt(disc))/(2*a);
            r2=(-b-sqrt(disc))/(2*a);
            img1=img2=0;
        }
          else
        {
              if(disc==0)
            {
               printf("Real and equal roots\n");
               r1=r2=(-b)/(2*a);
               img1=img2=0;
            }
            else
            {
              printf("Imaginary roots\n");
              r1=r2=-b/(2*a);
              img1=sqrt(-disc)/(2*a);
              img2=img1;
            }
              }
        printf("\nFirst root is \n");
        printf("\nReal part=%.2f  Imaginary part=%.2f\n",r1,img1);
        printf("\nSecond root");
        printf("\nReal part=%.2f  Imaginary part=%.2f\n",r2,img2);
    }
return 0;

C PROGRAM FOR TRIANGLE AREA AND ITS TYPE

In the following code i have included the math library as well because the use of square root function was required . There are plenty others functions located in the math library .Dont forget to write –lm while compiling as it is required for math library if ur working on linux environment eg gcc test.c –lm . Anyways here is the code as the topic says

#include<stdio.h>
#include<math.h>
int main ()
{
float a,b,c,s,area;
printf("\nENTER THE THREE SIDES OF TRIANGLE\n");
scanf("%f%f%f",&a,&b,&c);
if( ((a+b)>c) && ((a+c)>b) && ((b+c)>a))
  {
     if ((a==b) && (a==c))
    {printf("\nEQUILATERAL TRIANGLE\n");}
     else
       {
     if((a==b) || (a==c) || (b==c) )
       printf("\nISOCELES TRIANGLE\n");
     else
       printf("\nSCALENE TRIANLGE\n");
    }
    s=(a+b+c)/2;
    area=sqrt(s*(s-a)*(s-b)*(s-c));
    printf("AREA IS %.2f sq units\n",area);
    }
else
{printf("TRIANGLE NOT POSSIBLE");}
retur

C PROGRAM FOR SWITCH CONTROL

#include<stdio.h>
int main ()
{
int day;
printf("ENTER THE WEEKDAY\n");
scanf("%d",&day);
switch(day)
{
  case 1: printf("weekday is Sunday\n");
          break;
  case 2: printf("weekday si Monday\n");
      break;
  case 3: printf("weekday is Tuesday\n");
      break;
  case 4: printf("weekday is Wednesday\n");
      break;
  case 5: printf("weekday is Thursday\n");
      break;
  case 6: printf("weekday is Friday\n");
         break;
  case 7: printf("weekday is Saturday\n");
       break;
  default:printf("Wrong choice entered\n");
      break;
}
return 0;
}

C PROGRAM FOR 5 NUMBERS AVERAGE TELLER

#include<stdio.h>
int main ()
{
float a,b,c,d,e,sum,avg;
printf("ENTER THE FIVE NUNBERS\n");
scanf("%f%f%f%f%f",&a,&b,&c,&d,&e);
sum=a+b+c+d+e;
avg=sum/5;
printf("SUM=%.2f\n",sum); // .2 is used to restrict upto 2 decimal digit
printf("AVERAGE=%.2f\n,",avg);
return 0;
}

C PROGRAM FOR CONVERTING NUMBER TO YEARS WEEKS & DAYS

#include<stdio.h>
int main () {
int number,years,weeks,days;
printf("ENTER THE NUMBER\n");
scanf("%d",&number);
years=number/365;
weeks=(number-(years*365))/7;
days=(number-(years*365)-(weeks*7));
printf("\nYEARS=%d\nWEEKS=%d\nDays=%d\n",years,weeks,days);
return 0;
}

C PROGRAM FOR LEAP YEAR

#include<stdio.h>
int main() {
int year;
printf("ENTER THE YEAR\n");
scanf("%d",&year);
if ((year%4==0)&& (year%100!=0))
{printf("%d is a leap year\n",year);}
else
printf("%d is not a leap year\n",year);
return 0;
}

C PROGRAM FOR GRADE CALCULATOR

#include<stdio.h>
int main () {
int sub1,sub2,sub3,sub4,sub5,total;
float average;
printf("ENTER THE NUMBERS IN 5 SUBJECTS OF THE STUDENT\n");
scanf("%d%d%d%d%d",&sub1,&sub2,&sub3,&sub4,&sub5);
   total=sub1+sub2+sub3+sub4+sub5;
   average=total/5;
   if(average>=80)
     {printf("STUDENT HAS GOT A GRADE\n");}
  else if(average>=70)
     {printf("STUDENT HAS GOT B GRADE\n");}
  else if(average >=60)
     {printf("STUDENT HAS GOT C GRADE\n");}
  else if(average>=50)
     {printf("STUDENT HAS GOT D GRADE\n");}
  else if(average>=40)
     {printf("STUDENT HAS GOT E GRADE\n");}
  else
     {printf("STUDENT HAS FOT F GRADE\n");}  
return 0;
}

C PROGRAM FOR CONDITIONAL OPERATER

#include<stdio.h>
int main()
{
int age;
printf("ENTER YOUR AGE IN YEARS\n");
scanf("%d",&age);
(age>=18) ?printf("\nYOU SHOULD VOTE\n"): printf("\nYOU CANNOT VOTE\n");
return 0;
}

C PROGRAM FOR GETTING ASCII CODE way2

#include<stdio.h>
int main()
{
int z;
printf("ENTER THE CHARACTER\n");
z=getchar();
printf("THE ASCII VALUE OF CHARACTER is %d\n",z);
return 0;
}

C PROGRAM GOR ASCII CODE way1

The following code will get the ASCII code of the character entered by the user
#include<stdio.h>
int main()
{
int x;
char character;
printf("ENTER THE CHARACTER\n");
scanf("%c",&character);
x=character;
printf("THE ASCII VALUE OF %c is %d\n",character,x);
return 0;
}

Wednesday, January 26, 2011

C PROGRAM TO REVERSE 5 DIGIT NUMBER

/*this program will reverse the five digit number*/
#include<stdio.h>
int main()
{
int no,b,c,d,e,rev; /*no is the number entered by user rev is the reverse number which will be displayed at the end*/
printf("enter a five digit no.\n");
scanf("%d",&no);
if(no<=99999 && no>=10000)        /*this if statement is to make sure that user enters a five digit number
                                    otherwise the program will display "you have not entered a five digit number"*/
{
  b=no/10;      /*int  is used so number after decimal will be neglected*/
  c=b/10;
  d=c/10;
  e=d/10;
  rev=(no-10*b)*10000;      /*this formula will calculate unit digit of number entered by user and multiply by 10000
                              in this way it will become first digit of reverse number*/  
  rev=rev+((b-10*c)*1000); /*this formula will calculate the tens digit of number entered by user and multiply by 1000
                             the resultant will be added to previous calculated no. i.e rev so first two digits are
                             reversed.in the similar way all digits will be reversed*/
  rev=rev+((c-10*d)*100);
  rev=rev+((d-10*e)*10);
  rev=rev+e;
  printf("%d\n",rev);
}
else          /*this else is with the first if statement*/
printf("you have not entered a five digit no.\n");
return 0;
}

C PROGRAM FOR BASIC FORMULAS

/*this program can solve formulas:
1)force=mass*acceleration        2)coversion of litres in gallons      3)conversion of km in meters
this program will display a menu and its your choice which formula you want to use*/
#include<stdio.h>
int main()
{
float choice;
float mass;
float acc;
float force;
float lt;
float gall;
float meter;
float km;
printf("which formula do you want to use\n\n1)force=mass*acceleration\n2)conversion of litres of petrol in gallons\n3)conversion of distance in km into meters\n");
printf("\nenter a choice 1,2 or 3\n");
scanf("%f",&choice); /*this will take a number from user that which formula he want to solve*/
if(choice==1 || choice==2 || choice==3)     /*this if statement makes sure that choice entered is 1,2
                                              or 3*/                    
{
  if(choice==1)     /*this statement wil execute if the user enters 1 coice which is to find force*/
  {
   printf("enter mass\n");
   scanf("%f",&mass);
   printf("enter acceleration\n");
   scanf("%f",&acc);
   force=mass*acc;
   printf("force is %f\n",force);
  }
  if(choice==2)     /*this statement wil execute if the user enters 2 coice*/
  {
   printf("enter volume of petrol in litres\n");
   scanf("%f",&lt);
   gall=lt*0.264172052358148;
   printf("volume of petrol in gallons is %f\n",gall);
  }
  if(choice==3)    /*this statement wil execute if the user enters 3 coice*/
  {
   printf("enter distance in km\n");
   scanf("%f",&km);
   meter=km*1000;
   printf("distance in meters is %f\n",meter);
  }
}
else            /*this else is with the first if statement*/
printf("you have entered a wrong choice\n");
return 0;
}

C PROGRAM FOR NUMBER VALIDITY FOR DIFFERENT CONDITIONS

This program checks the validity of two numbers.a valid input would satisfy following conditions:
a)inputs should be integers
b)each no. is between 1 and 100
c)two no.s are not divisible to each other
d)difference of two is not less than 1
e)sum of these should not exceed 100

#include<stdio.h>

int main()
{
float no1,no2;
int x,y,z;
z=0; /*this variable is introduced so that in the end we can print inputs are valid or not.for each condition satisfying
      its value will increase by 1.if its value becomes 5 at the end then all the conditions are satisfying otherwise not*/
printf("Enter two numbers\n");
scanf("%f",&no1);            
scanf("%f",&no2);
/*this procedure will calculate that the number is an integer or not.Any integer devided by 2 will always give remainder 0,1 or -1.(no1-2*x) in this formula x is not a floating point no. so it will neglect no.s after decimal.in this way remainder will always be 0,1 or -1 if no1 is an integer*/
x=no1/2;
if((no1-2*x)==0 || (no1-2*x)==1 || (no1-2*x)==-1) // the || is used for or
{
x=no2/2;
if((no2-2*x)==0 || (no2-2*x)==1 || (no2-2*x)==-1)
{
printf("\nthe numbers are integers\n");
z=z+1;
}
else
printf("one or more numbers are not integers\n");
}
else
printf("one or more numbers are not integers\n");
/*in this procedure it is calculated that the numbers are between 1 and 100 or not.1/no1 will always be greater than 1/100
//or 0.01 if no1>0 and no1<100 and if no1 is between 1 and 100 than no1 cannot be equl to 0,1 or 100*/
if((1/no1)>0.01 && (1/no2)>0.01 && no1!=100 && no2!=100 && no1!=0 && no2!=0 && no1!=1 && no2!=1)
{
printf("numbers enterd are between 1 and 100\n");
z=z+1;
}
else
printf("one or more numbers enterd are not between 1 and 100\n");
//y is not afloating point number so it will neglect any no.s after decimal.according to formula in //the if statement if the two no.s are not divisible the formula will not give 0 resultant
y=no1/no2;
if(no1-no2*y!=0)
{
y=no2/no1;
if(no2-no1*y!=0)
{
printf("numbers are not divisible to each other\n");
z=z+1;
}
}
else
printf("numbers are divisible to each other\n");
//if difference of two numbers is not less then one then one number is atleast +1 greater tnan the other
if(no1>=no2+1 || no2>=no1+1)
{
printf("difference is not less than 1\n");
z=z+1;
}
else
printf("difference is less than 1\n");
//the sum of numbers should not be greater than 100
if((no1+no2)<=100)
{
printf("sum of numbers does not exceed 100\n");
z=z+1;
}
else
printf("sum of numbers exceeds 100\n");
//as mentioned earlier if z becomes 5 at the end it will be printed that inputs are valid otherwise not
if(z==5)
printf("\nall conditions are satisfied inputs are valid\n");
else
printf("\none or more conditions are not satisfied inputs are not valid\n");

return 0;

}

C PROGRAM FOR SWAPPING TWO NUMBERS

#include<stdio.h>
int main()
{
int no1;
int no2;
printf("Enter first no\n");
scanf("%d",&no1);            
printf("enter second no\n");
scanf("%d",&no2);            
printf("\nBefore swapping\n");
printf("no1=%d no2=%d\n",no1 ,no2);
no1=no1+no2;                  
no2=no1-no2;
no1=no1-no2;
printf("\nAfter swapping\n");
printf("no1=%d no2=%d\n",no1,no2);
return 0;
}

C PROGRAM FOR TAKING CHARACTER INPUTs USING gerchar()

# include<stdio.h>
int main () {
char x,y,z;
printf("ENTER THE THREE CHARACTERs\n");
x=getchar();
y=getchar();
z=getchar();
printf("\nTHESE ARE THE CHARACTERS ENTERED\n");
printf("%c\n %c\n %c\n",x,y,z);
return 0;
}

C PROGRAM FOR TAKING MULTIPLE CHARACHTER INPUTS

#include <stdio.h>
int main () {
char x,y,z;
printf("PLEASE ENTER 3 CHARACTERS");
scanf("%c%c%c",&x,&y,&z);
printf("THE CHARACTERs ENTERED ARE AS FOLLOW:\n")
printf("%c\n  %c\n  %c\n  ",x,y,z);
return 0;
}

C PROGRAM FOR INITIALIZING AND PRINTING CHARACTER

#include<stdio.h>
int main() {
char x='A';
printf("%c \n",x);
return 0;
}

C PROGRAM FOR SMALLEST PRODUCT

#include<stdio.h>
int main () {
int x,y,z;
printf("Enter the three numbers:\n");
scanf("%d%d%d",&x,&y,&z);
if ((x*y<y*z) && (x*y<z*x))
{
printf("The smallest product is %d of %d and %d",x*y,x,y);
}
if ((y*z<x*z) && (y*z<x*y))
{
printf("The smallest product is %d of %d and %d",y*z,y,z);
}
if((z*x<x*y)&&(z*x<y*z))
{
printf("The smallest product is %d of %d and %d",z*x,z,x);
}
return 0;
}

C PROGRAM FOR GREATEST PRODUCT

#include<stdio.h>
int main () {
int x,y,z;
printf("Enter the three numbers:\n");
scanf("%d%d%d",&x,&y,&z);
if ((x*y>y*z) && (x*y>z*x))
{
printf("The greatest product is %d of %d and %d",x*y,x,y);
}
if ((y*z>x*z) && (y*z>x*y))
{
printf("The greatest product is %d of %d and %d",y*z,y,z);
}
if((z*x>x*y)&&(z*x>y*z))
{
printf("The greatest product is %d of %d and %d",z*x,z,x);
}
return 0;
}

Tuesday, January 25, 2011

C PROGRAM FOR SMALLEST SUM


#include <stdio.h>

int main() {

int x,y,z;

printf("PLEASE ENTER THE NUMBERS\n");

scanf("%d%d%d",&x,&y,&z);

if ( (x+y<x+z)  &&  (x+y<y+z)   )

{ printf("THE SUM ie %d OF %d AND %d IS SMALLEST\n",x+y,x,y); }

if ( (y+z<x+y)  &&   (y+z<x+z)  )

{printf("THE  SUM ie %d OF %d AND %d IS SMALLEST\n",y+z,y,z); }

if( (z+x<x+y )  &&    (z+x<y+z) )

{ printf("THE SUM IS %d OF %d AND %d IS SMALLEST\n",z+x,z,x); }


return 0;
}

C PROGRAM FOR GREATEST SUM

#include<stdio.h>
int main() {



int x,y,z;

printf("PLEASE ENTER THE NUMBERS\n");

scanf("%d%d%d",&x,&y,&z);

if ( (x+y>x+z)  &&  (x+y>y+z)   )

{ printf("THE SUM ie %d OF %d AND %d IS GREATEST\n",x+y,x,y); }

if ( (y+z>x+y)  &&   (y+z>x+z)  )

{ printf("THE  SUM ie %d OF %d AND %d IS GREATEST\n",y+z,y,z); }

if( (z+x>x+y )  &&    (z+x>y+z) )

{ printf("THE SUM IS %d OF %d AND %d IS GREATEST\n",z+x,z,x); }

return 0;
}

C PROGRAM FOR SMALLEST NUMBER

#include <stdio.h>
int main () {

int x,y,z;

printf("ENTER THE THREE NUMBERS\n");

scanf("%d%d%d",&x,&y,&z);

if (x<y && x<z)

  { printf("THE SMALLEST NUMBER IS %d\n",x);}

if (y<x && y<z)

  { printf("THE SMALLEST NUMBER IS %d\n",y); }

if (z<x && z<y)

  { printf("THE SMALLEST NUMBER IS %d\n",z); }

return 0;
}

C PROGRAM FOR GREATEST NUMBER

# include<stdio.h>

int main () {

int x,y,z;

printf("ENTER THE THREE NUMBERS\n");

scanf("%d%d%d",&x,&y,&z);

if (x>y && x>z)    // && shows that both conditions have to be true

{ printf("THE NUMBER %d IS THE GREATEST",x); }

if (y>x && y>z)  // && shows that both conditions have to be true

{ printf("THEN NUMBER %d IS THE GREATEST",y); }

if (z>x && z>y)  // && shows that both conditions have to be true

{ printf("THE NUMBER  %d IS THE GREATEST" ,z); }

return 0;
}

C PROGRAM FOR BASIC “if statement”

#include<stdio.h>
int main()  {

int x,y;

printf("ENTER THE NUMBERS\n");

scanf("%d %d",&x,&y);

if(x>y)

      {printf("THE NUMBER ENTERED FIRST IS GREATER THAN THE SECOND ie %d\n",x);

       }

if (y>x)

      {printf("THE NUMBER ENTERED SECOND IS GREATER THAN THE FIRST ie %d\n",y);

       }

return 0;
}

C PROGRAM FOR CALCULATING REMAINDER

The following code will print the remainder as a result of two numbers
#include <stdio.h>
int main() {

int x,y,z;

printf("ENTER THE NUMBER TO BE DIVIDED\n");

scanf(“%d”,&x);

printf("ENTER THE DIVISOR\n");

scanf("%d",&y);

z=x%y;

printf("THE REMAINDER IS %d\n",z);

return 0;
}

C PROGRAM FOR SUM DIFFERENCE MULTIPLICATION DIVISION IN FLOAT

#include<stdio.h>
int main () {

float x,y,sum,difference,product,division;

printf("ENTER THE NUMBERS\n");

scanf("%d%d",&x,&y);

sum=x+y;

difference=x-y;

product=x*y;

division=x/y;

printf("THE SUM IS : %d\n",sum);

printf("THE DIFFERENCE IS : %d\n",difference);

printf("THE PRODUCT IS : %d\n",product);

printf("THE DIVISION RESULT IS %d\n",division);

return 0;
}

C PROGRAM FOR DIVISION

#include<stdio.h>

int main() {

int x,y,division;

printf("ENTER THE NUMBERS\n");

scanf("%d%d",&x,&y);

division=x/y;

printf("THE DIVISION OF TWO NUMBERS IS %d\n",division);

return 0;
}

C PROGRAM FOR SIMPLE MULTIPLICATION

#include<stdio.h>

int main () {

int x,y,product;

printf("ENTER THE NUMBERS\n");

scanf("%d%d",&x,&y);

product=x*y;

printf("THE PRODUCT OF TWO NUMBERS IS %d\n",product);

return 0;
}

C PROGRAM FOR SIMPLE SUBTRACTION

#include<stdio.h>

int main () {

int x,y,difference;

printf("ENTER THE NUMBERS:\n");

scanf("%d%d",&x,&y);

difference=x-y;

printf("THE DIFFERENCE OF TWO NUMBERS IS %d\n",difference);

return 0;
}

C PROGRAM FOR BASIC ADDITION

#include<stdio.h>

int main() {

int x,y,sum;

printf("PLEASE ENTER NUMBERS:\n");

scanf("%d %d",&x,&y);

sum=x+y;

printf("THE SUM OF NUMBERS ENTERED IS %d\n",sum);

return 0;
}

C PROGRAM TO RECEIVE MULTIPLE INPUTS

The following code represents basic way to receive multiple inputs from user.It depends on the number of variables initialized. At this stage more variables initialized more inputs  can be take from user.

#include <stdio.h>

int main () {

int a,b,c,d,e;

printf("PLEASE ENTER 5 NUMBERS\n");

scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);

printf("YOU HAVE ENTERED FOLLOWING NUMBERS:\n");

printf("First=%d \nSecond=%d \nThird=%d \nFourth=%d \nFifth=%d\n ",a,b,c,d,e);

return 0;
}

C PROGRAM FOR SIMPLE SCANF

The following code represents the simple use of “scanf” to get user input.
#include <stdio.h>
int main () {
int x;
printf("PLEASE ENTER A NUMBER\n");
scanf("%d",&x);
printf("%d\n",x);
return 0;
}

C PROGRAM FOR SIMPLE PRINTF

The following codes represents the basic use of printf function.

#include<stdio.h>

int main() {

printf( "HELLO TO THE WORLD OF C \n" );

return 0;
}
Related Posts with Thumbnails