Thursday, 20 March 2014

Program in c to find greatest among three numbers via function

/*… Hey guy’s this is a simple program with a twist  i have made it with function… try it…*/
#include <stdio.h>
 /* function prototype */
int maximum( int, int, int );
/*…main function starts..*/
void main()
{
int a, b, c;
printf( “Enter three integers: ” );
scanf( “%d%d%d”, &a, &b, &c );
printf( “Maximum is: %d\n”, maximum( a, b, c ) );
getch();
}
/*…Main Function End’s…*/
/* Function maximum definition */
int maximum( int x, int y, int z )
{
int max = x;
if ( y > max )
max = y;
if ( z > max )
max = z;
return max;
}

//The output is:::::::::::::::::::

Image

program in c to show the “randomization of die-roll”

/*…… hey guy’s it is a randomizing die rolling program…*/
#include <stdlib.h>
#include<conio.h>
#include <stdio.h>
/*…Main function start’s….*/
void main()
{
/*….Initialization…*/
int i;
unsigned seed;
printf( “Enter seed: ” );
scanf( “%u”, &seed );
srand( seed );        //here srand is used to randomise the seed…….
/*….Loop start’s…*/
for ( i = 1; i <= 10; i++ ) 
{
printf( “%10d”, 1 + ( rand() % 6 ) );
/*…Condition checking..*/
if ( i % 5 == 0 )
printf( “\n” );
}
/*….Loop end’s….*/
getch();
}
/*…Main function end’s..*/

Image

PROGRAM IN C TO ILLUETRATE THE USE OF “SRAND” WITH “SWITCH STATEMENT”

//IT IS JUST A GEME OF CHANCES AND I HAVE NAMED IT ” ROLL BABY ROLL…”
//rules are so simple listed below——–
–Roll two dice
•7 or 11 on first throw, player wins
•2, 3, or 12 on first throw, player loses
•4, 5, 6, 8, 9, 10 – value becomes player’s “point”
–Player must roll his point before rolling 7 to win

/*… Now programming begins…*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int rollDice( void );
/*…Main function begin’s…*/
void main()
{
int gameStatus, sum, myPoint;
srand( time( NULL ) );
sum = rollDice();                                    /* first roll of the dice */
switch ( sum ) {
case 7: case 11:                                   /* win on first roll */
gameStatus = 1;
break;
case 2: case 3: case 12:                      /* lose on first roll */
gameStatus = 2;
break;
default:                                               /* remember point */
gameStatus = 0;
myPoint = sum;
printf( “Point is %d\n”, myPoint );
break;
}
while ( gameStatus == 0 )                    /* keep rolling */
{                                                     
sum = rollDice();
if ( sum == myPoint )                           /* win by making point */
gameStatus = 1;
else
if ( sum == 7 )                                       /* lose by rolling 7 */
gameStatus = 2;
}
if ( gameStatus == 1 )
printf( “Player wins\n” );
else
printf( “Player loses\n” );
getch();
}
/*…Main function end’s…*/
int rollDice( void )
{
int die1, die2, workSum;
die1 = 1 + ( rand() % 6 );
die2 = 1 + ( rand() % 6 );
workSum = die1 + die2;
printf( “Player rolled %d + %d = %d\n”, die1, die2, workSum );
return workSum;
}

Image

what is ENUMERATION IN C

  Enumeration
  Set of integers represented by identifiers
–Enumeration constants – like symbolic constants whose values automatically set
•Values start at 0 and are incremented by 1
•Values can be set explicitly with =
•Need unique constant names
–Declare variables as normal
•Enumeration variables can only assume their enumeration constant values (not the integer representations)

PROGRAM IN C TO SHOW THAT THE ADDRESS AND VALUE OF A POINTER VARIABLE ARE COMPLEMENTS OF EACH OTHER

