Dec 4, 2013

A simple game with C program

Unknown | 2:15 PM | | 1 Comment so far
Create a simple game with C program.


#include <stdlib.h>
#include <stdio.h>
#include <conio2.h>
#include <stdbool.h>
#include <time.h>
#define N_OBJ 10

typedef struct {
        float life,
               money,
               score;
        char name[30];
        struct {
               int speed,
                   high,
                   force;
               }skills;
}character;

typedef struct {
        float life;
        }Enemy;

typedef struct {
        int x,y;
        }pos;


bool upload(character *MainCh)
{
 FILE *fr=fopen("ch","rb");
 if(fr!=NULL)
  fread(&(*MainCh),sizeof(character),1,fr);
 fclose(fr);
 return fr!=NULL;
}

void createGUI(character MainCh)
{
 system("MODE CON: COLS=100 LINES=100");
 printf("PROFILE NAME : %s",MainCh.name);
 gotoxy(80,1);
 printf("LIFE : %.1f",MainCh.life);
 gotoxy(80,3);
 printf("MONEY : %.1f",MainCh.money);
}

void initPlayer(character *MainCh)
{
 MainCh->life=100;
 MainCh->money=50;
 MainCh->score=0;
 MainCh->skills.speed=1;
 MainCh->skills.force=1;
 MainCh->skills.high=1;
 printf("Set player's name : ");
 scanf("%s",MainCh->name);
}

void endGame()
{
  gotoxy(45,4);
  printf("YOU WIN!");
}

void loseGame()
{
 gotoxy(45,4);
 printf("YOU LOSE!");
}

void boom()
{
 gotoxy(45,4);
 printf("BOOM HEADSHOT!");
 sleep(500);
 gotoxy(45,4);
 printf("              ");
}

void initEnemy(Enemy *alien)
{
 alien->life=100;
}

void download(character MainCh)
{
 FILE *fw=fopen("ch","wb");
 fwrite(&MainCh,sizeof(character),1,fw);
 fclose(fw);
}

void checkBorders(pos *curr)
{
 if(curr->x==0)
  curr->x=5;
 if(curr->y=0)
  curr->y=5;
}

void go(int dx,int dy,pos current)
{
 gotoxy(current.x,current.y);
 printf(" ");
 gotoxy(current.x+dx,current.y+dy);
 printf("#");
}

void destroy(pos posXY)
{
 gotoxy(posXY.x,posXY.y);
 printf(" ");
}

void enemyGo(int dx,pos current)
{
   gotoxy(current.x,current.y);
   printf(" ");
   gotoxy(current.x+dx,current.y);
   printf("@");
}

bool shot(int x,pos enemy,Enemy *alien,character MainCh)
{
 if(x==enemy.x)
 {
  alien->life-=25;
  if(alien->life==0)
  {
   destroy(enemy);
   endGame();
   getch();
   download(MainCh);
   exit(0);
  }
  return true;
 }
 return false;
}

void moveCh(character *MainCh,pos *curr,pos enemy,Enemy *alien)
{
int key=getch();
switch(key){
case 97:
    {
           go(-1,0,*curr);
           curr->x--;
           break;
     }

case 115:
     {  
           go(0,1,*curr);
           curr->y++;
           break;
     }
case 119:
     {
           go(0,-1,*curr);
           curr->y--;
           break;
     }
case 100:
     {
           go(1,0,*curr);
           curr->x++;
           break;
     }
 case 32:
      {
       if(shot(curr->x,enemy,alien,*MainCh))
       {
        boom();
        MainCh->money+=100;
       }
      }
  }
}

bool checkPlayerLife(float life)
{
  return life<=0;
}

void update(character MainCh,pos curr)
{
 gotoxy(87,1);
 printf("%.1f",MainCh.life);
 gotoxy(88,3);
 printf("%.1f",MainCh.money);
 gotoxy(80,5);
 printf("X=%d Y=%d\n",curr.x,curr.y);
}

void createRndObj(pos currEatPos[])
{
 srand(time(NULL));
 int index=0;
 for(;index<N_OBJ;index++)
 {
  currEatPos[index].x=rand()%75+1;
  currEatPos[index].y=rand()%55+2;
  gotoxy(currEatPos[index].x,currEatPos[index].y);
  printf("*");
 }
}

