Saturday 15 November 2014

Programme of Function

#include<stdio.h>
#include<conio.h>
void swaping(int *,int *);

main()
{
    int a,b;
    //clrscr();
    printf("Enter value of A and B");
    scanf("%d %d",&a,&b);
    swaping(&a,&b);
    printf("After swapping value of A and B is %d and %d",a,b);
    //getch();


}
void swaping(int *x,int *y)
{
   int temp=0;
   temp=*x;
   *x=*y;
   *y=temp;
}


#include<stdio.h>
#include<conio.h>
void ncr(int ,int );
int fact(int);
main()
{
    int n,r;
    //clrscr();
    printf("Enter value of N and R");
    scanf("%d %d",&n,&r);
    ncr(n,r);

    //getch();


}
void ncr(int x,int y)
{
   float ans;

   ans=fact(x)/(fact(y)*fact(x-y));
   printf("%dC%d is %f",x,y,ans);
}
int fact(int p)
{
    int f=1,i;
    for(i=1;i<=p;i++)
    {
        f=f*i;
    }
    return f;

}



    #include<stdio.h>
    int Fibonacci(int);
     main()
    {
    int n, i = 0, c;
    scanf("%d",&n);
    printf("Fibonacci series\n");
    for ( c = 1 ; c <= n ; c++ )
    {
    printf("%d\n", Fibonacci(i));
    i++;
    }
    return 0;
    }
    int Fibonacci(int n)
    {
    if ( n == 0 )
    return 0;
    else if ( n == 1 )
    return 1;
    else
    return ( Fibonacci(n-1) + Fibonacci(n-2) );
    }


#include<stdio.h>
#include<conio.h>
void maxmin(int [] ,int );

main()
{
    int n,a[20],i;
    //clrscr();
    printf("Enter value size of Array");
    scanf("%d",&n);

    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    maxmin(a,n);

    //getch();
}
void maxmin(int x[],int n)
{
   int i,max,min;

   max=x[0];
   min=x[0];
   for(i=0;i<n;i++)
   {
       if(max<x[i])
       {
           max=x[i];
       }
       if(min>x[i])
       {
           min =x[i];
       }

   }
   printf("Minimum and Maximum number in given array is %d and %d",max,min);

}


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

int fibo(int);
int strlen(char []);
void strrev(char []);
main()
{
    char  s[20],s2[20];

    //clrscr();
    printf("Enter any string ");
    gets(s);
    strrev(s);

    //getch();


}
int strlen(char p[])
{
    int i,length=0;

    for(i=0;p[i] != '\0';i++)
    {

        length++;
    }
    return length;

}
void strrev(char s[])
{
    int length,i,j;
    char revstr[20]="";
    length=strlen(s);
j=0;
    for(i=length-1;i>=0;i--)
    {

        revstr[i]=s[j];
        j++;
    }
printf("Reverse of %s is %s",s,revstr);

}


#include <stdio.h>



int sum (int a);



int main()

{

    int num, result;



    printf("Enter the number: ");

    scanf("%d", &num);

    result = sum(num);

    printf("Sum of digits in %d is %d\n", num, result);

    return 0;

}



int sum (int num)

{
    int x;
    if (num == 0)

    {
        x=0;
       return x;

    }

    else

    {

        x=num % 10 + sum (num / 10);

       return x;

    }

}

Wednesday 15 October 2014

Character Array Basic Introduction

What are Strings
The way a group of integers can be stored in an integer array, similarly a group of characters can be stored in a character array. Character arrays are many a time also called strings. Many languages internally treat strings as character arrays, but somehow conceal this fact from the programmer. Character arrays or strings are used by programming languages to manipulate text such as words and sentences. A string constant is a one-dimensional array of characters terminated by a null ( ‘\0’ ). For example, char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ; Each character in the array occupies one byte of memory and the last character is always ‘\0’. What character is this? It looks like two characters, but it is actually only one character, with the \ indicating that what follows it is something special. ‘\0’ is called null character. Note that ‘\0’ and ‘0’ are not same. ASCII value of ‘\0’ is 0, whereas ASCII value of ‘0’ is 48. Figure shows the way a character array is stored in memory. Note that the elements of the character array are stored in contiguous memory locations. The terminating null (‘\0’) is important, because it is the only way the functions that work with a string can know where the string ends. In fact, a string not terminated by a ‘\0’ is not really a string, but merely a collection of characters. 