/*hey guy’s this is just a simple program that illustrate you  the “&” and ”  * ”  operators used on pointers……. */
#include <stdio.h>
/*….Main function Starts…*/
void main()
{
int a;                                                            /* a is an integer */
int *aPtr;                                                       /* aPtr is a pointer to an integer */
a = 7;
aPtr = &a;                                                      /* aPtr set to address of a */
printf( “The address of a is %p” “\nThe value of aPtr is %p”, &a, aPtr );
printf( “\n\nThe value of a is %d” “\nThe value of *aPtr is %d”, a, *aPtr );
printf( “\n\nShowing that * and & are inverses of “ ”each other.\n&*aPtr = %p” “\n*&aPtr = %p\n”, &*aPtr, *&aPtr );
getch();
}
/*…Main function ends…*/

Image

PREDEFINED SYMBOLIC CONSTANTS

Five predefined symbolic constants
Cannot be used in #define or #undef——
given below………….


Symbolic constant Description
__LINE__ The line number of the current source code line (an inte¬ger constant).
__FILE__ The presumed name of the source file (a string).
__DATE__ The date the source file is compiled (a string of the form “Mmm dd yyyy” such as “Jan 19 2001″). 
__TIME__ The time the source file is compiled (a string literal of the form “hh:mm:ss”).

CALL BY REFERENCE

Call by reference with pointer arguments
–Pass address of argument using & operator
–Allows you to change actual location in memory
–Arrays are not passed with & because the array name is already a pointer
* operator 
–Used as alias/nickname for variable inside of function
void double(int *number)
{
*number = 2 * (*number);
}
*number used as nickname for the variable passed

Cube a variable using call-by-reference with a pointer argument

/*….Hey guy’s this is the program reffered to the post i have posted i.e “CALL BY REFERENCE…”
/*…HOPE YOU LIKE IT….*/
#include <stdio.h>
void cubeByReference( int * );                                              /* prototype */
/*…Main Function Starts…*/
void main()
{
int number = 5;                                                                 /* Initialising….*/
printf( “The original value of number is %d”, number );
/*….Calling of Function…with arguments in it..*/
cubeByReference( &number );
printf( “\nThe new value of number is %d\n”, number );
getch();
}
/*…Main Function Ends..*/
/*…Function Definition Starts..*/
void cubeByReference( int *nPtr )
{
*nPtr = *nPtr * *nPtr * *nPtr; /* cube number in main */
}
/*….Function Definition Ends..*/

Image

HOW TO USE CONST QUALIFIER WITH POINTERS

  • const qualifier – variable cannot be changed
–Good idea to have const if function does not need to change a variable.
–Attempting to change a const is a compiler error.
  • const pointers – point to same memory location
-Must be initialized when declared.
int *const myPtr = &x;
  • Type int *const – constant pointer to an int
const int *myPtr = &x;
  • Regular pointer to a const int
const int *const Ptr = &x;
  • const pointer to a const int
  • x can be changed, but not *Ptr

BUBBLE SORT USING CALL BY REFERENCE

/*………This program puts values into an array, sorts the values into ascending order, and prints the resulting array….. */
#include <stdio.h>
#define SIZE 10
void bubbleSort( int *, const int );                              /*…Prototype…*/
/*…Main Function Starts…*/
void main()
{
/*….Initialization and Declaration…….*/
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };                    
int i;
printf( “Data items in original order\n” );
for ( i = 0; i < SIZE; i++ )                                                      /*..CHecking Condition……*/
printf( “%4d”, a[ i ] );
bubbleSort( a, SIZE );                                                           /* sort the array */
printf( “\nData items in ascending order\n” );
for ( i = 0; i < SIZE; i++ )                                                     /*..CHecking Condition……*/
 printf( “%4d”, a[ i ] ); 
