Tuesday, June 28, 2011

IF statement in C program

0 comments

                    The if statement controls conditional branching.The body of an if statement is executed if the value of the expression is nonzero.The if statement allows you to control if a program enters a section of code or nor based on whether a given condition is true or false.One of the important function of the if statement is that it allows the program to select an action based upon the user's input.For example we can check user entered password by using if statement,and decide whether a user is allowed access to the program. 

Syntax is:

if(expression)
Execute this line of code


Example:


#include<stdio.h>
void main()
{
int number;
printf("Enter the number");
scanf("%d",&number);
if(number<5) /*if number less than five*/
{
printf("The number is less than five");
}
getch():
}


I recommended always putting braces following if statements.If you do this,you never have to remember to put them in when you want more than one statement to executed,and you make the body of the if statement more visually clear.

Else

 When the condition in an if statement evaluates to false,it would be nice to some code instead of the code executed when the statement evaluates to true. The else statement effectively says that whatever code after it is executed if the if statement is false.

Syntax is:

if(expression is TRUE)
 { 
 Execute this code 
 }
else 

Execute this code
 }

Example:

#include<stdio.h>
void main()
{
int num;
printf("Enter the number");
scanf("%d",&num);
if(num==5);
{
printf("The entered number is 5");
}
else
{
printf("The entered number is not 5");
}
getch():
}

Else if

When there are multiple conditional statements that may all evaluates to true,yet you want only if statements body to execute.You can use an else if statement following an if statement and it's body.If the first statement is true,the else if will be ignored,but if the if statement is false,it will then check condition for the else if statement.we can use numerous else if statements to ensure that only one block of code is executed.

Example:

#include<stdio.h>
void main()
{
int num;
printf("Enter the number 1 or 2 or 3");
scanf("%d",&num);
if(num==1)
{
printf("The entered number is one");
}
else if(num==2)
{
printf("The entered number is two");
}
else if(num==3)
{
printf("The entered number is three");
}
else
{
printf("number is invalid");
}
getch();
}


<<Prev Home Next>>

Continue reading →

C PROGRAM TO REVERSE A NUMBER USING WHILE LOOP

2 comments
/*Program to reverse a number using while loop*/
#include<stdio.h>
void main()
{
long int number,reverse,n;
clrscr();
printf("Enter the number");
scanf("%ld",&number);
reverse=0;
while(number!=0)
{
n=number%10;
reverse=reverse*10+n;
number=number/10;
}
printf("The reverse number=%ld\n",reverse);
getch();
}
Continue reading →

TO FIND THE SUM OF DIGITS IN A FIVE DIGIT NUMBER

0 comments
#include<stdio.h>
void main()
{
int digit_1,digit_2,digit_3,digit_4,digit_5,sum,number,n;
printf("Enter a five digit number");
scanf("%d",&number);
n=number;
digit_1=n%10;
n=n/10;
digit_2=n%10;
n=n/10;
digit_3=n%10;
n=n/10;
digit_4=n%10;
n=n/10;
digit_5=n;
sum=digit_1+digit_2+digit_3+digit_4+digit_5;
printf("sum of digits=%d\n",sum);
getch();
}

Continue reading →
Monday, June 27, 2011

How Use Loops in C-'DO WHILE' Loops

0 comments



'DO WHILE' loops are useful for things that want to loop at least once.The syntax is:
do
{
Code to execute
}while(condition);

Example:
#include<stdio.h>
int main()
{
int x;
x=0;
do
{/*"Hello World!" is printed at least one time even though the condition is false*/
printf("Hello World!");
}
while(x!=0);
getchar();
}
Notice that the condition is tested at the end of the block instead of beginning ,so the block will be executed at least once.If the condition is true,we jump back to the beginning of the block and execute it again.A DO WHILE loop is almost  the same as WHILE loop except that the loop body is guaranteed to execute at least once.A WHILE loop says"Loop while the condition is true,and execute this block of code".A DO WHILE loop says"execute this block of code,and then continue to loop while the condition is true". Notice that this loop will execute once,because it automatically execute before checking the condition.


<<Prev Home Next>>
Continue reading →
Sunday, June 26, 2011

How Use Loops in C-'While' Loops

0 comments


