Sunday 1 November 2015

Java Program to print greatest of two numbers


Program:

import java.io.*;
import java.util.*;
class greater
{
public static void main(String[ ] args) {
System.out.println("Enter two values: ");
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
if(a>b)
System.out.println(a + " is Greater than " + b);
else
System.out.println(b + " is Greater than " + a);
}
}

Input/Output:

Enter two values:
5
6
6 is Greater than 5

Sunday 16 August 2015

C language Control statements Tutorials

Control Statements

    These statements are useful to decide which statements are executed and which statements are not to be executed and also decide the number of times that a particular set of statements are to be executed.

--> Control statements are two types:

      1) Decision control statements

      2) Loop control statements

1) Decision control statements

These statements are useful to decide which statements are to be executed and which are not to be executed. These are of two types

      i) if statement

      ii) switch case statement

--> If statements are three types.

a) if statement:

--> It is an alternative to conditional operator

   Syntax:

         if( condition )

         {

            statements

         }

--> The condition is evaluated first, If it is TRUE, then the statements in the if block get executed. After completing the execution the control transfers to the next statement and continnue the execution.

--> If it is FALSE, then the control transfers to the next statement and continue the execution.

Program:

#include< stdio.h >
#include< conio.h >
void main( )
{

      int n;
      clrscr( );
      printf("\nEnter your age: ");
      scanf("%d", &n);
      if(n>=18)
      {

         printf("\nYour are Major");

      }

      printf("\nYour are Minor");

}

--> When the if block contain only one statement, braces are optional.

b) if-else statement:

   Syntax:

         if( condition )
        {

             statements

        }
        else
        {

            statements

        }

--> The condition is evaluated first. If it is TRUE, then the statements in the if block get executed. After completing the execution the control transfers to the next statement and continue the execution.

--> It it is FALSE, then the control transfers to else block and continue the execution.

Program:

#include< stdio.h >
#include< conio.h >
void main( )
{

      int a, b;
      clrscr( );
      printf("\nEnter values of a & b: ");
      scanf("%d%d", &a, &b);
      if(a > b)
      {

               printf("%d is Bigger", a);

      }
      else
      {

               printf("%d is Bigger", b);

      }

}

--> if block should be immediately followed by else block.

--> When using if statement, specifying else block is optional.

--> It is useful when we have multiple options and we are required to select one among them.

c) else-if ladder:

   Syntax:

      if( condition 1)
      {

         statements

      }
      else if( condition 2)
      {

         statements

      }
      else if( condition 3)
      {

         statements

      }

      .

      .

      .
      else
      {

         statements

      }

--> Condition 1 is evaluated first. If it is TRUE, then the statements in the if block get executed. After completing the execution the control transfers to the next statement and continue the execution.

--> If it is FALSE, then condition 2 is evaluated and the same process is repeated.

Program:

#include< stdio.h >
#include< conio.h >
void main( )
{

      int a, b, c;
      clrscr( );
      printf("\nEnter values of a, b & c: ");
      scanf("%d%d%d", &a, &b, &c);
      if(a > b && a > c)
      {

              printf("%d is Bigger", a);

      }
      else if(b > a && b > c)
      {

              printf("%d is Bigger", b);

      }
      else
      {

              printf("%d is Bigger", c);

      }

}

Note:

--> exit( ) is the function which is used to terminate the program as required.

--> It is available in the header file stdlib.h.

--> It accepts an integer value as an argument.

--> "0" represent successful termination and nonzero value represent that some error as occur.

ii) switch case statement:

--> If statement is useful when we know range of the control variable or exact value of the control variable .

--> switch case statement is useful only when we know exact value of control variable. So, all the program that use switch case statement can also be implimented using if statement, but the reverse is not possible.

   Syntax:

      switch(variable/expression)
      {

            case < values > : statements
                                       break;
            case < values > : statements
                                       break;

            .

            .

            .

            .

            default: statements

      }

--> By using switch statement we can specify only control variable or expression(no relational operators).

--> The value of the var/exp, will be first verified with the value of first case.

--> If it match, then the statements in the corresponding case get executed.

--> If it doesn't match, then it is verified with the next case value and the same process is repeated.

--> If no case match, then the default case get executed.

--> Every case should be ended with a break statement.

--> We can have as many number of statements as possible and required.

--> The default case is optional.

--> If the default case is present it should be present after all the case statements.

--> The given set of statements can be associated with as many number of cases as possible and required.

Program:

#include< stdio.h >
#include< conio.h >
void main( )
{

      int n;
      clrscr( );
      printf("\nEnter any number(1-7): ");
      scanf("%d", &n);
      switch(n);
      {

            case 1: printf("It is Monday");
                        break;
            case 2: printf("It is Tuesday");
                        break;
            case 3: printf("It is Wednesday");
                        break;
            case 4: printf("It is Thursday");
                        break;
            case 5: printf("It is Friday");
                        break;
            case 6: printf("It is Saturday");
                        break;
            case 7: printf("It is Sunday");
                        break;
            default: printf("Let Us Code in C");

}

Note:

--> goto statement is referred as branching statement.

--> It is useful to transfer the control of execution from one statement to the other statement either if forward direction or in reverse direction only within that function.

--> If the goto statement is associated with a condition, then it is referred as conditional branching.

--> If the goto statement is not associated with any condition, then it is referred as un-conditional branching.

   Syntax:

      goto   < label >;

--> label is the name given to the statement.

--> The rules for naming a label are same as that of naming a variable.

--> label names should be unique i.e no two labels should have same name.

--> If the program can have as many number of goto statements as possible and required.

Drawbacks of goto statement:

--> usage of too many labels and goto statements results confusion in understanding the flow of control.

--> Mis-placing a label with another label results in abnormal behaviour in the program.

--> goto statements are strictly prohibited in C language.

2) Loop control statements

These statements are useful to repeatedly execute the given set of statements as long as some condition is satisfied.

-->These statements are of three types of follows.

      a) while

      b) do while

      c) for

a) while:

   Syntax:

         while( condition )
         {
                   statements
          }

--> The condition is evaluated first. If it is TRUE, then the statements in the while block get executed. After completing the execution the control transfers to the condition again and the same process is repeated as long as the condition is TRUE

--> If it is FALSE, then the control transfers to the next statement after the while statement and continue the execution.

--> while statement use pre-condition checking, which is also referred as Entry control loop mechanism.

--> The statements in the while block will be execited zero or more number of times.

--> If the statements in the while block get executed n times, then the condition will be evaluated (n+1) times.

Program:

#include< stdio.h >
#include< conio.h >
void main( )

{

      int n,r,sum=0;
      printf("Enter any Number: ");
      scanf("%d",&n);
      while(n>0)
      {

            r = n%10;
            sum = sum + r;
            n = n/10;

      }

      printf("\nSum of digits of given number is ",sum);

      }

}

--> When the while block contain only one statement then braces are optional.

--> Sometimes there may be "a" requirement then "a" statements in the while block are to be execited atleast one.

b) do-while:

   Syntax:

      do{

            statements

      }while( condition );

--> The statements in the do-while block are executed and after completing the execution the condition is evaluated.

--> If it is TRUE, then the control transfers to be giving of the do-while block and the same process is repeated as long as the condition evaluates to TRUE.

--> If it is FALSE, then the control transfers to the next statement after the do-while block and continue the execution.

--> So, do-while statement use post-condition checking which is also referred as Exit Control loop Mechanism.

--> So, the statements in the do-while block get executed one or more number of times.

--> If the statements in the do-while block are executed n times, then the condition will be evaluated n times.

Program:

#include< stdio.h >
#include< conio.h >
void main( )
{

      int n,r,sum=0;
      printf("Enter any Number: ");
      scanf("%d",&n);
      do
      {

            r = n%10;
            sum = sum + r;
            n = n/10;

      }while(n>0);
      printf("\nSum of digits of given number is ",sum);
      }

}

--> The variable used in the condition based on whose value the decision is being made and it is referred as loop control variable.

Drawbacks with while statements:

--> The loop control variable should be compulsorily assign with some initial value before the while block fails, which behaves the program abnormal.

--> The loop control variable should be compulsorily modified to the while block fails ,it results from the formation of infinite loop.

--> To overcome these problems, while statement is modified as for statement, whose syntax is as follows.

c) for:

   Syntax:

      for(initialization;condition;increment/decrement)
      {

            statements

      }

--> The initialization is performed first and then the condition is evaluated.

--> If it is TRUE, then the statements in the for block get executed. After completing the execution the control transfer to the inc/dec and then checks condion. This process repeated until condion is TRUE.

--> If it is FALSE, then the control transfer to the next statement after the for statement and continue the execution.

--> So, while and for statements are syntactically different, but semantically same.

--> If the for block contain only one statement, braces are optional.

--> In the initialization part we can specify as many number of statements as possible and required and they should be seperated by comma(,).

--> Similarly in the inc/dec part also we can specify as many number of statements as possible and required, they should be seperated by comma(,).

Eg:-

      for(n=1,p=1;n<=k;p++,n++;)
      {

            statements

      }

Program:

#include< stdio.h >
#include< conio.h >
void main( )
{

      int n,i,f0=0,f1=1,f2;
      printf("\nEnter N Value: ");
      scanf("%d",&n);
      printf("%d\t%d",f0,f1);
      for(i=1;i<=n-2;i++)
      {

            f2=f0+f1;
            printf("\t%d",f2);
            f0=f1;
            f1=f2;

      }

}



C language Strings Tutorials

Strings

    A string is a group of characters enclosed in a curly braces or ends with a null character

--> The null character is present at the end of the string character array.

--> The null character is represented by "\0".

--> The ASCII value of null character is zero.

--> The purpose of null character is, it indicates that end of the string.

   Syntax:

      datatype array_name[size];

      Eg: char a[100];

--> Here array name indicates name of the character array and size indicates the number of characters it can store.

      Eg: char a[100];

Initialization:

char a[20] = "LetUsCodeinC";

