Showing posts with label c -programming. Show all posts
Showing posts with label c -programming. Show all posts

C Program to solve Tower of Hanoi Problem Using Recursion


This C Program uses recursive function to solve tower of hanoi problem.The tower of hanoi is a mathematical puzzle problem.It is also a great example of recursion.
It consists of three rods, and a number of disks of different sizes.While transferring disk from one rod other, larger disk can't be at the top of smaller disk.
We have to obtain the same stack on the third rod as in the first rod below:
tower of hanoi
Here is the source code of the C Program for solving towers of hanoi problem.It was successfully compiled and run in Dev C++.

Source Code:
#include<stdio.h>
void toh(int,char,char,char);
void main()
{
int n;
printf("Enter no. of disks:\n");
scanf("%d",&n);
printf("The steps to solve toh are:\n");
toh(n,'A','B','C');
}
void toh(int n,char frompeg,char auxpeg,char topeg)
{
if(n==1)
{
printf("Move disk 1 from peg %c to peg %c.",frompeg,topeg);
return;
}
toh(n-1,frompeg,topeg,auxpeg);
printf("\nMove disk %d from peg %c to peg %c.\n",n,frompeg,topeg);
toh(n-1,auxpeg,frompeg,topeg);
}
//www.sparajuli.com.np

C Program to convert Infix To Postfix Expression Using Stack


This is a  short, easy to understand and functional C Program which converts Infix Expression to Postfix Expression.i.e. (a+b)*c/(d-e)+f   To  ab+cde-/*f+.

Source Code:
#include<ctype.h>
#include<stdio.h>
void push(char elem);
int pr(char elem);
char pop();
char infx[50],pofx[50],ch,elem,s[50];
int top=-1;       /* Global declarations */
void main()
{                         /* Main Program */
    int i=0,k=0;
    push('#');
    printf("\nEnter the Infix Expression: ");
    scanf("%s",infx);
    while( (ch=infx[i++]) != '\0')
    {
        if( ch == '(')
push(ch);
        else if(isalnum(ch))
pofx[k++]=ch;
            else if( ch == ')')
                {
                    while( s[top] != '(')
                        pofx[k++]=pop();
                    elem=pop(); /* Remove ( */
                }
                else
                {       /* Operator */
                    while( pr(s[top]) >= pr(ch) )
                        pofx[k++]=pop();
                    push(ch);
                }
    }
    while( s[top] != '#')     /* Pop from stack till empty */
        pofx[k++]=pop();
    pofx[k]='\0';          /* Make pofx as valid string */
    printf("\n\nInfix Expression: %s\nPostfix Expression: %s\n",infx,pofx);
}
void push(char elem)
{                       /* Function for PUSH operation */
    s[++top]=elem;
}

char pop()
{                      /* Function for POP operation */
    return(s[top--]);
}
int pr(char elem)
{                 /* Function for precedence */
    switch(elem)
    {
    case '#': return 0;break;
    case '(': return 1;break;
    case '+': return 2;break;
    case '-': return 2;break;
    case '*': return 3;break;
    case '/': return 4;break;
    }
}
//www.sparajuli.com.np/

This program is successfully compiled and run in Dev C++ and working.If you have any query, ask below in comment section.

(DMA)Dynamic Memory Allocation in C - Explained with examples


The size of array you have declared initially can be sometimes insufficient and sometimes more than required.Dynamic memory allocation allows us to allocate additional more memory space or to release unwanted space at run time, thus optimizes the use of storage space.

There are 4 library functions under "stdlib.h" for dynamic memory allocation:
  1. malloc(); - Allocates requested size of bytes and returns a pointer to first byte of allocated space.
  2. calloc(); - Allocates space for an array elements, initializes to zero and then returns a pointer to memory.
  3. free(); - frees the previously allocated space.
  4. realloc(); - Change the size of previously allocated space.
1.malloc();
The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and returns a pointer of type void which can be casted into pointer of any form.
Syntax of malloc();

ptr=(cast-type*)malloc(byte-size);
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
 For example:
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory.

2.calloc();

The name calloc stands for "contiguous allocation".The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.
 Syntax of calloc();

ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements. 
For example:
 ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.

3.free();

Dynamically allocated memory with either calloc() or malloc() does not get return on its own.The programmer must use free() explicitly to release space.
 syntax of free();

free(ptr);
This statement cause the space in memory pointed by ptr to be free. 

4.realloc();

If the previously allocated memory is insufficient or more than sufficient.Then, you can change memory size previously allocated using realloc().
 Syntax of realloc();