WHILE loops are very simple and the syntax is:
while(condition)
{
Code to execute while the condition is true
}
 The true represent a boolean expression which could be while(x==1) or while(x!=7),x does not equal to 7.It can be any combination of boolean statements that are legal.Even, while(x==5||y==7) which says execute the code while x equal to 5 or y equal to 7.


Example:


To print numbers up to 10:
#include<stdio.h>
int main()
{
int x=0;  /*Don't forget to declare variables*/
while(x<10) /*while x less than 10*/
{
printf("%d",x);
x++; /*Update x so the condition can be met eventually */
}
getchar();
}
This was another example ,but it is longer than FOR loop.The easiest way to think of the loop is that when it reach the brace at the end it jumps back up to the beginning of the loop,which check the condition again and decides whether to repeat the block another time,or stop and move to the next statement after the block.


More example using 'while' loop


<<Prev Home Next>>

Continue reading →

How Use Loops in C-'FOR' Loops

0 comments

Loops are used to repeat a block of code.Loops are one of the most basic but useful task in programming.We can simply produce extremely complex out put using loops.A loops let you write a very simple statement to produce a significantly greater result  simply by repetition.


FOR LOOPS:


FOR loops are the most useful one.The syntax of FOR loops:
for(variable initialization; condition; variable update)
{
code to execute while the condition is true
}
Example:


To print numbers upto 10:
#include<stdio.h>

int main()
{
    int x;
    /* The loop goes while x < 10, and x increases by one every loop*/
    for ( x = 0; x < 10; x++ ) {
        /* Keep in mind that the loop condition checks 
           the conditional statement before it loops again.
           consequently, when x equals 10 the loop breaks.
           x is updated before the condition is checked. */  
        printf( "%d\n", x );
    }
    getchar();
}


The variable initialization allows you to either declare a variable and give it a value or give it a value to already existing variable.The condition tells the program that while the conditional expression is true the loop should continue to repeat it self.The variable update section is the easiest way for a FOR loop to handle changing of the variable.It is possible to do things like X++,X=X+10 or even X=random(3).Notice that a semicolon separates each of these sections. Also note that every single one of the sections may be empty,though the semicolon still have to be there


This program is a very simple example of a for loop.x is set to zero,while x is less than 10 it calls printf to display the value of variable x,and it adds 1 to x until the condition is met.Keep in mind also that the variable is  incremented after the code in the loop is run for the first time


<<Prev Home Next>>

Continue reading →
Thursday, June 23, 2011

Shiny Text-C Program

0 comments

We can able to create shiny text using simple and small C code.Copy and Paste the below code into your TURBO C++ 3.0 complier.Run the program.You can see its effect on colored monitor.


Source Code:

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