char a[ ] ={'L','e','t','U','s','C','o','d','e','i','n','C'};

String library functions:

1) strlen( )

      This function is used to find the length of string i.e no. of characters present in it. This function return number of characters in the string expect null character.

   Syntax:

      strlen(string);

Eg:-

#include< stdio.h >
#include< conio.h >
void main( )

{

      char str[20];
      int l;
      printf("\nEnter String: ");
      gets(str);
      l = strlen(str);
      printf("Length of the given string: %d", l);

}

2) strcpy( )

This function is used to copy contents of one string into another string.

   Syntax:

            strcpy(string1, string2)

3) strcat( )

This function is used to concatenate two string values i.e contents of one string are attached with the contents of another string.

   Syntax:

            strcat(string1, string2)

--> Here contents of string2 are appended to the contents of string1.

4) strrev( )

This function is used to reverse the contents of given string.

   Syntax:

            strrev(string);

5) strcmp( )

This function is used to compare two string values whether they are equal, which one is bigger or smaller string.

   Syntax:

            strcmp(string1, string2);

--> It performs comparison on the two strings based on the ASCII value of the characters present in the string.

6) strlwr( )

This function is used to convert uppercase letters in a string into lowercase.

   Syntax:

            strlwr(string);

7) strupr( )

This function is used to convert lowercase letters in a string to uppercase.

   Syntax:

            strupr(string);




C language Functions Tutorials


Functions

Functions are introduced by the concept of write once and run any number of times.

--> A Function is self contained block of code which perform a predefined task.

Syntax:

          returntype function_name(arg list)
         {

                  ----------

                  ----------

                  ----------

          }

--> Each and every function identified with a name and it is referred as FUNCTION NAME.

--> The rules for naming a function are same as that of naming a variable.

--> Function name should be unique with in a program i.e no two functions should have same name in the program.

--> The function name should be followed by parenthesis which contains the data supplied to that function.

--> The data supplied to the function are referred as arguments or parameters.

--> The function name should be preceded with a return type.

--> If a function does not return any value, then return type is to be specified as void.

--> Return type specifies the type of values being sent out of the function.

--> A function can return only one value.

--> If we don't specify any return type then by default the return type is considered as int.

--> Function body specify the work assign to that function.

--> Even if we define several functions, they will not be executed unless they are called directly or indirectly by the main( ) function.

--> Using an existing function perform the required operation is referred as FUNCTION call.

--> In Function call, we shouldn't specified return type and function call.

--> The functions provided by C language as a part of C language are referred as primitive / pre-defined / built-in functions.

--> The functions defined by the user as the requirement are referred as user defined function.

--> Based on the arguments and returning value, functions are classified under four categories as follows.

1) Functions without arguments and not returning a value.

2) Functions with arguments and not returning a value.

3) Functions without arguments and returning a value.

4) Functions with arguments and returning a value.

--> When a function is called, the control transfers from function call to the function definition, execute all the statements in that function and after completing the execution the control transfer to the next statement after the function call and continue the execution.

Sample Program:

#include< stdio.h >
#include< conio.h >
void display( );
void display( )
{

      printf("\nLet Us Code in C");

}
void main( )
{

      display( );
      display( );
      display( );

}

Note:

--> We can't define a function in another function.

--> A function can be defined either before using it, then its prototype is to be specified before using it.

Program:

#include< stdio.h >
#include< conio.h >
void main( )
{

      void display( void );
      display( );
      display( );
      display( );

}

void display( void );
{

      printf("\nLet Us Code in C");

}

--> The prototype should be specified only in the declaration section.

--> When we specified prototype in a function, then that function can be access only in that function.

--> Sometimes we may have a requirement that the function should be access any function in that program.

--> In general, the life time of a variable will be only for the execution of the block or function.

Program:

#include< stdio.h >
#include< conio.h >
void display( );
void main( )
{

      display( );
      display( );
      display( );

}
void display( )
{

      int x;
      printf("\nEnter any number: ");
      scanf("%d",&x);
      if(x%2 == 0)
            printf("\n\t EVEN NUMBER");
      else
            printf("\n\t ODD NUMBER");

}

Scope of a variable:

Scope of a variable refers to portion of the program in which that variable can be access or referred to.

--> So, the variables declared in a block are said to be local to that block.

--> Similarly the variables declared in a function can be access only within that function and can't be access directly in other functions.

--> So, the variables declared in a function are said to be local to that function.

--> Sometimes the variable declared in a function may be required to the access in some other function. This is possible by sending the corresponding values as arguments when calling that function.

--> The arguments specified in the function call are referred as Actual Parameters.

--> The arguments specify in the function definition are referred as Formal Parameters.

--> When the function is call, the control transfers from function call to the function definition and the actual parameters get copied to the formal parameters.

Program:

#include< stdio.h >
#include< conio.h >
void display( int );
void main( )
{

      int x;
      printf("\nEnter any number: ");
      scanf("%d", &x);
      display(x);

}
void display(int n);
{

      if(n%2 == 0)
            printf("\nEVEN NUMBER");
      else
            printf("\nODD NUMBER");

}