bool matchObj(pos curr,pos curr1)
{
 if(curr.x==curr1.x&&curr.y==curr1.y)
  return false;
 return true;
}

int matchPosXY(pos curr,pos currEatPos[])
{
 int index=0;
 while(index<N_OBJ&&matchObj(curr,currEatPos[index]))
  index++;
 if(index!=N_OBJ)
  return index;
 return -1;
}

void deleteObj(pos *currEatPos)
{
 gotoxy(currEatPos->x,currEatPos->y);
 printf("#");
 currEatPos->x=-1;
 currEatPos->y=-1;
}

bool checkSpawnPoint(character *MainCh,pos curr,pos currEatPos[])
{
 int index=matchPosXY(curr,currEatPos);
 if(index!=-1)
 {
     MainCh->money+=10;
     MainCh->life+=10;
     deleteObj(&currEatPos[index]);
 }
 return index!=-1;
}

void enemyShot(int PosX,int Pos1X,character *MainCh)
{
 srand(time(NULL));
 if((rand()%2+1)%2==0)
  if(PosX==Pos1X)
   MainCh->life-=25;
}

int createEnemy(character *MainCh,pos currentPos,pos *enemyPos)
{
 character Enemy;
 gotoxy(enemyPos->x,enemyPos->y);
 printf("@");
 if(currentPos.x>50&&enemyPos->x<99)
 {
  enemyGo(1,*enemyPos);
  enemyPos->x++;
 }
 else if(enemyPos->x>2)
 {
  enemyGo(-1,*enemyPos);  
  enemyPos->x--;
 }
 enemyShot(enemyPos->x,currentPos.x,MainCh);      
}



int main(){
character MainCh;
Enemy alien;
pos curr={5,5},currEatPos[N_OBJ],enemyPos={4,4};
int index=0;
if(!upload(&MainCh))
 initPlayer(&MainCh);
MainCh.life=100;
initEnemy(&alien);
createGUI(MainCh);
createRndObj(currEatPos);
curr.y=5;
gotoxy(curr.x,curr.y);
printf("#");
while(index<N_OBJ)
{
 moveCh(&MainCh,&curr,enemyPos,&alien);
 if(checkSpawnPoint(&MainCh,curr,currEatPos))
  index++;
 update(MainCh,curr);
 if(checkPlayerLife(MainCh.life))
 {
  loseGame();
  getch();
  exit(0);
 }
 createEnemy(&MainCh,curr,&enemyPos);
}
download(MainCh);
}

If you have problem with the library conio2.h you have to download it. If you have still problems set on compiler settings->linker the string "-lconio".

Read more ...

Nov 12, 2013

Meaning of Comparison, Logical, Assignment and Arithmetic Operators in C++

Unknown | 12:38 PM | 2 Comments so far

Comparison and Logical Operators

For program flow, the comparison as well as the logical operators is required. The comparison and logical operators can be grouped into three. They are relational operators, equality operators and logical operators.
      OPERATOR
                          MEANING
               <
               >
             <=
             >=
             ==
             !=
             &&
             ||
              !

     Less than
     Greater than
     Less than or equal to
     Greater than or equal to
     Equal to
     Not equal to
     Logical AND
     Logical OR
     Not

Assignment Operators


An assignment operator is used to assign back to a variable, a modified value of the present holding.
   OPERATOR
                                                       MEANING
            =

           +=

            -=

           *=

           /=

           %=

          >>=
          <<=
          &=
          \=
           %=
Assign right hand side (RHS) value to the left hand side (LHS)

Value of LHS variable will be added to the value of RHS and assign it back to the variable in LHS
Value of RHS variable will be subtracted from the value of LHS and assign it back to the variable in LHS
Value of LHS variable will be multiplied by the value of RHS and assign it back to the variable in LHS
 Value of LHS variable will be divided by the value of RHS and assign it back to the variable in LHS
The remainder will be stored back to the  LHS after integer division is carried out between the LHS variable and the RHS variable
Right shift and assign to the LHS
Left shift and assign to the LHS
Bitwise AND operation and assign to the LHS
Bitwise OR  operation and assign to the LHS
Bitwise complement and assign to the LHS