C concedes the fact that you would use strings very often and hence provides a shortcut for initializing strings. For example, the string used above can also be initialized as, char name[ ] = "HAESLER" ; Note that, in this declaration ‘\0’ is not necessary. C inserts the null character automatically. 

Wednesday 10 September 2014

Control Structures in C:

Control Structures in C:
Normally statements in C program are executed sequentially i.e in the order in which they are written. This is called sequential execution. We can transfer the control point to a desired location is possible with control structures. C allows many kinds of control statements.
I. Conditional(decision ) control structures
· if
· if –else
· if-elseif – else
· nested if
II. Jumping(branching) control structures
· goto
· break
· return
· continue
III. Loop(iterative) control structures
· for loop
· while loop
· do - while loop
IV. Multi way conditional(case) control structures
· switch- case
Conditional Control Structures:
If: if is also called as conditional statement in if statements get executed only when the condition is true, it can terminate when the condition becomes false.
Syntax:
if (condition)
{
        ………..
        …statements…
        ………….
}

if –else: in if-else conditional control statement, statements in if block gets executed only when the condition is true and statements in else block gets executed only when the condition is false.

Syntax:
if (condition)
{
            statements
}
else
{
             statements
}

if –else if-else: in this statement statements in loops gets executed when the corresponding conditions are true. Statements in final else block gets executed 
when all other conditions are false. We can use any no. of else-if blocks between if and else.

Syntax:
if (condition1)
{
       statements
}
else if(condition2)
{
         statements
}
else if(condition3)
{
        statements
}
….
else
{
statements
}

nested if : writing the if statement with in another if is called as nested if. Inner if is processed only when outer if condition is true. Hence statements of inner if gets executed when outer if and inner if conditions are true.

Syntax:
if (condition1)
{
if(condition2)
{
statements
}
else
{
statements
}
}
else
   statements

II. Jumping Control Structures:

goto :
goto os a kind of branching structure. It moves the control (moves
forward or back)to label. goto is condition dependent.
In above goto forward statements2 gets omitted because after executing
statements1 goto moves the control to label statements.
In goto back after executing statement1, statements2 repeated more times
depends on condition(goto transfers to label, if condition is true only).

Syntax1 : goto back syntax: goto forward
    ……..
…statements1..
   ..
label:
   ..statements2
    ..
if(condition)
         goto label;
..
EXAMPLE:
i=0;
abc:
printf(“hello”);
i++;
if(i<10)
goto abc;
……statemnts1..
if(condition)
goto label;
..
.. statemnts2..
label:
…….
…..
EXAMPLE:
i= -3;
if(x>0)
goto abc;
x=-x;
abc:
printf(“%d”,x);