Note:

--> In function prototype, it is optional to specify variable names.

--> In general actual parameters are referred as arguments i.e the data supplied to a function in the function call.

--> Formal parameters are referred as parameters i.e the data specified in the function definition.

--> We can send as many number of arguments as possible and required to a function.

--> The number of actual parameters should be same as number of formal parameters.

--> The datatypes of the actual parameters should be same as the datatypes of the formal parameters.

--> The actual parameters get copied to the formal parameters in the same order and sequence.

Program:

#include< stdio.h >
#include< conio.h >
void sum(int,int);
void main( )
{

      int x,y;
      printf("\nEnter two numbers x & y : ");
      scanf("%d"%d",&x,&y);
      sum(x,y);

}
void sum(int a,int b)
{

      int c;
      c = a + b;
      printf("\nSUM = %d",c);

}

--> return statement is used for sending values from one function to another function.

Syntax:

         return value/variable/expression;

--> A function can be return only one value.

--> A program can have as many number of return statements as possible and required, but only one among then will be executed.

--> The value return will be placed in the corresponding function call or statement.

--> Based on the requirement, we can store the returned value in a variable.

--> The return type should be specified as data type of the value being return.

Program:

#include< stdio.h >
#include< conio.h >
void sum(int,int);
void main( )
{

      int x,y,z;
      printf("\nEnter two numbers x & y : ");
      scanf("%d"%d",&x,&y);
      z = sum(x,y);
      printf("\nRESULT: %d",z);

}
int sum(int a, int b)
{

      int c;
      c = a + b;
      return c;

}


C Language Files Tutorials

Files

--> A file is a defined data type used as data structure. A file is known as a string.

--> Files are used to stored data permanently to the external devices such as floppy disc and also to read data from external storage devices.

Operations on files:

   * Open the file

   * Updating the file

   * Closing the file

File Pointers:

    File pointer in the internal name or logical name given to the file which is opened for specific purpose.

   Syntax:

         File *file_pointer_name;

fopen( ):

    This function is used to open a file in the specified mode.

   Syntax:

         File file_pointer_name = fopen("file_name", "mode");

File Modes:

         Mode             Symbol

         Read                  "r"

         Write                 "w"

         Append              "a"

         Readwrite          "r+"

         Writeread          "w+"

         Binarywrite        "wb"

         Read                 "rb"

fclose( ):

    This function is used to close the opened file.

   Syntax:

         fclose(file_pointer);

FILE ACCESSING

    1. Sequential Accessing

    2. Random Accessing

Sequential Accessing Functions:

1) putc( ):

    This function is used to write character by character into the file.

   Syntax:

         putc(character, fp);

2) fputc( ):

    This function is used to write character by character into the file.

   Syntax:

         fputc(character, fp);

3) getc( ):

    This function is used to read single character from the file.

   Syntax:

         character_variable = getc(filepointer);

4) fgetc( ):

    This function is used to read single character from the file.

   Syntax:

         character_variable = fgetc(filepointer);

5) feof( ):

    This function is used to indicate end of file. This function returns zero, if the end of file is not reached. This function returns non-zero, if the end of file is reached.

   Syntax:

         feof(filepointer);

6) fputs( ):

    This function is used to write a string into the file.

   Syntax:

         fputs(string, filepointer);

7) fgets( ):

    This function is used to read a string from the file.

   Syntax:

         fgets(string, no. characters, filepointer);

8) fprintf( ):

    This function is used to write formatted input into the file.

   Syntax:

         fprintf(filepointer, "format specifier", arg1, arg2,...... argn);

9) fscanf( ):

    This function is used to read formatted output from the file.

   Syntax:

         fscanf(filepointer, "format specifier", &arg1, &arg2,...... &argn);

10) fwrite( ):

    This function is used to write an entire structure into file.

   Syntax:

         fwrite(&structure variable_name, sizeof(structure), n, filepointer);

11) fread( ):

    This function is used to read a structure from the file.

   Syntax:

         fread(&structure variable_name, sizeof(structure), n, filepointer);

12) ferror( ):

    This function is used to findout error when file read write operation is carried out.

   Syntax:

         ferror(filepointer);

13) perror( ):

    It is a standard library function which prints the error messeges specified by the compiler.

   Syntax:

         perror(filepointer);

Randoom Accessing Functions:

1) ftell( ):

    This function is used to indicate the position of the file pointer. This function returns the long integer value.

   Syntax:

         ftell(FILE *stream);

2) fseek( ):

    This function is used to move the file pointer either forwards or backwards to the specified number of byte the given position.

   Syntax:

         fseek(FILE *stream, long int offset, int position);

--> Here offset indicates no. of bytes to move from the given position.

--> Here position can take three values

   * 0 indicates beginning of the file

   * 1 current position

   * 2 end of the file

3) rewind( ):

    This function is used to remove the file pointer to the starting position of the file.

   Syntax:

         rewind(filepointer);