ptr=realloc(ptr,newsize);
Here, ptr is reallocated with size of newsize.

Have a look at following example to understand DMA in C which uses all four functions of DMA:

Q.Write a menu driven program to perform following operations in Array using DMA(Dynamic Memory Allocation):
1.Insert     4.Display
2.Search   5.Exit.
3.Delete
Solution:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
    char *p,d,t;
    int s,i,a,c;
    printf("Enter 1D array size:\n");
    scanf("%d",&s);
    p=(char*)malloc(s*sizeof(char));
    printf("Enter array elements(char):\n");
    for(i=0;i<s;i++)
    {
       scanf("%s",&p[i]);
    }
    do
    {
       system("cls");
       printf("Choose option for Array Operation:\n1-Insert\n2-Search\n3-Delete\n4-Display\n5-Exit.\n");
       scanf("%d",&c);
       switch(c)
      {
       case 1:
       system("cls");
       printf("After which position you want to insert?\n");
       scanf("%d",&a);
       if(a>s-1)
      {
         printf("Invalid position!\a");
         break;
      }
      printf("What you want to insert?\n");
      scanf("%s",&d);
      p=(char*)realloc(p,s++);
      for(i=s-1;i>a+1;i--)
      {
        p[i]=p[i-1];
      }
      p[a+1]=d;
      printf("Your array elements after insertion are:\n");
      for(i=0;i<s;i++)
     {
        printf("%c ",p[i]);
     }
     break;
     case 2:
     system("cls");
     printf("What you want to search?\n");
     scanf("%s",&t);
     printf("Your element is at following location of array:\n");
     for(i=0;i<s;i++)
     {
        if(p[i]==t)
       {
          printf("%d,",i);
       }
      }
      break;
      case 3:
      system("cls");
      printf("Which position element you want to delete?\n");
      scanf("%d",&a);
      if(a>s-1)
     {
        printf("Invalid position!\a");
        break;
      }
      for(i=a;i<s-1;i++)
      {
         p[i]=p[i+1];
      }
      s--;
      p=(char*)realloc(p,s);
      printf("Your number is deleted!");
      break;
      case 4:
      system("cls");
      printf("The elements in array are:\n");
      for(i=0;i<s;i++)
     {
        printf("%c ",p[i]);
     }
     break;
     case 5:
      exit(0);
     default:
     printf("Your choice is wrong.");
     break;
   }
   getch();
   fflush(stdin);
   }while(1);

}
--------------------------------------------------------------------------------------------------------------------------
Don't forget to comment below if you have still any confusions.

Keywords and Identifiers in C Programming


Keywords:


Keywords are the reserved words used in programming. Each keywords has fixed meaning and that can't be changed by user. For e.g: int book;
Here, int is a keyword that indicates, 'book' is of type integer.
As, C programming is case sensitive, all keywords must be written in lowercase. Here is the list of all keywords predefined by ANSI C.

Keywords in C Language:

auto        double                  int                          struct
break      else                       long                       switch
case        enum                    register                  typedef
char        extern                   return                     union
for          signed                   void                        continue
do            if                           static                     while
default    goto                      sizeof                    volatile
const      float                      short                      unsigned

Besides these keywords, there are some additional keywords supported by Turbo C.
Additional Keywords for Borland C:

asm ,far, interrupt ,pascal ,near, huge, cdecl

Identifiers:

In C programming, identifiers are names given to C entities, such as variables, functions, structures etc. Identifier are created to give unique name to C entities to identify it during the execution of program. For example:

int money;
int mango_tree;
Here, ‘money’ is a identifier which denotes a variable of type integer. Similarly, ‘mango_tree’ is another identifier, which denotes another variable of type integer.

Rules for writing identifier:

An identifier can be composed of letters (both uppercase and lowercase letters), digits and underscore '_' only.
The first letter of identifier should be either a letter or an underscore. But, it is discouraged to start an identifier name with an underscore though it is legal. It is because, identifier that starts with underscore can conflict with system names. In such cases, compiler will complain about it. Some system names that start with underscore are _fileno, _iob, _wfopen etc.
There is no rule for the length of an identifier. However, the first 31 characters of an identifier are discriminated by the compiler. So, the first 31 letters of two identifiers in a program should be different.

Tips for Good Programming Practice :
Programmer can choose the name of identifier whatever they want. However, if the programmer choose meaningful name for an identifier, it will be easy to understand and work on, particularly in case of large program.