Break :
Break quits the corresponding iterative loop statements, break is valid
only for loop statements and switch case .
……..
……..
return :
return is used in functions. It moves the control to calling function from
the called function module. Return is also return values to the point where the
function is called.
Ex: main( )
{
int a=10,b=20;
printf(“%d”,sum(x,y);
getch( );
}
int sum(int x, int y)
{
return x+y;
}
Iterative (loop) control statements :

for loop :
in for loop statements get executed as long as condition is true. For loop
contains three expressions, expression1 includes initializing the variables and
expression 2 includes increment or decrement of initialized variable.

Syntax:
for( expression1; condition; expression2)
{
statements;
}
example :
for(i=1;i<=10;i++)
printf(“hello”); prints hello 10 times.
….
….
break;
…..
…..
EXAMPLE:

for(i=1;i<10;i++)
{
printf(“hello”);
if(i==5)
break;
}
Prints 5 times only

While loop :
In while loop statements get executed as long as condition is true. In while it checks the condition first and executes the statements later. So minimum no. of execution times of statements is 0.

Syntax:

While(condition)
{
statements;
}

EXAMPLE:

i=1;
while(i<=10)
{
printf(“hello”); prints hello 10 times.
i++;
}
do while loop:
In do while loop statements get executed as long as condition is true. In do while it executes the statements first and checks the condition later. So minimum no. of execution times of statements is 1.
Syntax:
do
{
….
statements;
….
}while(condition);

EXAMPLE:

i=1;
do
{
printf(“hello”); prints hello 10 times.
i++;
} while(i<=10);

multi-way conditional control statement:

switch case:
switch case is similar ti else if. In switch case statements get executed when corresponding case constants are true only(which have been mentioned match with the value of variable in switch). Control point comes to default when all the cases are false.
startcondition statementstruefalseendstartstatements conditiontruefalseend

Syntax:
Switch(variable/expression)
{
case constant1:statements1;
break:
case constant2: statements2;
break:
case constant3: statements3;
break:
default: statements;
break:
}
EXAMPLES:

program to perform arithmetic operators using switch case.
main( )
{
char op;
int a=10,b=5;
clrscr( );
printf(“enter your operator +,-,*,/,%”);
scanf(“%c”,&op);
switch(op)
{
case ‘+’: printf(“sum=%d”,a+b);
break;
case ‘-’: printf(“difference=%d”,a-b);
break;
case ‘*’: printf(“mul=%d”,a*b);
break;
case ‘/’: printf(“div=%d”,a/b);
break;
case ‘%’: printf(“rim=%d”,a%b);
break;
default: printf(“your option is wrong”;
break;
}
getch( );
}
start
Case 1 Statements 1
true
end
Case 2
default
false
false
true
Statements 2
Default statements

Types of errors

Different types of errors:
Error is a mistake or bug, which can be associated with programmer in
program, common programming errors in C can be classified into 3 types:
1. compilation errors.(syntax errors)
2. linker errors.
3. logical errors.
Compilation(syntax ) errors: these are raised when we compile the
program and can be located and corrected easily. Most common
compilation or syntax errors are.
· Undefined variable
· Redeclaration of variable
· Unterminated string character
· Missing semicolon ;
· Function call missing ( ,;”)
· Function should have prototype.
Linker errors: the program must be linked to the ‘C’ library. If it fails in
such case these errors are raised . most common errors are:
· Unable to link cos.obj
· Undefined symbol
Logical ( run time) errors: these are raised because of the due to logical
inefficiency. We can know them when program gets executed. It is very
difficult to locate them, most common logical errors are:
· Divide by zero
· Floating point error
· Null value

· Garbage result in printing.

C Tokens

Character set of C Language:
C compiler allows to use many no. of characters :
Lower case letters : a b c … z
Upper case letters : A B C….Z
Digits : 0 1 2 3…9
Other characters : + - * ( ) & % $ # { } [ ]’ “ : ; etc.
White space characters : blank, new line, tab space etc.
Conversion Characters( format specifiers):
Conversion characters or format specifiers are used to provide the format
for the value to be print.. it has a prefix ‘ % ‘ and followed by a specifier.
%d : prints integer
%f : prints float and double
%c : prints character
%s : prints string
%o : prints octal value
%u : prints unsigned integer

%x : prints hexa decimal value

Escape Sequences:
Escape sequences are used in input and output functions such as printf
and scanf. Which has ‘\’ and a following character.
\n à new line
\t à horizental tab
\v à vertical tab
\b à back space
\? àquestion mark
\” à double quote

Data type Memory Format specifier
int 2 bytes %d, %i
char 1 bytes %c
float 4 bytes %f
double 8 bytes %f
string Size of char array %s
Unsigned int 2 bytes %u
Long unsingned 8 bytes %lu
long 4 bytes %ld

Differences between variables and identifiers :
Variables are tokens defined by user and used in programming. It must
start with a letter or underscore(_), it can’t include spaces, it can contain
digits.
Valid invalid
int x int 3x
float pi float pi+var
int a_b inta.b
the names of variables, functions, labels and other user defined functions
are called as identifiers.

All identifiers are not variables All variables are identifiers Identifier may not have any
memory unless it is a variable All variables have memory Mentioning the type of an
identifier is not needed unless it is a variable. Type of the variable must be defined.

Features/Characteristics of C language

C Programming is widely used in Computer Technology, We can say that C is
inspiration for development of other languages. We can use C for different purposes.
Below are some of the Features of C Programming –
Features of C
Low Level Language Support Program Portability
Powerful and Feature Rich Bit Manipulation
High Level Features Modular Programming
Efficient Use of Pointers

1 . Low Level Features :


  •  C Programming provides low level features that are generally provided by the Lower level languages. C is Closely Related to Lower level Language such as “Assembly Language“.
  •  It is easier to write assembly language codes in C programming.

2 . Portability :

  •  C Programs are portable i.e they can be run on any Compiler with Little or no
  • Modification
  •  Compiler and Preprocessor make it Possible for C Program to run it on
  • Different PC

3 . Powerful


  •  Provides Wide verity of ‘Data Types‘
  •  Provides Wide verity of ‘Functions’
  •  Provides useful Control & Loop Control Statements

4 . Bit Manipulation


  •  C Programs can be manipulated using bits. We can perform different operations
  • at bit level. We can manage memry representation at bit level. [Eg. We can use Structure to manage Memory at Bit Level]
  • It provides wide verity of bit manipulation Operators. We have bitwise
  • operators to manage Data at bit level.

5 . High Level Features :


  • It is more User friendly as compare to Previous languages. Previous languages such as BCPL,Pascal and other programming languages never provide such great features to manage data.
  •  Previous languages have there pros and cons but C Programming collected all useful features of previous languages thus C become more effective language.

6 . Modular Programming


  •  Modular programming is a software design technique that increases the extent to which software is composed of separate parts, called modules
  •  C Program Consist of Different Modules that are integrated together to form complete program

7 . Efficient Use of Pointers

  •  Pointers has direct access to memory.
  •  C Supports efficient use of pointer 

Monday 18 August 2014

Compilation Process of C language



Like any programming language, C by itself is completely incomprehensible to a microprocessor. Its purpose is to provide an intuitive way for humans to provide instructions that can be easily converted into machine code that is comprehensible to a microprocessor. The compiler is what takes this code, and translates it into the machine code.


To those new to programming, this seems fairly simple. A naive compiler might read in every source file, translate everything into machine code, and write out an executable. This could work, but has two serious problems. First, for a large project, the computer may not have enough memory to read all of the source code at once. Second, if you make a change to a single source file, you would rather not have to recompile the entire application.

To deal with these problems, compilers break their job down into steps; for each source file (each .c file), the compiler reads the file, reads the files it references with #include, and translates it to machine code. The result of this is an "object file" (.o). Once every object file is made, a "linker" collects all of the object files and writes the actual program. This way, if you change one source file, only that file needs to be recompiled and then the application needs to be re-linked.


Without going into the painful details, it can be beneficial to have a superficial understanding of the compilation process.


Preprocessor

The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control. Many times you will need to give special instructions to your compiler. This is done by inserting preprocessor directives into your code. When you begin compiling your code, a special program called the preprocessor scans the source code and performs simple substitution of tokenized strings for others according to predefined rules. The preprocessor is not a part of the C language.
In C language, all preprocessor directives begin with the pound character (#). You can see one preprocessor directive in the Hello world program introduced in A taste of C:

Example:
#include <stdio.h>
This directive causes the header to be included into your program. Other directives such as #pragma control compiler settings and macros. The result of the preprocessing stage is a text string. You can think of the preprocessor as a non-interactive text editor that prepares your code for the compilation step. The language of preprocessor directives is agnostic to the grammar of C, so the C preprocessor can also be used independently to process other kinds of text files.

Syntax Checking

This step ensures that the code is valid and will sequence into an executable program. Under most compilers, you may get messages or warnings indicating potential issues with your program (such as a statement always being true or false, etc.)

When an error is detected in the program, the compiler will normally report the file name and line that is preventing compilation.

Object Code

The compiler produces a machine code equivalent of the source code that can then be linked into the final program. The code itself can't be executed yet, as it has to complete the linking stage.


It's important to note after discussing the basics that compilation is a "one way street". That is, compiling a C source file into machine code is easy, but "decompiling" (turning machine code into the C source that creates it) is not. Decompilers for C do exist, but they rarely create useful code.

Linking

Linking combines the separate object codes into one complete program by integrating libraries and the code and producing either an executable program or a library. Linking is performed by a linker, which is often part of a compiler.
Common errors during this stage are either missing functions, or duplicate functions.

Wednesday 13 August 2014

Example of Various Algorithms


* Sum of n natural numbers */

1. Read the value of n.
2. i = 1 , SUM = 0
3. if ( i > n ) go to 7
4. S = S + i
5. i = i + 1
6. go to 3
7. Display the value of S
8. Stop

/* Factorial of n numbers */


1. Read the value of n.
2. i = 1 , F =1
3. if ( i > n ) go to 7
4. F = F * i
5. i = i + 1
6. go to 3
7. Display the value of S
8. Stop

/* To Find the value of xn */

1. Read the value of n.
2. i = 1 , m = 1
3. If i > n then go to 7
4. m = m * x
5. i = i + 1
6. go to 3
7. Display m
8. Stop