Defining and opening a file:-

    If we want to store data in a file in the secondary memory, we must specify certain things about the file to the operating system. They include

      1. Filename

      2. Data structure

      3. Purpose

--> Filename is a string of characters that make up a valid filename for the operating system. It may contain two parts, a primary name and an optional period with the execution.

--> Data structure of a file is defined as FILE in the library of standard Input/output definitions. Therefore, all files should be declared as type FILE before they are used. FILE is a defined data type.

--> When we open a file, we must specify what we want to do with the file.

Declaring a file

         FILE *fp;

         fp = fopen("filename", "mode");

--> The first statement declares the variable fp as a pointer to the data type FILE.

--> The second statement also specifies the purpose of opening this file.

Closing a file:

    After the required operations such as reading, writing or appending operations on a file are done, the file needs to be closed.

   Syntax:

         fclose(filepointer);

The fclose( ) function has one parameter i.e filepointer for a particular file to be closed. If more than one files are to be closed then more than one fclose( ) function can be written with the respective filepointers.



C language Pointers Tutorials


Pointers

   Pointer is a variable which stores address of another variable.

--> The syntax for declaring a pointer is as follows.

datatype  *<var_name>

   Eg:-   int  *a;

--> Function calls are of two types

1) call-by-value:

   Here the values of actual parameters get copied to formal parameters.

2) call-by-reference:

   Here the address of actual parameters get copied to formal parameters.

--> Any pointer variable required 2 bytes of memory irrespective of their datatype.

--> A pointer variable of some datatype can store address of a variable of same datatype i.e int * can store address of a variable, float * can store address of a float variable etc.

--> A pointer which is capable of storing address of a variable of any datatype is void *.

--> The address stored in a pointer in always being an unsigned integer.

--> When we have a pointer containing address of a variable, then we can access the value contained is that variable into the pointer using an operator called De-referencing operator, represented with the symbol *.

Program:

#include< stdio.h >
#include< conio.h >
void main( )
{

      int x, *a;
      clrscr( );
      printf("\nEnter X Value: ");
      scanf("%d", &x);
      a = &x;
      printf("\n\tAddress: %u", a);
      printf("\n\tValue : %d", x);
      x = x + 7;
      printf("\n\tValue : %d", *a);
}

Advantages:

--> Instead of maintaining multiple copies of data, we can maintain a single copy and send its address to all the other peoples.

--> When large volumes of data is to be copied from one function to the other function instead of sending the entire data we can just send only the address, there by saving lot of time.

--> We can also allocate memory as much as we requires as and when required.

Dynamic memory allocation:

Allocating memory as much as we require as and when required is refered as dynamic memory allocation.

--> C language provide dynamic memory allocation using the following functions.

1) malloc( )

2) calloc( )

3) realloc( )

4) free( )

--> These functions are available in the header file alloc.h

1) malloc( ):

   Syntax:

            void * malloc(no. of bytes);

--> This function expect number of bytes for which the memory is to be allocated as argument.

--> It allocates the specified amount of memory and return its address.

--> It doesn't talk about what type of values to store in the allocated memory. So, its return type is void *

--> So, we need to type casting to the required pointer type when a pointer contain address of an array, then the pointer itself behavior like an array.

Program:

#include< stdio.h >
#include< conio.h >
#include< alloc.h >
void readarray(int *, int);
void printarray(int *, int);
void main( )
{

      int *a, n;
      clrscr( );
      printf("\nEnter N Value: ");
      scanf("%d",&n);
      a = (int *)malloc(n*sizeof(int));
      readarray(a, n);
      printarray(a, n);

}
void readarray(int *x, int n)
{

      int i;
      printf("\nEnter array elements: ");
      for(i=0;i<n;i++)
      scanf("%d",&x[i]);
}
void printarray(int *x, int n)
{

      int i;
      printf("\nThe elements in the array are:");
      for(i=0;i<n;i++)
      printf("%d ", x[i]);

}

2) calloc( ):

It is same as malloc( ) except that the values are initiated to zero of allocating the memory.

--> It is used to allocate multiple block of memory.

   Syntax:

            void * calloc(no. of elements, elements size);

3) realloc( ):

It is useful when we are required to adjust already allocated memory.

   Syntax:

            void * realloc(void *, size)

4) free( )

It is used to clear the allocated memory.

   Syntax:

            void  free(void *)




C language Operators and Expressions Tutorials

Operators:

   The symbol is used to perform an operation is called an operator.

--> An operator which expect only one operand is referred as Unary operator.

--> An operator which expect two operands is referred as Binary operator.

--> An operator which expect three operands is referred as Terinary operator.

--> The operators provided by C language are classified as follows.

1. Size operator:

   This operator is useful to retrieve the size of a datatype or a variable.

operator:    sizeof

   Syntax:

      sizeof( datatype/variable )

Program:

#include< stdio.h >

#include< conio.h >

void main( )