Arithmetic Operators

Arithmetic operations are the basic and common operations performed using any computer programming. Normally, these operators are considered as basic operators and known as binary operators as they require two variables to be evaluated. For example, if we want to multiply any two numbers, one has to enter or feed the multiplicand and the multiplier. That is why it is considered as a binary operator. In C++, the arithmetic operators used are as follows:
           OPERATOR
             MEANING
               +
                -
               *
               /
               %
              addition
              subtraction
              multiplication
              division
              modulo(remainder of an integer division)



Read more ...

Oct 8, 2013

C++ program to find the sum and average of given numbers using for loop

Unknown | 10:19 AM | 3 Comments so far
The for loop is the most commonly used statement in C++. This loop consists of three expressions. The first expression is used to initialize the index value, the second to check whether or not the loop is to be continued again and the third to change the index value for further iteration.
                         
Sometimes, the operations carried out by the while loop can also be done by using the for loop.
However, it is the programmer who has to decide which loop to be used in a given situation.

The syntax of the for loop is:
for (expression_1; expression_2; expression_3)
statement;
Now I am going to tell you a C++ program using the for loop. This program to find the sum and average of given numbers. The C++ program code is following bellow




// A program to find the sum and average of given numbers
#include <iostream.h>
void main (void)
{
int n;
cout <<"How many numbers ?\n";
cin >>n;
float sum = 0;
float a;
for (int i = 0; i <= n-1; ++i) {
cout <<"Enter a number \n";
cin >>a;
sum = sum+a;
}
float av;
av = sum/n;
cout <<"sum = " << sum << endl;
cout <<" Average = " << av << endl;
}
Output the above program

How many numbers ?
4
Enter a number
3
Enter a number
2
Enter a number
1
Enter a number
4
sum = 10
Average = 2.5
Read more ...

Oct 1, 2013

Display the name of the week with C++ program

Unknown | 2:37 PM | Be the first to comment!
Hi,
Today I am going to give you a simple C++ program. This following program structures display the name of the week, depending upon the number entered through the keyboard using the switch-case statementThe switch statement is a special multi way decision maker that tests whether an expression matches one of the numbers of constant values, and braces accordingly.




However, Type this following code on Turbo C++ and run your program.



// A program to display the name of the week, depending upon the number entered through the keyboard
#include <iostream.h>
void main (void)
{
int day;
cout << "Enter a number between 1 to 7 \n";
cin >>day;
switch (day) {
case 1 :
cout <<"Monday \n";
break;
case 2 :
cout <<"Tuesday \n";
break;
case 3 :
cout <<"Wednesday \n";
break;
case 4 :
cout <<" Thursday \n";
break;
case 5 :
cout <<" Friday \n";
break;
case 6 :
cout <<" Saturday \n";
break;
case 7 :
cout <<" Sunday \n";
break;
} // end of switch statement
} // end of main program

Output of the above program:

Enter a number between 1 to 7
4
Thursday

If you face any problem please inform us by commenting. We always ready to serve you.
Thanks! 
Read more ...

Sep 27, 2013

Find Prime number with C++ Program

Unknown | 4:10 PM | Be the first to comment!
Do you know what is a prime number?
A natural number greater than 1 which has only two divisors 1 and it is called a prime number. For example: 7 is a prime number. Because it has only two divisors 1 and 7 (itself).




Now I am going to tell you how to find a prime number by using C++ program. Just type these code below

//C++ Program to find Prime number
#include<iostream.h>
#include<conio.h>
        void main()
        {
         //clrscr();
         int number,count=0;
cout<<"Enter number to check it is Prime or not ";
          cin>>number;
           for(int a=1;a<=number;a++)
               {
                if(number%a==0)
                   {
                  count++;
                   }
               }
       if(count==2)
         {
          cout<<" PRIME NUMBER \n";
         }
       else
         {
          cout<<" NOT A PRIME NUMBER \n";
         }
       //getch();
       }

Thanks! 
Read more ...

Sep 17, 2013

C++ program to find the largest value among any four numbers