C Programming - Operators


Operators are the symbol which operates on value or a variable. For example: + is a operator to perform addition.
C programming language has wide range of operators to perform various operations. For better understanding of operators, these operators can be classified as:

Operators in C programming:

Arithmetic Operators
Increment and Decrement Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Special Operators

Arithmetic Operators :

Operators          Meaning of Operator
+                           addition or unary plus
-                            subtraction or  unary minus
*                            multiplication
/                            division
%                          remainder after division (modulo division)

Example of working of arithmetic operators:

/* Program to demonstrate the working of arithmetic operators in C.  */
#include <stdio.h>
int main()
{
    int a=9,b=4,c;
    c=a+b;
    printf("a+b=%d\n",c);
    c=a-b;
    printf("a-b=%d\n",c);
    c=a*b;
    printf("a*b=%d\n",c);
    c=a/b;
    printf("a/b=%d\n",c);
    c=a%b;
    printf("Remainder when a divided by b=%d\n",c);
    return 0;
}

a+b=13
a-b=5
a*b=36
a/b=2
Remainder when a divided by b=1

Explanation:

Here, the operators +, - and * performed normally as you expected. In normal calculation, 9/4 equals to 2.25. But, the output is 2 in this program. It is because, a and b are both integers. So, the output is also integer and the compiler neglects the term after decimal point and shows answer 2 instead of 2.25. And, finally a%b is 1,i.e. ,when a=9 is divided by b=4, remainder is 1.

Suppose a=5.0, b=2.0, c=5 and d=2
In C programming,
a/b=2.5    
a/d=2.5
c/b=2.5      
c/d=2
Note: % operator can only be used with integers.

Increment and decrement operators:

In C, ++ and -- are called increment and decrement operators respectively. Both of these operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and -- subtracts 1 to operand respectively. For example:

Let a=5 and b=10
a++;  //a becomes 6
a--;  //a becomes 5
++a;  //a becomes 6
--a;  //a becomes 5 
Difference between ++ and -- operator as postfix and prefix:

When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return it but, if ++ is used as postfix(like: var++), operator will return the value of operand first and then only increment it. This can be demonstrated by an example:

#include <stdio.h>
int main()
{
    int c=2,d=2;
    printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3.
    printf("%d",++c);   //this statement increments 1 to c then, only c is displayed. 
    return 0;
}

Output:

2
4

Assignment Operators:



The most common assignment operator is =. This operator assigns the value in right side to the left side. For example:

var=5  //5 is assigned to var
a=c;   //value of c is assigned to a
5=c;   // Error! 5 is a constant.
Operator Example Same as
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b

Relational Operator:

Relational operators checks relationship between two operands. If the relation is true, it returns value 1 and if the relation is false, it returns value 0. For example:

a>b
Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0.

Relational operators are used in decision making and loops in C programming.

Operators             Meaning of Operator                                   Example
==                           Equal to                                                           5==3 returns false (0)
>                             Greater than                                                    5>3 returns true (1)
<                             Less than                                                          5<3 returns false (0)
!=                            Not equal to                                                     5!=3 returns true(1)
>=                           Greater than or equal to                                  5>=3 returns true (1)
<=                           Less than or equal to                                       5<=3 return false (0)

Logical Operators:

Logical operators are used to combine expressions containing relation operators. In C, there are 3 logical operators:

Operators           Meaning of Operator         Example
&&                       Logial AND                         If c=5 and d=2 then,((c==5) && (d>5)) returns false.
||                           Logical OR                          If c=5 and d=2 then, ((c==5) || (d>5)) returns true.
!                            Logical NOT                        If c=5 then, !(c==5) returns false.

Explanation:

For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true, either the expression should be true. Since, (c==5) is true. So, the expression is true. Since, expression (c==5) is true, !(c==5) is false.

Conditional Operator:

Conditional operator takes three operands and consists of two symbols ? and : . Conditional operators are used for decision making in C. For example:

c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.

Bitwise Operators:

A bitwise operator works on each bit of data. Bitwise operators are used in bit level programming.

Operators             Meaning of operators
&                            Bitwise AND
|                             Bitwise OR
^                             Bitwise exclusive OR
~                             Bitwise complement
<<                           Shift left
>>                           Shift right

Bitwise operator is advance topic in  programming . Learn more about bitwise operator in C programming.

Other Operators:

Comma Operator:
Comma operators are used to link related expressions together. For example:

int a,c=5,d;
The sizeof operator
It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc. For example:

#include <stdio.h>
int main()
{
    int a;
    float b;
    double c;
    char d;
    printf("Size of int=%d bytes\n",sizeof(a));
    printf("Size of float=%d bytes\n",sizeof(b));
    printf("Size of double=%d bytes\n",sizeof(c));
    printf("Size of char=%d byte\n",sizeof(d));
    return 0;
}
Output:

Size of int=4 bytes
Size of float=4 bytes
Size of double=8 bytes
Size of char=1 byte

Conditional operators (?:)

Conditional operators are used in decision making in C programming, i.e, executes different statements according to test condition whether it is either true or false.

Syntax of conditional operators:
conditional_expression?expression1:expression2
If the test condition is true, expression1 is returned and if false expression2 is returned.

Example of conditional operator:

#include <stdio.h>
int main()
{
   char feb;
   int days;
   printf("Enter l if the year is leap year otherwise enter 0: ");
   scanf("%c",&feb);
   days=(feb=='l')?29:28;
   /*If test condition (feb=='l') is true, days will be equal to 29. */
   /*If test condition (feb=='l') is false, days will be equal to 28. */ 
   printf("Number of days in February = %d",days);
   return 0;
}
Output:

Enter l if the year is leap year otherwise enter n: l
Number of days in February = 29
Other operators such as &(reference operator), *(dereference operator) and ->(member selection) operator will be discussed in pointer chapter.

Data Type in C-Programming



In C, variable(data) should be declared before it can be used in program. Data types are the keywords, which are used for assigning a type to a variable.
Data types in C:

Fundamental Data Types:
     Integer types
     Floating Type
     Character types
Derived Data Types:
     Arrays
     Pointers
     Structures
     Enumeration

Syntax for declaration of a variable:
   data_type variable_name;
For e.g:
   int book;

Integer data types:

Keyword int is used for declaring the variable with integer type. For example:

int var1;

Here, var1 is a variable of type integer.