{

      int x;

      clrscr( );

      x = sizeof(char);

      printf("\n\tCHAR: %d",x);

      x = sizeof(int);

      printf("\n\tINT: %d",x);

      x = sizeof(float);

      printf("\n\tFLOAT: %d",x);

      x = sizeof(double);

      printf("\n\tDOUBLE: %d",x);

      x = sizeof(long int);

      printf("\n\tLONG INT: %d",x);

      x = sizeof(long double);

      printf("\n\tLONG DOUBLE: %d",x);

}

2. Arithmetic operators:

   These operators are useful to perform arithmetic operators on the data.

--> The arithmetic operators are provided by C language as follows.

      + ------> Addition

      - ------> Subtraction

      * ------> Multiplication

      / ------> Division

--> When both the numerator and denomenator are integers, the division operator give only the quotient and will not considered the remainder

      % ------> Modulo or Remainder

--> It gives the remainder when two numbers are divided.

Program:

#include< stdio.h >

#include< conio.h >

void main( )

{

      int x, y, a, b, c, d, e;

      clrscr( );

      printf("\nEnter two numbers: ");

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

      a = x + y;

      b = x - y;

      c = x * y;

      d = x / y;

      e = x % y;

      printf("\n\t %d + %d : %d", x, y, a);

      printf("\n\t %d - %d : %d", x, y, b);

      printf("\n\t %d * %d : %d", x, y, c);

      printf("\n\t %d / %d : %d", x, y, d);

      printf("\n\t %d %% %d : %d", x, y, e);

}

Note:

--> When % is to be displayed in the output, we are required to specify %% in the format.

      + = ---> Add and Assign

      - = ---> Subtract and Assign

      * = ---> Multiply and Assign

      / = ---> Divide and Assign

      % = ---> Modulo and Assign

3) Increment/Decrement operators:

      ++ ----> Increment operator

      --   ----> Decrement operator

      x = x + 1 or x += 1 or x++

      x = x - 1 or x -= 1 or x--

--> Both the Increment and Decrement operators can be used in two ways as follows.

      x++ ---> post-increment

      ++x ---> pre-increment

      x--   ---> post-decrement

      --x   ---> pre-decrement

--> When we used as individual statement, both the pre and post operators appear to be same.

--> They vary when we used in other expressions or statements

--> When we used in expressions and other statements.

1) The pre-increment/pre-decrement assume latest updated value in that expression/statements

2) The post-increment/post-decrement assume pre-updated value or old value is that expression.

--> But in both the cases the value of that variable will be increment.

Program:

#include< stdio.h >

#include< conio.h >

void main( )

{

      int x;

      clrscr( );

      printf("\nEnter a number: ");

      scanf("%d", &x);

      printf("\n\t%d %d %d %d %d", x++, ++x, x++, ++x, x++);

}

4) Type casting operator:

This is useful when a value of one type is to be consider as of another type temporarily for that expressions.

   Syntax:

      (type) value

Program:

#include< stdio.h >

#include< conio.h >

void main( )

{

      int x, y;

      float res;

      clrscr( );

      printf("\n\tEnter two numbers: ");

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

      res = (float)x/y;

      printf("\n\tRESULT: %.2f", res);

}

5) Bit-wise operators:

These operators are useful to perform operations on the individual bits of the given data.

--> C language has a distinction of supporting special operators known as "Bit-wise operators" for manipulating of data at "bit level"

--> These operators are used for "testing the bits" or "shifting them" left or right--> Bit-wise operators may not be applied in "float or "double". They operate only "integers". Such as int, char, short, long int etc.

      operator      meaning

           >>           Right shift

           <<           Left shift

            ^            Bit-wise XOR

            ~            1's complement

            &            Bit-wise AND

            |             Bit-wise OR

--> Bit-wise operators are used for operators on individual bits.

1) Bit-wise AND:

This is useful to perform AND operator on the individual bits of the given data.

--> The truth table of Bit-wise AND operator is

    a      b      a&b

    0      0        0

    0      1        0

    1      0        0

    1      1        1

a = 0 0 0 0 0 1 1 1

b = 0 0 0 1 0 0 0 1

-------------------------

a&b = 0 0 0 0 0 0 0 1

-------------------------

2) Bit-wise OR operator:

This is useful to perform OR operation on the individual bits of the given data.

--> The truth table of Bit-wise OR operator is

    a      b      a|b

    0      0        0

    0      1        1

    1      0        1

    1      1        1

a = 0 0 0 0 0 1 1 1

b = 0 0 0 1 0 0 0 1

-------------------------

a|b = 0 0 0 1 0 1 1 1

-------------------------

3) Bit-wise XOR:

This is useful to perform XOR operation on the individual bits of the given data.

--> The truth table of Bit-wise XOR operator is

    a      b      a^b

    0      0        0

    0      1        1

    1      0        1

    1      1        0

a = 0 0 0 0 0 1 1 1

b = 0 0 0 1 0 0 0 1

-------------------------

a^b = 0 0 0 1 0 1 1 0

-------------------------

4) one's complement:

This is useful to perform 1's complement on the internal representation of the given data.

--> It is used to perform a unary operator.

a = 0 0 0 0 0 1 1 1

-------------------------

~a = 1 1 1 1 1 0 0 0

-------------------------