int main()
{
char *name;
int len,count,place,row;
clrscr();
textbackground(0);
printf("\n Enter Your Name : ");
gets(name);
len=strlen(name); // Find the Length of name
for(count=0;count<=len;count++)
{
row=30;
for(place=0;place
{
if(place==count)
{
textcolor(13);
gotoxy(row++,10);

cprintf("%c",name[count]);
}
else
{
textcolor(10);
gotoxy(row++,10);
cprintf("%c",name[place]);
}
}
delay(200); // Wait for 200 milliseconds

}
return 0;

}






Continue reading →
Tuesday, June 21, 2011

C Program to Play Wave File

0 comments

Hi Friends,here we will discuss about how to play a Wave file using C program.i found source code to play Wave file.Copy and Paste ,compile using Turbo C++ 3.0.

Source Code:


//Include files
#include "ALLOC.H"
#include "DOS.H"
#include "CONIO.H"
#include "STDIO.H"
void playwav(char wavefile[14],float delaytime);
struct WaveData {
  unsigned int SoundLength, Frequency;
  char *Sample;
};
struct HeaderType {
  long         RIFF;      //RIFF header
  char         NI1 [18];  //not important
  unsigned int Channels;  //channels 1 = mono; 2 = stereo
  long         Frequency; //sample frequency
  char         NI2 [6];   //not important
  char         BitRes;    //bit resolution 8/16 bit
  char         NI3 [12];  //not important
} Header;
struct WaveData Voice;         //Pointer to wave file
unsigned int    Base;          //Sound Blaster base address
char            WaveFile [25]; //File name for the wave file to be played
/****************************************************************************
** Checks to see if a Sound Blaster exists at a given address, returns     **
** true if Sound Blaster found, false if not.                              **
****************************************************************************/
int ResetDSP(unsigned int Test)
{
  //Reset the DSP
  outportb (Test + 0x6, 1);
  delay(10);
  outportb (Test + 0x6, 0);
  delay(10);
  //Check if (reset was succesfull
  if ((inportb(Test + 0xE) & 0x80 == 0x80) && (inportb(Test + 0xA) == 0xAA))
  {
    //DSP was found
    Base = Test;
    return (1);
  }
  else
    //No DSP was found
    return (0);
}
/****************************************************************************
** Send a byte to the DSP (Digital Signal Processor) on the Sound Blaster  **
****************************************************************************/
void WriteDSP(unsigned char Value)
{
  //Wait for the DSP to be ready to accept data
  while ((inportb(Base + 0xC) & 0x80) == 0x80);
  //Send byte
  outportb (Base + 0xC, Value);
}
/****************************************************************************
** Plays a part of the memory                                              **
****************************************************************************/
void PlayBack (struct WaveData *Wave)
{
  long          LinearAddress;
  unsigned int  Page, OffSet;
  unsigned char TimeConstant;
  TimeConstant = (65536 - (256000000 / Wave->Frequency)) >> 8;
  WriteDSP(0x40);                  //DSP-command 40h - Set sample frequency
  WriteDSP(TimeConstant);          //Write time constant
  //Convert pointer to linear address
  LinearAddress = FP_SEG (Wave->Sample);
  LinearAddress = (LinearAddress << 4) + FP_OFF (Wave->Sample);
  Page = LinearAddress >> 16;      //Calculate page
  OffSet = LinearAddress & 0xFFFF; //Calculate offset in the page
  /*
      Note - this procedure only works with DMA channel 1
  */
  outportb (0x0A, 5);              //Mask DMA channel 1
  outportb (0x0C, 0);              //Clear byte pointer
  outportb (0x0B, 0x49);           //Set mode
  /*
      The mode consists of the following:
      0x49 = binary 01 00 10 01
                    |  |  |  |
                    |  |  |  +- DMA channel 01
                    |  |  +---- Read operation (the DSP reads from memory)
                    |  +------- Single cycle mode
                    +---------- Block mode
  */
  outportb (0x02, OffSet & 0x100); //Write the offset to the DMA controller
  outportb (0x02, OffSet >> 8);
  outportb (0x83, Page);           //Write the page to the DMA controller
  outportb (0x03, Wave->SoundLength & 0x100);
  outportb (0x03, Wave->SoundLength >> 8);
  outportb (0x0A, 1);              //Unmask DMA channel
  WriteDSP(0x14);                  // DSP-command 14h - Single cycle playback
  WriteDSP(Wave->SoundLength & 0xFF);
  WriteDSP(Wave->SoundLength >> 8);
}
/****************************************************************************
** Loads a wave file into memory.                                          **
** This procedure expects a _very_ standard wave header.                   **
** It doesn't perform much error checking.                                 **
****************************************************************************/
int LoadVoice (struct WaveData *Voice, char *FileName)
{
  FILE *WAVFile;
  //If it can't be opened...
  WAVFile = fopen(FileName, "rb");
  if (WAVFile == NULL) {
    //..display error message
    return (0);
  }
  //Return length of file for sound length minus 48 bytes for .WAV header
  fseek(WAVFile, 0L, SEEK_END);
  Voice->SoundLength = ftell (WAVFile) - 48;
  fseek(WAVFile, 0L, SEEK_SET);
  //Check RIFF header
  if (Voice->SoundLength > 32000) {
    if (Voice->SoundLength > 64000) {
      Voice->SoundLength = 64000;
    }
  }
  free(Voice->Sample);
  Voice->Sample = (char *)malloc(Voice->SoundLength); //Assign memory
  if (!Voice->Sample) {
     
    return (0);
  }
  //Load the sample data
  fread(&Header, 46, 1, WAVFile);
  //Check RIFF header
  if (Header.RIFF != 0x46464952) {
    printf ("Not a wave file\n");
    return (0);
  }
  //Check channels
  if (Header.Channels != 1) {
    printf ("Not a mono wave file\n");
    return (0);
  }
  //Check bit resolution
  if (Header.BitRes != 8) {
    printf ("Not an 8-bit wave file\n");
    return (0);
  }
  Voice->Frequency = Header.Frequency;
  //Load the sample data
  fread(Voice->Sample, Voice->SoundLength + 2, 1, WAVFile);
  fclose (WAVFile); //Close the file
  return (1);
}
void playwav (char wavefile[14], float delaytime = 1.0 )
{
  if (ResetDSP (0x220)) {
    //at 220h
    printf ("");
  } else {
    if (ResetDSP (0x240)) {
      //at 240h
      printf ("");
    } else {
      //or none at all
      printf ("");
      return;
    }
  }
  //Load wave file
  if (LoadVoice (&Voice, wavefile)) {
    //Start playback
    PlayBack (&Voice);
    delay(delaytime*1000);
    //Stops DMA-transfer
    WriteDSP (0xD0);
  }
}


/*************************END*************************/



Enjoy C Programming :)