printf( “\n” );
getch();
}
/*….Main Function Ends…*/
void bubbleSort( int *array, const int size )                       /*..Function Definition…*/
{
void swap( int *, int * );
int pass, j; 
for ( pass = 0; pass < size – 1; pass++ )
for ( j = 0; j < size – 1; j++ )
if ( array[ j ] > array[ j + 1 ] )
swap( &array[ j ], &array[ j + 1 ] );
}
void swap( int *element1Ptr, int *element2Ptr )                 /*…Function Definition………*./
{
int hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
}

Image

SOME CONVERSION SPECIFIERS

  • p
         —Displays pointer value (address)
  • n
         —Stores number of characters already output by current printf statement.
         —Takes a pointer to an integer as an argument.
         —Nothing printed by a %n specification.
         —Every printf call returns a value.
  1.         Number of characters output
  2.         Negative number if error occurs
  • %


         —Prints a percent sign 
         —%%

PROGRAM IN C TO SHOW THE USE OF CONVERSION SPECIFIERS

/*……….Hey  guys this is a program made by  Using the p, n, and % conversion specifiers…….. */
#include <stdio.h>
/*…Main Function Start’s…*/
void main()
{
/*…Initialization and Declaration….*/
int *ptr;
int x = 12345, y;
ptr = &x;
printf( “The value of ptr is %p\n”, ptr );
printf( “The address of x is %p\n\n”, &x );
printf( “Total characters printed on this line is:%n”, &y );
printf( ” %d\n\n”, y );
y = printf( “This line has 28 characters\n” );
printf( “%d characters were printed\n\n”, y );
printf( “Printing a %% in a format control string\n” );
getch();
}
/*…Main Function End’s…*/

Image

RELATIONSHIP BETWEEN POINTERS AND ARRAYS

  • Arrays and pointers closely related
         –Array name like a constant pointer
         –Pointers can do array subscripting operations
  • Declare an array b[5] and a pointer bPtr
          bPtr = b; 
          Array name actually a address of first element
                                         OR
          bPtr = &b[0] 
         Explicitly assign bPtr to address of first element.

  • Element b[n] 
        –can be accessed by *( bPtr + n )
        –n – offset (pointer/offset notation)
        –Array itself can use pointer arithmetic.
b[3] same as *(b + 3)
        –Pointers can be subscripted (pointer/subscript notation).
           bPtr[3] same as b[3].

PROGRAM IN C TO SHUFFLE THE 52 CARDS USING ARRAY OF POINTERS

/*.. Hey guy’s this is a program of Card shuffling ……. */
/*…In this Program i Have used three refinements to get the desired Results…..*/
/*…Hope you LIke it..*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>                               /*…Used to count time …*/
/*..Prototyping..*/
void shuffle( int [][ 13 ] );
void deal( const int [][ 13 ], const char *[], const char *[] );
/*…Main Function Starts..*/
void main()
{
/*…Initialization and Declaration…*/
const char *suit[ 4 ] = { “Hearts”, “Diamonds”, “Clubs”, “Spades” };
const char *face[ 13 ] = 
{ “Ace”, “Deuce”, “Three”, “Four”,
“Five”, “Six”, “Seven”, “Eight”,
“Nine”, “Ten”, “Jack”, “Queen”, “King” };
int deck[ 4 ][ 13 ] = { 0 };
srand( time( 0 ) );
shuffle( deck );
deal( deck, face, suit );
getch();
}                                                                     /*…Main Function Ends..*/ 
void shuffle( int wDeck[][ 13 ] )                       /*….Function Definition…*/
{
int row, column, card;
for ( card = 1; card <= 52; card++ )                      /*…Loop Begins..*/ 
{
do {
row = rand() % 4;
column = rand() % 13;
} while( wDeck[ row ][ column ] != 0 );
wDeck[ row ][ column ] = card;
}
}                                                                                     /*…Loop End’s…*/
void deal( const int wDeck[][ 13 ], const char *wFace[],const char *wSuit[] )
{
int card, row, column;
for ( card = 1; card <= 52; card++ )
for ( row = 0; row <= 3; row++ )
for ( column = 0; column <= 12; column++ )
if ( wDeck[ row ][ column ] == card )
printf( “%5s of %-8s%c”,
wFace[ column ], wSuit[ row ],
card % 2 == 0 ? ‘\n’ : ‘\t’ );
}

the output is……

Image

PROGRAM IN C TO CREATE A SEQUENTIAL FILE