5) Left shift operator(<<):

This is useful to shift the bits in the internal representation of the given data towards left by the specified number of positions.

--> If the value is shifted by n positions towards left, then the value is raised by 2n

a = 0 0 0 0 1 1 0 1

a<<2

a = 0 0 1 1 0 1 0 0

6) Right shift operator(>>)

This is useful to shift the binary representation of the given value towards right by the specified number of positions.

--> If the value shifted by n-positions towards right, then the value will be decreased by 2n

a = 0 0 0 0 1 1 0 1

a>>2

a = 0 0 0 0 0 0 1 1

6) Relational operators:

These operators are useful to find the relation between the two given numbers.

      <     ---> Lessthan

      <=   ---> Lessthan or equal to

      >     ---> Greaterthan

      >=   ---> Greaterthan or equal to

      ==   ---> Equal to

      !=    ---> Not equal to

--> The relation operators are all Binary operators

--> They result in an integer value. That integer value will be either 0 or 1

--> '0' represents false i.e the condition doesn't hold

--> '1' represents true i.e the condition is satisfied

Note:

--> = is called Assignment operator.

--> It is useful to assign the RHS value to LHS variable

--> == is called comparison operator

--> It compares both the RHS and LHS value and return TRUE(1) if they are same, FALSE(0) otherwise.

7) Conditional operator:

--> The conditional operator is represented as "?" and ":"

   Syntax:

      (condition)?s1:s2

--> The condition is evaluated first

--> If it is TRUE, then the statements between ? and : will be executed.

--> If it is FALSE, then the statement after : will be executed.

Note:

--> "0" is considered as FALSE and any nonzero value is considered as TRUE.

--> We can specify as many number of statements as possible and required between ? and : they should be seperated by ",".

--> We can also specify as many number of statements as possible and required after column.

--> Among the statements specify after column the first statement will be executed only when the condition is false and the remaining statements will be executed all the times i.e when the condition is true or false.

--> Conditional operators can be nested i.e we can use conditional operator in another conditional operator.



Wednesday 12 August 2015

C Program to read array of elements and print only odd numbers


Program:

#include< stdio.h >
#include< conio.h >
void main( )
{
         int i, a[10];
         for( i = 0; i < 5; i++ )
         {
                    printf("Enter the value for a[ %d ]: ", i);
                    scanf("%d", &a[ i ]);
          }
          printf("\nThe array of Even elements are:\n");
          for( i = 0; i < 5; i++ )
          {
                    if( a[ i ] % 2 != 0 )
                    {
                               printf(" %d ", a[ i ] );
                     }
           }
}


Output:

Enter the value for a[ 0 ]: 1

Enter the value for a[ 1 ]: 2

Enter the value for a[ 2 ]: 3

Enter the value for a[ 3 ]: 4

Enter the value for a[ 4 ]: 5

The array of Even elements are:

1 3 5

C Program to read array of elements and print only even numbers


Program:

#include< stdio.h >
#include< conio.h >
void main( )
{
         int i, a[10];
         for( i = 0; i < 5; i++ )
         {
                    printf("Enter the value for a[ %d ]: ", i);
                    scanf("%d", &a[ i ]);
          }
          printf("\nThe array of Even elements are:\n");
          for( i = 0; i < 5; i++ )
          {
                    if( a[ i ] % 2 == 0 )
                    {
                               printf(" %d ", a[ i ] );
                     }
           }
}


Output:

Enter the value for a[ 0 ]: 1

Enter the value for a[ 1 ]: 2

Enter the value for a[ 2 ]: 3

Enter the value for a[ 3 ]: 4

Enter the value for a[ 4 ]: 5

The array of Even elements are:

2 4








C program to read array of elements separated by comma and print array of elements



Input   : 2, 6, 7, 8, 1, 0
Output: 2 6 7 8 1 0

Program:

#include< stdio.h >
#include< conio.h >
void main( )
{
          int i = 0;
          char a[ ] = "2, 6, 7, 8, 1, 0";
          char *p, *b[ 10 ];
          p = strtok(a, ",");
          while( p != NULL )
          {
                 b[ i++ ] = p;
                 p = strtok( NULL, ",");
          }
          for( i = 0; i < 6; i++ )
          {
                 printf("%s", b[ i ]);
          }
}

Output:

2 6 7 8 1 0



C program to read and print array elements in reverse order



Program:

#include< stdio.h >
#include< conio.h >
void main( )
{
         int a[ 5 ], i;
         for( i = 1; i < 5; i++)
        {
                printf("\nEnter the value for [ %d ]: ",i);
                scanf("%d", &a[ i ]);
         }
         printf("\nThe array of elements in reverse order:\n");
         for(i=5;i>0;i--)
         {
               printf("%d\t", a[ i ]);
         }
}


Output:

Enter the value for [ 0 ]: 0

Enter the value for [ 1 ]: 2

Enter the value for [ 2 ]: 1

Enter the value for [ 3 ]: 9

Enter the value for [ 4 ]: 7

The array of elements in reverse order:

7 9 1 2 0


C Program to read and print array of elements