printf("Pls Add Your Comments Thanks\n");

Continue reading →
Thursday, June 16, 2011

How to Compile C in Linux

0 comments


How to Compile C program in Linux/Unix ?:

Some people have doubts about how to compile C source code in Linux/Unix.Firstly you need GNU project C and C++ compiler for compiling C program and create executable(EXE) file.Most Linux and Unix user start compiling their C program by the name cc.But you can use gcc command to compile program.


  • First make sure you have gcc installed.
Type the following Command in Terminal to verify that gcc is installed:
which gcc

Output:
/usr/bin/gcc
  •   Find out version of gcc:
gcc --version

Output:
gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE

  • To compile C program you need to use syntax as follows:
gcc program.c -o program-output

Use text editor such as vi or gedit to creat a c program called sample.c
For example open gedit and type your code and save as sample.c


Type the following code:
#include<stdio.h>
int main(void){
printf("Hello! World.This is my sample program in C\n");
return 0;
}

How do compile my C program?:

  • To compile my sample.c program:
gcc sample.c -o sample

  • To execute C program:
./sample




Continue reading →
Monday, June 13, 2011

UBUNTU LINUX 11:04 REVIEW

0 comments
                         Ubuntu Linux released new version of Ubuntu named as Ubuntu 11:04  Natty Narwhal. Normally Ubuntu considered as Linux based Windows.About 12 million Desktop computer running under Ubuntu operating system.Ubuntu OS differed from other Linux OS by it's easy to use ability.

                         I upgraded my later version Ubuntu 10:10 to Ubuntu 11:04 Natty Narwhal.Ubuntu is almost free from virus attack compared to Windows OS.Ubuntu is free and open source OS.So we can use it freely.

Main advantages of Ubuntu
  1. It's a free and open source OS.
  2. Almost zero virus attacks compared to Windows.
  3. Speedy network and Secure.
  4. Easy to use as Windows OS.
  5. Speedy computing.
  6. Almost all useful applications are free and we can buy other applications.
  7. We can Run Ubuntu OS in low RAM computer also.And many more.

Software Changes in Ubuntu 11:04

                           Many softwares are updated to new versions.Banshee replaced Rhythmbox as default media player.LibreOffice has replaced OpenOffice.It also come with the new generation browser Firefox 4.0.Linux Kernel 2.6.38.3, Nautilus 2.32.2, Gnome 2.32.1,Empathy 2.34.0,Banshee 2.0,Compiz 0.9.4 and many more.

Some screen shots of Ubuntu 11:04 Natty Narwhal

 Ubuntu Work Places


We can access four Work Places in Ubuntu 11:04 and navigate between Work Places

Latest Chrome Browser



New Wallpaper and Improved Theme 


The desktop has been totally advanced to a new level.The background has been changed slightly and 17 new wallpapers have been added.The default Ambiance theme has been once again improved.

Ubuntu Software Center


The new Software Center offers users review ,better support to buy applications.it also provides suggestions and applications to install.We can easily download and install(Automatically) from Software Center.

Scroll Bars



Another worthwhile feature in this release is the overlying scroll bars(they appear were the scroll bar should be).This increase the productivity of windows.

Control Center




Other Changes in Ubuntu 11:04

  1. Improved Installer.
  2. Revamped Indicator Applet.
  3. Built in support for installing proprietary software-automatically,straight from the file manager.
  4. Better support for iPhone-User can mount the iPhone's documents directory now.
  5. Support for multi-arc-to install library packages of different architectures.
  6. Ubuntu One Control Panel-integrated into unity,the new control panel for Ubuntu One offers users a great control over their cloud account.