The size of int is either 2 bytes(In older PC's) or 4 bytes. If you consider an integer having size of 4 byte( equal to 32 bits), it can take 232 distinct states as: -231,-231+1, ...,-2, -1, 0, 1, 2, ..., 231-2, 231-1

Similarly, int of 2 bytes, it can take 216 distinct states from -215 to 215-1. If you try to store larger number than 231-1, i.e,+2147483647 and smaller number than -231, i.e, -2147483648,  program will not run correctly.

Floating types:

Variables of floating types can hold real values(numbers) such as: 2.34, -9.382 etc. Keywords either float or double is used for declaring floating type variable. For example:

float var2;
double var3;
Here, both var2 and var3 are floating type variables.
In C, floating values can be represented in exponential form as well. For example:

float var3=22.442e2;

Difference between float and double:

Generally the size of float(Single precision float data type) is 4 bytes and that of double(Double precision float data type) is 8 bytes. Floating point variables has a precision of 6 digits whereas the the precision of double is 14 digits.

Note: Precision describes the number of significant decimal places that a floating values carries.

Character types:

Keyword char is used for declaring the variable of character type. For example:
char var4='h';

Here, var4 is a variable of type character which is storing a character 'h'.
The size of char is 1 byte. The character data type consists of ASCII characters. Each character is given a specific value. For example:

For, 'a', value =97
For, 'b', value=98
For, 'A', value=65
For, '&', value=33
For, '2', value=49
Here is the list of all ASCII characters in C language.

Qualifiers:
Qualifiers alters the meaning of base data types to yield a new data type.

Size qualifiers:

Size qualifiers alters the size of basic data type. The keywords long and short are two size qualifiers. For example:

long int i;

The size of int is either 2 bytes or 4 bytes but, when long keyword is used, that variable will be either 4 bytes of 8 bytes. Learn more about long keyword in C programming. If the larger size of  variable is not needed then, short keyword can be used in similar manner as long keyword.

Sign qualifiers:

Whether a variable can hold only positive value or both values is specified by sign qualifiers. Keywords signed and unsigned are used for sign qualifiers.

unsigned int a;
// unsigned variable can hold zero and positive values only.
It is not necessary to define variable using keyword signed because, a variable is signed by default. Sign qualifiers can be applied to only int and char data types. For a int variable of size 4 bytes it can hold data from -231 to 231-1 but, if that variable is defined unsigned, it can hold data from 0 to 232 -1.

Constant qualifiers:

Constant qualifiers can be declared with keyword const. An object declared by const cannot be modified.
const int p=20;
The value of p cannot be changed in the program.

Volatile qualifiers:
A variable should be declared volatile whenever its value can be changed by some external sources outside program. Keyword volatile is used to indicate volatile variable.



C-Programming Variables and Constants


Variables:

Variables are memory location in computer's memory to store data. To indicate the memory location, each variable should be given a unique name called identifier. Variable names are just the symbolic representation of a memory location. Examples of variable name: sum, car, count etc.
int num;
Here, num is a variable of integer type.
Rules for writing variable name in C:

Variable name can be composed of letters (both uppercase and lowercase letters), digits and underscore '_' only.
The first letter of a variable should be either a letter or an underscore. But, it is discouraged to start variable name with an underscore though it is legal. It is because, variable name that starts with underscore can conflict with system names and compiler may complain.
There is no rule for the length of length of a variable. However, the first 31 characters of  a variable are discriminated by the compiler. So, the first 31 letters of two variables in a program should be different.
In C programming, you have to declare variable before using it in the program.

Constants:

Constants are the terms that can't be changed during the execution of a program. For example: 1, 2.5, "Programming is easy." etc. In C, constants can be classified as:

Integer constants:

Integer constants are the numeric constants(constant associated with number) without any fractional part or exponential part. There are three types of integer constants in C language: decimal constant(base 10), octal constant(base 8) and hexadecimal constant(base 16) .

Decimal digits: 0 1 2 3 4 5 6 7 8 9

Octal digits: 0 1 2 3 4 5 6 7

Hexadecimal digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.

For example:

Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
Notes:
You can use small caps a, b, c, d, e, f instead of uppercase letters while writing a hexadecimal constant.
Every octal constant starts with 0 and hexadecimal constant starts with 0x in C programming.
Floating-point constants:
Floating point constants are the numeric constants that has either fractional form or exponent form. For example:
-2.0
0.0000234
-0.22E-5
Note: Here, E-5 represents 10-5. Thus, -0.22E-5 = -0.0000022.

Character constants:

Character constants are the constant which use single quotation around characters. For example: 'a', 'l', 'm', 'F' etc.
Escape Sequences:

Sometimes, it is necessary to use newline(enter), tab, quotation mark etc. in the program which either cannot be typed or has special meaning in C programming. In such cases, escape sequence are used. For example: \n is used for newline. The backslash( \ ) causes "escape" from the normal way the characters are interpreted by the compiler.

Escape Sequences:

Escape Sequences           Character
\b                                       Backspace
\f                                        Form feed
\n                                       Newline
\r                                        Return
\t                                        Horizontal tab
\v                                       Vertical tab
\\                                        Backslash
\'                                        Single quotation mark
\"                                       Double quotation mark
\?                                       Question mark
\0                                       Null character
\a                                       bell(sound)

String constants:

String constants are the constants which are enclosed in a pair of double-quote marks. For example:

"good"                                    //string constant
""                                            //null string constant
"   "                                         //string constant of three white space
"x"                                          //string constant having single character.
"Earth is round\n"                  //prints string with newline

Enumeration constants:

Keyword enum is used to declare enumeration types. For example:

enum color {yellow, green, black, white};

Here, the variable name is color and yellow, green, black and white are the enumeration constants having value 0, 1, 2 and 3 respectively by default.

Learn C programming From base to Top


Introduction:

C programming is a popular computer programming language which is widely used for system and application software. Despite being fairly old programming language, C programming is widely used because of its efficiency and control. This tutorial is targeted for beginners who does not have any prior knowledge or have very little knowledge of computer programming. All basic features of C programming language are included in detail with explanation to give you solid platform to understand C programming.

Getting Started With C ....

In order to run a C program, you need a compiler. Compiler change source code(code written by programmer) to object code(code that computer understands) and creates executable file. There are many free and professional compilers available.There are many compilers available such as Netbeans,Eclipse IDE ,DEV C++,TURBO C++ etc. All the examples here are tested and verified in DEV C++ compiler.
Lets Begin With:

Character set:
Character set are the set of alphabets, letters and some special characters that are valid in C language.
Alphabets: 

Uppercase: A B C  ....................................  X Y Z 

Lowercase: a b c  ......................................  x y z

Digits:

0 1 2 3 4 5 6  8 9

Special Characters:

,   <    >  .  _  (  )  ;  $  :   %   [  ]  #  ?  ' &  { } " ^  ! * /  |  -  \  ~  +

White space Characters:

blank space, new line, horizontal tab, carriage return and form feed