Program:

#include< stdio.h >
#include< conio.h >
void main( )
{
          int a[5], i;
          for( i = 0; i < 5; i++ )
         {
                  printf("\nEnter the value for a[%d]: ", i);
                  scanf("%d", &a[i]);
         }
         printf("\nThe array elements are: \n");
         for( i = 0; i < 5; i++ )
         {
                 printf("%d\t", a[i]);
         }
}

Output:

Enter the value for a[ 1 ]: 3

Enter the value for a[ 2 ]: 2

Enter the value for a[ 3 ]: 1

Enter the value for a[ 4 ]: 9

Enter the value for a[ 5 ]: 7

The array elements are:

3 2 1 9 7



C Program to print Data Type Size and Ranges


Program:

#include< stdio.h >
#include< conio.h >
#include< limits.h >
#include< float.h >
void main( )
{
            clrscr( ); // Clear the screen Contents
            printf("Integer data type:\n\tSize: %d\n\tRange: %d to %d", sizeof(int), INT_MIN, INT_MAX);
            printf("\nCharacter data type:\n\tSize: %d\n\tRange: %d to %d", sizeof(char), CHAR_MIN, CHAR_MAX);
            printf("\nFloat data type:\n\tSize: %d\n\tRange: %E to %E", sizeof(float), FLT_MIN, FLT_MAX);
            printf("\nDouble data type:\n\tSize: %d\n\tRange: %E to %E", sizeof(double), DBL_MIN, DBL_MAX);
}

Output:

Integer data type:
           Size: 2
           Range: -32768 to 32767
Character data type:
           Size: 1
           Range: -128 to 127
Float data type:
           Size: 4
           Range: 1.17549E - 38 to 3.402823E + 38
Double data type:
           Size: 8
           Range: 2.225074E - 308 to 1.797693E + 308



Thursday 6 August 2015

Java program for multiplication of original matrix and transpose matrix


Input: s = 1
Matrix elements increased by one.
Original Matrix:

1  2  3 
4  5  6
7  8  9

Transpose Matrix:

1  4  7
2  5  8
3  6  9

Multiplication of two matrices:

14  32  50
32  77  122
50  122  194

Program:

import java.io.*;
import java.util.*;
public class matmul
{
          public static void main( String[ ] args ) {
          Scanner n = new Scanner( System.in );
          int s, i, j, k;
          int a[ ][ ] = new int[ 10 ] [ 10 ];
          int b[ ][ ] = new int[ 10 ][ 10 ];
          int mul[ ][ ] = new int[ 10 ][ 10 ];
          System.out.println( "Enter S value: " );
          s = n.nextInt( );
          for( i = 0 ; i < 3 ; i++)
         {
                 for( j = 0 ; j < 3 ; j++ )
                {
                        a[ i ][ j ] = s;
                        s = s + 1;
                 }
          }
          System.out.println( "Original Matrix: " );
          for( i = 0 ; i < 3 ; i++ )
          {
                  for( j = 0 ; j < 3 ; j++ )
                 {
                        System.out.print( a[ i ][ j ] + "  " );
                  }
                  System.out.println("");
           }
           for( i = 0 ; i < 3 ; i++ )
          {
                   for( j = 0 ; j < 3 ; j++ )
                  {
                         b[ i ][ j ] = a[ j ][ i ];
                   }
           }
           System.out.println( "Traspose Matrix:" );
           for( i = 0 ; i < 3 ; i++)
           {
                   for( j = 0 ; j < 3 ; j++)
                  {
                          System.out.print( b[ i ][ j ] + "  " );
                   }
                   System.out.println( "" );
            }
            for(i=0 ; i < 3 ; i++ )
           {
                    for( j = 0 ; j < 3 ; j++)
                   {
                           for( k = 0 ; k < 3 ; k++ )
                          {
                                  mul[ i ] [ j ] = mul[ i ] [ j ] + ( a[ i ] [ k ] * b[ k ] [ j ] );
                           }
                    }
             }
             System.out.println( "Multiplication of two matrices: " );
             for( i = 0 ; i < 3 ; i++ )
            {
                    for( j = 0 ; j < 3 ; j++ )
                   {
                            System.out.print( mul[i][j] + "  " );
                    }
                    System.out.println( " " );
             }
       }
}



C Program to print prime numbers upto the given Range

C Program to print PRIME Numbers upto the given Range.
Input: Enter N Value: 11
Output: 2, 3, 5, 7, 11


C Program:

#include< stdio.h >
#include< conio.h >
void main( )
{
       int i, j, n;
       printf("\nEnter N Value: ");
       scanf("%d", &n);
       for( i = 1 ; i <= n ; i++ )
      {
              int c = 0 ;
              for( j = 1 ; j < = i ; j++ )
             {
                     if( i%j == 0)
                     {
                             c = c + 1;
                     }
              }
              if( c == 2 )
             {
                      printf(" %d ", i);
                      if( i < n )
                     {
                              printf(",");
                      }
              }
        }
}

Output:

Enter N Value: 11
2,3,5,7,11