/*………Hey guy’s this is a program to Create a sequential file………… */
#include <stdio.h>
/*…Main Function Start’s….*/
void main()
{
/*…Initialization and Declaration..*/
int account;
char name[ 30 ];
double balance;
FILE *cfPtr;                                                             /* cfPtr = clients.dat file pointer */
/*…Condition Checking…*/
if ( ( cfPtr = fopen( “clients.dat”, “w” ) ) == NULL )
printf( “File could not be opened\n” );
else { 
printf( “Enter the account, name, and balance.\n” );
printf( “Enter EOF to end input.\n” );
printf( “? ” );
scanf( “%d%s%lf”, &account, name, &balance );
while ( !feof( stdin ) )

fprintf( cfPtr, “%d %s %.2f\n”, 
account, name, balance );
printf( “? ” );
scanf( “%d%s%lf”, &account, name, &balance );
}
fclose( cfPtr );                /*…Close The File..*/
}
getch();
}
/*….Main Function End’s…*/

/*..The output is…:::::::


Image
 

READING DATA FROM A SEQUENTIAL ACCESS FILE

  • Reading a sequential access file.
        –Create a FILE pointer, link it to the file to read.
                myPtr = fopen( “myFile.dat”, “r” );
        –Use fscanf to read from the file.
             :Like scanf, except first argument is a FILE pointer.
         fscanf( myPtr, “%d%s%f”, &myInt, &myString, &myFloat );
        –Data read from beginning to end.
        --File position pointer – indicates number of next byte to be read/written.
            :Not really a pointer, but an integer value (specifies byte location).
            :Also called byte offset. 
        rewind(myPtr) - repositions file position pointer to beginning of the file (byte 0).

“TIC TAC TOE” GAME

/*…Hey guys “the game that we all like to play durinag a boring lecture in our schools in childhood”  —is back but with a twist this time it is not on paper it is in our programming language “C”….*/
/*…so let’s just start..*/
#include <stdio.h>
 /*…Main Function Start’s…*/
void main ()
{
/*….Initialization and Declaration….*/
int i;
int player = 0;
int winner = 0;
int choice = 0;
int row = 0;
int column = 0;
int line = 0;

char board [3][3] = {
{’1′,’2′,’3′},
{’4′,’5′,’6′},
{’7′,’8′,’9′}
};

clrscr();
/*…Loop Begin’s…*/
for ( i = 0; i<9 && winner==0; i++)
{
printf(“\n\n”);
printf(” %c | %c | %c\n”, board[0][0], board[0][1], board[0][2]);
printf(“—|—|—\n”);
printf(” %c | %c | %c\n”, board[1][0], board[1][1], board[1][2]);
printf(“—|—|—\n”);
printf(” %c | %c | %c\n”, board[2][0], board[2][1], board[2][2]);

player = i%2 + 1;                                                            /*…Used to Calculate Which Player’s Turn Is..*/
/*…Loop Begins…*/ 
do
{
printf(“\nPlayer %d, please enter the number of the square “ “where you want to place your %c: “,player,(player==1)?’X':’O');
scanf(“%d”, &choice);


row = –choice/3;
column = choice%3;
}while(choice<0 || choice>9 || board [row][column]>’9′);

board[row][column] = (player == 1) ? ‘X’ : ‘O’;


if((board[0][0]==board[1][1] && board[0][0]==board[2][2]) ||
(board[0][2]==board[1][1] && board[0][2]==board[2][0]))
winner = player;
else
for(line = 0; line <=2; line++)
if((board[line][0]==board[line][1] && board[line][0]==board[line][2])||
(board[0][line]==board[1][line] && board[0][line]==board[2][line]))
winner = player;

}                                                                                              /*…Loop End’s…*/

printf(“\n\n”);
printf(” %c | %c | %c\n”, board[0][0], board[0][1], board[0][2]);
printf(“—|—|—\n”);
printf(” %c | %c | %c\n”, board[1][0], board[1][1], board[1][2]);
printf(“—|—|—\n”);
printf(” %c | %c | %c\n”, board[2][0], board[2][1], board[2][2]);


if(winner==0)                                                                       /*…Condition Checking…*/
printf(“The game is a draw\n”);
else
printf(“Player %d has won\n”, winner);

getch();
}
/*…..Main Function End’s…*/
The Output Is::::::::::::::::::::::::::::::
there are multiple pic’s of output so that you can understand what is happening on the output screen….
hope you like it…
Image
ImageImageImageImageImage