Unknown | 11:14 AM | Be the first to comment!
Today I am going to tell you how to find the largest value among any four numbers with a simple C++ program. You can also see how to find the largest value of any three numbers






Anyway, the C++ program code is bellow:


// A C++ program to find the largest value among any four numbers
#include <iostream.h>
void main(void)
{
 float a,b,c,d;
 cout << "Enter any four numbers \n";
 cin >>a >>b >>c >>d;
 if (a > b) {
if (a > c) {
if (a > d)
cout <<"Largest value" << a << endl;
else cout <<"Largest value" << d << endl;
}
else {
if (c > d)
cout <<"Largest value" << c << endl;
else cout <<"Largest value" << d << endl;
}
} // end of outer if part
else {
if (b > c) {
if (b > d)
cout <<"Largest value" << b << endl;
else cout <<"Largest value" << d << endl;
}
else {
if (c > d)
cout <<"Largest value" << c << endl;
else cout <<"Largest value" << d << endl;
}
} // end of outer else part
} // end of main program

Output:


Enter any four numbers 
10   40    50    70 
Largest value 70

Thanks! 
Read more ...

Sep 14, 2013

A C++ program to find the largest value of any three numbers

Unknown | 1:20 PM | Be the first to comment!
Now I am telling you how to find the largest value of any three numbers with C++ program.

If you enter any three numbers you will get the largest value from these. It's so simple and easy program.




However, Let's start our program. 

#include <iostream.h>
void main( void)
{
 float x,y,z;
 cout << "Enter any three numbers \n";
 cin >> x >> y >> z;
 if (x > y) {
if (x > z)
cout <<"Largest value" << x << endl;
else
cout <<"Largest value" << z << endl;
}
else if (y > z)
cout <<"Largest value" << y << endl;
else
cout <<"Largest value" << z << endl;
} // end of main program

You can see this output:

Enter any three numbers
10     40      50
Largest value 50
Read more ...

Sep 10, 2013

The program of compound interest in C

Unknown | 10:12 AM | Be the first to comment!
Today I am going to tell you how to get Compound Interest with C program. It is not very difficult. Very simple and easy program.

However, Let's start our program. Open your Turbo C program and enter the following codes:






#include <stdio.h>
#include <conio.h>
#include <math.h>
void main (){
float p, r, n, i, f;
clrscr ();
printf("Please enter a value for the principal (p) : );
scanf ("%f", &p);
printf("Please enter a value for the interest rate (r) : );
scanf ("%f", &r);
printf("Please enter a value for the number of Years (n) : );
scanf ("%f", &n);
i=r/100;
i=i+l
f=p*(pow (i,n));
printf ("\n The Final value (F) is : %. 3f",f);
getch ();
}



Then compile and run.

Thanks!
Read more ...

Sep 4, 2013

Simple program in C++

Unknown | 2:20 PM | Be the first to comment!
Today I am going to tell you how to create a simple C++ program.

Suppose we would like to display the message “Hello world! This is my first program” on your video screen.

#include <iostream. h>
void main()  // program heading
  {  //  begin
     cout  << "Hello world! This is my first program";
  }  //  end

The function main() must be placed before the begin statement. It invokes another function to perform its job. The { symbol or notation is used as the begin statement. The declaration of variables and the type of operations are placed after the begin statement. The end statement is denoted by the symbol  }. In C++ , the semicolon (;) serves the purpose of the statement terminator rather than a separator.

 Statements are terminated by a semicolon and are grouped within braces {….}. Most statement contains expression, sequences of operators, function calls, variables and constants that specify computation.

Variable and function names are of arbitrary length and consist of upper and lower case letters, digits and underscore and they may not start with a numeral. All C++ keywords are written in lowercase letters.
Any statement or functions within comments are not executable and they are ignored by the compiler.
Read more ...

Sep 1, 2013

About programming language C and C++

Unknown | 5:24 PM | 1 Comment so far
For the last couple of decades, the C programming language has been widely accepted for all applications, and are perhaps the most powerful of structured programming languages. In recent times, the object oriented programming (OOP) paradigm has become popular in modern software life cycles. Now, C++ has the status of a structured programming language with Object Oriented Programming (OOP) methodology, in which the software reusability, testability, maintainability, portability and reliability are the key features and requisites of modern software development.
Initially, the C++ programming language was considered as just an enhanced version of the C program with a few extra keywords. But it is not so. It is one of the well designed and widely accepted object oriented programming languages.
C++ has become quite popular due to the following reasons:

  • ·     ·         It supports all features of both structured programming and object oriented programming.
  • ·         It gives the easiest way to handle the data hiding and encapsulation with the help of powerful keyword such as class, private, public and protected.
  • ·         Polymorphism through virtual function, virtual based classes and virtual destructors give the late binding of the compiler.
  • ·         Inheritance, one of the most powerful design concepts is supported with single inheritance and multiple inheritance of base class and derived classes.
  • ·         It provides overloading of operators and functions.
  • ·         C++ focuses on function and class templates for heading parameterized data types.
  • ·         Exception heading is done with the extra keyword , namely, try, catch and throw.
  • ·         Provides friends, static methods, constructors destructors for the class objects.
  •  


This blog has been organized in such a manner that new programmers will find easy to read and understand. I have assumed the reader has no prior knowledge of C++.
Read more ...

Aug 31, 2013

What is a program?

Unknown | 3:59 PM | Be the first to comment!
A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or (strangely enough) compiling a program.

The details look different in different languages, but a few basic instructions appear in just about every language:

Input: Get data from the keyboard, a file, or some other device.

Output: Display data on the screen or send data to a file or other device.

Math: Perform basic mathematical operations like addition and multiplication.

Conditional execution: Check for certain conditions and execute the appropriate code.

Repetition: Perform some action repeatedly, usually with some variation.

Believe it or not, that’s pretty much all there is to it. Every program you’ve ever used,
No matter how complicated, is made up of instructions that look pretty much like these.
So you can think of programming as the process of breaking a large, complex task into
smaller and smaller subtasks until the subtasks are simple enough to be performed with
one of these basic instructions.
That may be a little vague, but we will come back to this topic when we talk about algorithms.
Read more ...

Aug 30, 2013

How to create a Batch Program

Unknown | 3:42 PM | 1 Comment so far
Batch file programming is the native programming offered by the Microsoft Windows Operating
System. The batch file is created using any text editors like notepad, WordPad, WinWord or so on, which comprises of a sequence of built-in commands used to perform some often done tasks like deleting a series of files of the same type or of different type, creating logs, clearing unwanted craps from your computer and even for creating a batch VIRUS.


Whenever a Batch program is executed, it was interpreted line-by-line by the CLI (Command
Line Interpreter) command.com or the cmd.exe. The batch file is really helpful in automating tedious tasks and for maintaining system logs. The commands used while creating a batch file are case insensitive, in the sense that it may accept both small and upper case letters.

How to create a Batch Program:

As said earlier, batch programs can be written using any of the text editors such as notepad, wordpad and so on, but notepad is the most often used text editors in such cases. Like any other programing languages, lets start our first program with the ‘Hello World’ program.
1. Open up a notepad and type the following.

@echo off
Echo Hello World
pause
2. Save the file with any name you wish, but make sure that you save the file extension with .bat, in this case I am saving this file as file.bat’.

3. When you save the batch file, then the icon becomes like the left icon,
In Windows XP, the Batch file icon looks like right, whereas in Windows Vista the Icon looks like the below image,




4. Just double click to execute the batch file that you have created now. And the output looks like,

5. Congratulations! You're well on your way to becoming a Batch programmer.

Let me explain what does the above given program does,
echo is the command used to print text on the screen, so whatever that follows the echo
command will be displayed on the output screen. This command is just like the printfstatement in the C language.
When you type the echo command alone, then it will tell you whether the ‘echo is ON’ or ‘echo is OFF’.
It’s always recommended to turn the echo off, else it will display the prompts like (C:\>) and so on. In order to avoid the prompts being displayed, the echo is turned off by using the command “@echo off” or simply by using the “echo off”.

“Echo Hello World” will display the “Hello World” on the output screen, and the pause command is used to wait for the user interaction, whether to proceed further or not. If the pause is not used, then the batch will terminate immediately after displaying the “Hello World”.
Read more ...
Twitter Delicious Facebook Digg Stumbleupon Favorites More

Search