Download Ubuntu 11:04 Natty Narwhal

Download Ubuntu 11:04 from here
Download Ubuntu 11:o4


For more information about new feature and working of Ubuntu 11:04 Natty Narwhal,see the Video





Pls add your comments.Thanks!           Enjoy :)




Continue reading →
Sunday, June 12, 2011

MAKE SIMPLE GAME IN C

0 comments



Hi friends,here we will make a simple Game in C language.Enjoy C programming.Compile below code and Generate EXE file. 

Source code of Game:

#include <stdio.h>
#include <conio.h>
#include <dos.h>
#include <graphics.h>
#include <stdlib.h>
#include <time.h>

#define PAS 20

struct time t;
int keye=250;
int coordX=0;
int coorde=0;
int coordY=0;
int coordYe=0;
int tmp=0;
int tmp2=0;
int i;

void moveMyshipLeft(void);
void moveMyshipRight(void);
void moveMyshipUp(void);
void moveMyshipDown(void);
void desenMyShip(int,int,int);

void getConflict(it coordX,int coordXe,int coordY,int coordYe)
{
int stuffz,stuffy;
stuffz=coordX;
}
int getSecTime(void)
{
gettime(&t);
return t.ti_hund;
}
int pressedKey(void)
{
keye=getch();
return(keye);
}

void desenEnemyShip(int coordXe,int coordYe,int culoare)
{
setfillstyle(1,culoare);
bar(0+coordXe,0+coordYe,60+coordXe,40+coordYe);

}
void initDefault(void)
{
}
void desenEnemyShip(int coordX,int coordY,int culoare)
{
setfillstyle(1,culoare);
bar(coordX,coordY,60+coordX,40+coordY);
getConflict(coordX,coordY,coordXe,coordYe);
}

void moveMyShip(void)
{
if ((keye==75) && coordX >getmaxx()-1023)
{
moveMyShipLeft();
}
if ((keye==77) && coordX >getmaxx()-1023)
{
moveMyShipRight();
}
if ((keye==80) && coordY
{
moveMyShipUp();
}
if ((keye==72) && coordY >getmaxy()-767)
{
moveMyShipDown();
}

}
void moveEnemyShips(int coordXe,int coordYe,int culoare)
desenEnemyShip(coordXe,coordYe,0);
coordYe=coordYe+1;
desenEnemyShip(coordXe,coordYe,culoare);
tmp=getSecTime();
}
void initEnamies(void)
{
}
void moveMyShipLeft(void)
{
desenMyShip(coordX,coordY,0);
coordX=coordX-PAS;
desenMyShip(coordX,coordY,2);
}
void moveMyShipRight(void)
{
desenMyShip(coordX,coordY,0);
coordX=coordX+PAS;
desenMyShip(coordX,coordY,3);
}
void moveMyShipUp(void)
{
desenMyShip(coordX,coordY,0);
coordY=coordX+PAS;
desenMyShip(coordX,coordY,4);
}
void moveMyShipDown(void)
{
desenMyShip(coordX,coordY,0);
coordY=coordX-PAS;
desenMyShip(coordX,coordY,5);
}
int huge DetectVGA256(void)
{
int vid=4;
return vid;
}
void doGame(void)

{
initDefault();
coordYe=1000;
do
{
if(coordYe>8oo)
{
coordXe=rand()%1023;
coordYe=40;
}
if(kbhit()){
pressedKey();
moveMyShip();
}
desenMyShip(coordX,coordY,4);
if(getSecTime()+10!=tmp+10)
{
desenEnemyShip(coordXe,coordYe-15,coordY-15,0);
moveEnemyShips(coordXe,coordYe,12);
coordYe=coordYe+15;
}
}
while (keye!=27);
}
void main(void)
{
int gdriver,gmode,errorcode;
gdriver=installuserdriver("svga256",DetectVGA256);
gdriver=DETECT;
initgraph(&gdriver,&gmode,"..\bgi\svga256.bgi");
errocode=graphresult();
if(errorcode!=gr0k)
{
printf("Graphics error:%s\n",grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}
doGame();


Pls add your comments.Thanks! Enjoy! :)


Continue reading →