Saturday, November 16, 2013

java Program to Implement Thread using Runnable Interface

Program to Implement Thread using Runnable Interface
class A implements Runnable
{
public void run()
{
for(int i=0; i<20; i++)
{
System.out.println(i);
}
}
}
class Run1
{
public static void main(String args[])
{
A a1 = new A();
Thread t = new Thread(a1);
t.start();
}
}

java program to Implement this and super Keyword

Program to Implement this and super Keyword
class vehicle
{
int id;
String color;
vehicle(int regno,String color)
{
id = regno;
this.color = color;
}
}
class vchl extends vehicle
{
int id;
String color;
vchl(int i1,int i2,String s1,String s2)
{
super(i2,s2);
id = i1;
color = s1;
}
void pdata()
{
System.out.print(super.id);
}
void ddata()
{
System.out.print(super.color);
}
public static void main(String arg[])
{
vchl v = new vchl(10,2334,"GREY","WHITE");
System.out.print("Vehicle color is ");
v.ddata();
System.out.print("\nVehicle number is ");
v.pdata();
System.out.println("\nVehicle engine color is "
+ v.color);
System.out.println("Vehicle engine id is " + v.id);
}
}
class single_inherit
{
public static void main(String a[])
{
radha m = new radha();
m.get(520,22000);
m.show1();
}
}

Wednesday, September 18, 2013

java Program to Implement the Concept of Inheritance

 Program to Implement the Concept of Inheritance
class prnt
{
int a, s;
void show()
{
System.out.println("Fathre name: Mr. Roshan Lal");
}
}
class radha extends prnt
{
void get(int x,int y)
{
a = x;
s = y;
}
void show1()
{
show();
System.out.println("Std name: Radha");
System.out.println("age:" + a);
System.out.println("salary:" + s);
}
}

class single_inherit
{
public static void main(String a[])
{
radha m = new radha();
m.get(520,22000);
m.show1();
}
}

Program to Implement the Basic Functionality of a Calculator using Switch

Program to Implement the Basic Functionality of a Calculator
using Switch
import java.io.DataInputStream;
class Cal
{
public static void main(String args[])
{
DataInputStream pt=new DataInputStream(System.in);
int x,y,z,ch;
try
{
System.out.println("Enter Value of X:");
x = Integer.parseInt(pt.readLine());
System.out.println("Enter Value of Y:");
y = Integer.parseInt(pt.readLine());
System.out.println("1.Addition\n2.Subtraction
\n3.Multiplication\n4.Division");
System.out.println("Enter ur choice:");
ch = Integer.parseInt(pt.readLine());
switch(ch)
{
case 1:
z = x + y;
System.out.println("The Addition is:"+z);
break;
case 2:
z = x - y;
System.out.println("The Subtraction
is:"+z);
break;

case 3:
z = x * y;
System.out.println("The Multiplication
is:"+z);
break;
case 4:
z = x / y;
System.out.println("The Division is:"+z);
break;
default:
System.out.println("Sorry Try
Again.........");
break;
}
}
catch(Exception e)
{
System.out.println("x.getmessage()");
}
}
}

Program to Implement Overriding of Methods

 Program to Implement Overriding of Methods
class bca
{
int d;
void get(int x)
{
d = x;
}
void display()
{
System.out.println("Bca = " + d);
}
}
class mca extends bca
{
int y;
mca(int m, int y)
{
get(m);
this.y = y;
}
void display()
{
System.out.println("Bca = " + d);
System.out.println("mca y= " + y);
}
}

class override
{
public static void main(String a[])
{
mca m = new mca(100,200);
m.display();
}
}

Friday, August 16, 2013

java Program to Implement Overloading of Methods

 Program to Implement Overloading of Methods
class prnt
{
int a, a1, s, s1;
void show()
{
System.out.println("Father name: Mr.Roshan lal");
System.out.println("Mother Name: Mrs. Madhu Gupta") ;
}
}
class radha extends prnt
{
void get(int y)
{
a = 19;
s = y;
}
void show1()
{
System.out.println("\nstd name:Radha Garg");
System.out.println("age:" + a);
System.out.println("salary:" + s);
}
}
class money extends radha
{
void get(int x1,int y1)
{
a1 = x1;
s1 = y1;
}

void show2()
{
System.out.println("\nstd name:Money Garg");
System.out.println("age:" + a1);
System.out.println("salary:" + s1);
}
void shows()
{
show();
show1();
show2();
}
}
class overloading
{
public static void main(String z[])
{
money m = new money();
m.get(20,30000);
m.get(25000);
m.shows();
}
}

java Program to Implement Multithreading

Program to Implement Multithreading
import java.lang.*;
class aa extends Thread
{
public void run()
{
for(int i=0;i<4;i++)
{
try
{
if(i == 3)
{
sleep(4000);
}
}
catch(Exception x)
{ }
System.out.println(i);
}
System.out.println(" i finished ");
}
}
class bb extends Thread
{
public void run()
{
for(int i=0; i<4; i++)
{
System.out.println(i);
}
System.out.println(" ii finished ");
}
}

class cc extends Thread
{
public void run()
{
for(int i=0; i<4; i++)
{
System.out.println(i);
}
System.out.println(" iii finished ");
}
}
class multi_thread
{
public static void main(String arg[])
{
aa a1 = new aa();
bb b1 = new bb();
cc c1 = new cc();
a1.start();
b1.start();
c1.start();
}
}

java Program to Illustrate the use of Methods of Vector Class

 Program to Illustrate the use of Methods of Vector Class
import java.util.*;
class vctr
{
public static void main(String arg[])
{
Vector list = new Vector();
int l = arg.length;
for(int i=0; i<l; i++)
{
list.addElement(arg[i]);
}
list.insertElementAt("COBOL",2);
int size = list.size();
String lary[ ] = new String[size];
list.copyInto(lary);
System.out.println("List of Languages");
for(int i=0; i<size; i++)
{
System.out.println(lary[i]);
}
}
}

java Program to Illustrate the use of Methods of String Class

Program to Illustrate the use of Methods of String Class
import java.io.*;
class String1
{
public static void main(String arg[])
{
try
{
int n = 5;
int m = 8;
char s = 'n';
String str = new String(" Radha");
String str3 = new String(" Radha ");
String str4;
System.out.println(str.equals(str3));
String str1 = str.toLowerCase();
System.out.println("The String in Lower case:"
+ str1);
String str2 = str1.toUpperCase();
System.out.println("The String in Upper case:"
+ str2);
str4 = str1.trim();
System.out.println("The String after trimming:"
+ str4);
System.out.println("The length of String:"
+ str4.length());
str2 = str1.replace('h','d');
System.out.println("The repalced String" + str2);
System.out.println(str1.equals(str2));
System.out.println("The character at position 3:"
+ str2.charAt(3));System.out.println("The substring is:"
+ str2.substring(n));
System.out.println("The substring is:"+ str2.substring(n,m));
System.out.println("The Index of O:"+ str2.indexOf(s));
}
catch(Exception s)
{
System.out.println(s.getMessage());
}
}
}

Wednesday, August 7, 2013

java Program to Illustrate the use of Methods of StringBuffer Class

 Program to Illustrate the use of Methods of StringBuffer Class

import java.io.*;
import java.lang.*;
class Stringb
{
public static void main(String args[])
{
try
{
StringBuffer str=new StringBuffer("Radha Garg");
System.out.println("\n1.Length\n2.Capacity
\n3.Setlength\n4.Charat\n5.Setcharat
\n6.Append\n7.Deletecharat\n8.Substring
\n9.Substring1\n10.Insert\n11.Reverse");
System.out.println("Enter ur chioce");
DataInputStream ds = new DataInputStream(System.in);
int ch = Integer.parseInt(ds.readLine());
switch(ch)
{
case 1:
System.out.println("The length of the
string is:" + str.length());
break;
case 2:
System.out.println("The capacity of
String:" + str.capacity());
break;
case 3:
str.setLength(15);
System.out.println("Set length of String:"
+ str.length());
break;
case 4:
System.out.println("The character at 6th
position:" + str.charAt(5));
break;
case 5:
str.setCharAt(2,'u');
System.out.println("The string after
setting position is:" +str);
break;
case 6:
System.out.println("The string after
appending:" + str.append(" Sohni"));
break;
case 7:
System.out.println("The string after
deletion:" + str.deleteCharAt(7));
break;
case 8:
System.out.println("The substring is:" +
str.substring(2));
break;
case 9:
System.out.println("The subsstring2 is:" +
str.substring(3,8));
break;
case 10:
System.out.println(" The string after
insertion is:" + str.insert(6,'m'));
break;
case 11:
System.out.println("The string after
reverse is:" + str.reverse());
}
}
catch(Exception s)
{
System.out.println(s.getMessage());
}
}
}
Output:

JAVA Program to Handle In-built Exceptions

Program to Handle any Three In-built Exceptions
class checkExcept
{
public void add()
{
try
{
int y = 20,z = 0;
int x = y/z;
System.out.println(x);
System.out.println("working");
}
catch(ArithmeticException a)
{
System.out.println("error");
}
catch(SecurityException a2)
{
System.out.println("error");
}
catch(ArrayStoreException a1)
{ }
catch(Exception x)
{
System.out.println(x.getMessage());
}
finally
{
System.out.println("finaly");
}
}

public static void main(String a[])
{
checkExcept c = new checkExcept();
c.add();
}
}


Saturday, August 3, 2013

how to increase your pc speed

[Windows Experience Index] Re-run the assessment increases the pc performance..




Start> Right-Click on Computer> Properties

Click on the Windows Experience Index link (next to the rating)

You shall get further information about how the rating is calculated and down below you shall get the Re-run the assessment option.
 

This process will remove junk files ,  clean the cache, solve the registry problems, solve the clutter problems and increase your pc performance.
[important: don't detach the power while performing this process, the process will fail. If the process failed,then you can do it again....]

how to remove virus using cmd


Here some tips using batch line.

If the virus is running in your computer find the virus name first.
If you found it
type cmd on start menu.
Then type in the command line

taskkill /IM virusname.exe /F the IM and F should be capitalize.

This command will kill or stop the virus from running in your computer.

The next thing you do is to delete all virus but first you must find the path where the virus is located.

If you found it go to the virus path using cd command. For example the virus is in system32

you must type this "cd windows\system32"

then the prompt will be in system32 and it will look like this c:\windows\system32>_

then type attrib -r -h -s virusname.exe

this command will make the virus visible.

so type then erase or del virusname.exe

Thats it...

how to set video as desktop wallpaper

setting Video As Desktop Wallpaper

Labels: tricks corner


Ever wanted to set cool videos as your computers Desktop Wallpaper, then you came to right place.
Today in this post i will teach you how to set videos as your Desktop Wallpaper with a simple nice little trick and
small tool or software that mostly every one has installed on their computer or laptop. This trick works on  Windows Xp as
 well as it works on windows 7.
 Go through below post to learn this simple trick.

How to set video as desktop wallpaper ?
   1. Open VLC Media Player. If you don't have it download it frome Here.
   2. Then Go to Tools > Preference Or press CTRL + P and Selecet Video from left panel
   3. Then Choose DirectX video output from output dropdown list
      as shown in below image . 
  4. Save the changes ans restart VLC Media Player.
   5. Play any video you would like to set as your desktop wallpaper.
   6. Then click on Video and select DirectX Wallpaper from the dropdown list as show in below image.
   

   7. Now Minimize vlc player and you will see your video running on your desktop as wallpaper.
   8. If you want your default wallpaper back then uncheck DirectX Wallpaper from video dropdown list.
   9. Hope you like this simple trick .


how to use web browser as text editor


Simple Trick To Use Web Browsers As Text Editor

Labels: tricks corner
In this tutorial i will show you a simple and interesting trick to use your web browser such as Google Chrome or Mozilla Firefox as a simple text editor like Notepad. This trick works on all web browsers. So lets get started. How To Do ?
1 Copy below code in browser Url Section data:text/html,

2. Now Press Enter.
3. Now you can type anything as would do on any other text editor like Notepad.
4. To save your text file Press Ctrl + S and save it as anything.txt (.txt Is Must)

making a nameless folder in windows


Making Nameless Folder In Windows
Labels: tricks corner

Basically you can not make folder with no name on windows. This trick will allow you to make folder without any name. This trick works on any windows  operating system.

How To Make Nameless Folder
Before attempting this trick, try to make a folder with no name and you will fail to do so. This is what this trick will let you do. Below is screenshot of folder before and after doing this interesting trick.

1.    Make a New folder on desktop or where ever you want.
2.    Right click on this newly created folder and select Rename.
3.    Erase the text showing "New Folder".
4.    Now keep Pressing Alt (i.e alter key) and type 255. If you are on laptop then you need to enable your Num Lock and type from the highlighted number keys not from those below function keys.
5.    After that leave alt key and Press enter.
6.    Done you just created nameless folder.

Monday, July 29, 2013

Java Program to Find the Sum of the Digits of a Number

Program to Find the Sum of the Digits of a Number
import java.io.*;
class Add
{
void number()
{
try
{
int num,sum=0;
System.out.println("Enter any number:");
DataInputStream dts=new DataInputStream(System.in);
int n=Integer.parseInt(dts.readLine());
while ( n > 0 )
{
num = n % 10;
n = n / 10;
sum = sum + num;
}
System.out.println("The sum of the digits is:"
+sum);
}
catch(Exception s)
{
System.out.println(s.getMessage());
}
}
}

class Digit_add
{
public static void main(String args[])
{
Add a = new Add();
a.number();
}
}


Saturday, July 27, 2013

java Program to Find Square Root of a Number

Program to Find Square Root of a Number
import java.lang.*;
import java.io.*;
class sqrt
{
public static void main(String a[])
{
try
{
DataInputStream dts=new DataInputStream(System.in) ;
System.out.println("enter number to find squaroot");
int m=Integer.parseInt(dts. readLine());
System.out.println("square root
of"+m+"="+Math.sqrt(m));
}
catch(Exception x)
{
System.out.println(x.getMessage());
}
}
}

java Program to Draw a Concentric Circles with Random Colors

Program to Draw a Concentric Circles with Random Colors

Java Source Code
import java.awt.*;
import java.applet.*;
import java.util.*;
public class cir_c extends Applet
{
public void paint(Graphics g)
{
Random rg = new Random();
for (int i=1; i<=3; i++)
{
int r = rg.nextInt(255);
int gr = rg.nextInt(255);
int b = rg.nextInt(255);
Color c = new Color(r,gr,b);
g.setColor(c);
g.drawOval(100+i*5,100+i*5,100-i*10,100-i*10);
}
}
}

Output:

java Program to Create an Application that Represents Biodata Form

 Program to Create an Application that Represents Biodata Form
import java.lang.*;
import java.io.*;
class EmployeeS
{
int age, num;
String nme, add;
void emp_Info(int x)
{
try
{
num = x;
DataInputStream dts=new DataInputStream(System.in);
System.out.println("Enter Your Name:");
nme = dts.readLine();
System.out.println("\nEnter Your Address:");
add = dts.readLine();
System.out.println("\nEnter Your Age:");
age = Integer.parseInt(dts.readLine());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
class EmployeeM extends EmployeeS
{
String dep;
int sal;
void emp_dep(int da)

{
try
{
DataInputStream pts=new DataInputStream(System.in);
System.out.println("\nEnter your Department:");
dep = pts.readLine();
System.out.println("\nEnter your Salary:");
sal = Integer.parseInt(pts.readLine());
sal = sal-((sal*da)/100);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
class EmployeeF extends EmployeeM
{
void show_info()
{
System.out.println("\nThe name of Employee is:" + nme);
System.out.println("\nThe number of Employee is:" + num);
System.out.println("\nThe address of Employee is:"
+ add);
System.out.println("\nThe age of Employee is:" + age);
System.out.println("\nThe department of Employee is:"
+ dep);
System.out.println("\nThe salary of Employee is:" + sal);
}
}
class Main
{

public static void main(String arg[])
{
EmployeeF ep = new EmployeeF();
ep.emp_Info(30);
ep.emp_dep(5);
ep.show_info();
}
}
Output:

java Program to convert Fahrenheit temperature into Celsius temperature

Program to convert Fahrenheit temperature into Celsius
temperature using command line

import java.lang.*;
import java.io.*;
class temp
{
public static void main(String a[])
{
try
{
DataInputStream dts=new DataInputStream(System.in) ;
float m=Float.parseFloat(a[0]);
double f;
f = ( ( 9 * m ) / 5 + 32 );
System.out.println("tempreture in fahrenheit ="+f);
}
catch(Exception x)
{
System.out.println(x.getMessage());
}
}
}
Output:
java Program to convert Fahrenheit temperature into Celsius temperature

java Program to Convert a Decimal Number into Binary, Octal, Hexadecimal

java Program to Convert a Decimal Number into Binary, Octal, Hexadecimal

import java.io.*;
class conversion
{
public static void main(String s[])throws IOException
{
int a;
DataInputStream ins=new DataInputStream (System.in);
System.out.println("Enter value");
a = Integer.parseInt(ins.readLine());
System.out.println("Binary:"+ Integer.toBinaryString(a));
System.out.println("Hexadecimal:" +
Integer.toHexString(a));
System.out.println("Octal:" + Integer.toOctalString(a));
}
}
Output:
java Program to Convert a Decimal Number into Binary, Octal, Hexadecimal

java program to check whether the number is palindrome or not


/*** Program to Check Whether a Number is Palindrome or Not ***/
import java.io.*;
class rev
{
public static void main(String a[ ])
{
int n, m, rev = 0;
int k = Integer.parseInt(a[0]);
n = k;
while( n > 0 )
{
m = n % 10;
rev = ( rev * 10 ) + m;
n = n / 10;
}
if( rev == k )
System.out.println("palindrome" );
else
System.out.println(" not palindrome" );
}
}
Output:
java program to check whether the number is palindrome or not

java Program to Calculate Area and Circumference of Circle

Program to Calculate Area and Circumference of Circle

import java.lang.*;
import java.io.*;
class crcl
{
public static void main(String a[])
{
try
{
DataInputStream dts=new DataInputStream(System.in) ;
System.out.println("enter radius of circle");
float m = Float.parseFloat(dts. readLine());
double area, cir;
area = 3.14 * m * m;
cir = 2 * 3.14 * m;
System.out.println("area of circle =" + area);
System.out.println("circumfrance of circle =" +cir);
}
catch(Exception x)
{
System.out.println(x.getMessage());
}
}
}
Output:

java program to add two matrix

java  program to add two matrix
import java.lang.*;
import java.io.*;
class addmatrix
{
static void add()
{
int a[][], b[][], c[][];
a = new int[2][2];
b = new int[2][2];
c = new int[2][2];
DataInputStream dts=new DataInputStream(System.in);
try
{
System.out.println("enter first matrix
2*2 order :");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
a[i][j]=Integer.parseInt(dts.readLine());
}
}
System.out.println("enter second matrix
2*2 order :");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)

{
b[i][j]=Integer.parseInt(dts.readLine());
}
}
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println("\t");
}
}
catch(Exception x)
{
System.out.println("error");
}
}
public static void main(String arg[])
{
add();
}
}
java program to add two matrices

Friday, May 3, 2013

Program to Find HCF of Two Numbers Without Recursion

Program to Find HCF of Two Numbers Without Recursion

 The following C program using iteration finds the HCF of two entered integers. The HCF stands for Highest Common Factor.
Here is the source code of the C program to find the HCF of two entered integers. The C program is successfully compiled and run on a turbo cpp.

#include <stdio.h>
main()
{
int q, m, n, temp;
printf("\nEnter values of two numbers: ");
scanf("%d %d", &m, &n);
if (m == 0)
{
printf("\nHCF of number is: %d", n);
goto end;
}
if (n == 0)
{
printf("\nHCF of numbers is: %d", m);
goto end;
}
if (n > m)
{
temp = m;
m = n;
n = temp;
}

q = 1;
while (q != 0)
{
q = m % n;
if (q != 0)
{
m = n;
n = q;
}
}
printf("\nHCF of number is: %d", n);
end:
getch();
}
what is recursive programming?
Recursive programming is a powerful technique that can greatly simplify some programming tasks. In summary, recursive programming is the situation in which a procedure calls itself, passing in a modified value of the parameter(s) that was passed in to the current iteration of the procedure. Typically, a recursive programming environment contains (at least) two procedures: first, a procedure to set up the initial environment and make the initial call to the recursive procedure, and second, the recursive procedure itself that calls itself one or more times.


Cautions For Recursive Programming
While recursive programming is a powerful technique, you must be careful to structure the code so that it will terminate properly when some condition is met. In the Fact procedure, we ended the recursive calls when N was less than or equal to 1. Your recursive code must have some sort of escape logic that terminates the recursive calls. Without such escape logic, the code would loop continuously until the VBA runtime aborts the processing with an Out Of Stack Space error. Note that you cannot trap an Out Of Stack Space error with conventional error trapping. It is called an untrappable error and will terminate all VBA execution immediately. You cannot recover from an untrappable error.

Program to Find HCF of Two Numbers using Recursion

 Program to Find HCF of Two Numbers using Recursion

 The following C program using iteration finds the HCF of two entered integers. The HCF stands for Highest Common Factor.
Here is the source code of the C program to find the HCF of two entered integers. The C program is successfully compiled and run on a turbo cpp.
#include <stdio.h>
int hcf(int, int);
main()
{
int h, i, a, b;
printf("\nEnter values of two numbers: ");
scanf("%d %d", &a, &b);
h = hcf(a, b);
printf("\nHCF of numbers is: %d", h);
getch();
}
int hcf(int a, int b)
{
if (a%b == 0)
return b;
else
return hcf(b, a%b);
}

 what is recursive programming?
Recursive programming is a powerful technique that can greatly simplify some programming tasks. In summary, recursive programming is the situation in which a procedure calls itself, passing in a modified value of the parameter(s) that was passed in to the current iteration of the procedure. Typically, a recursive programming environment contains (at least) two procedures: first, a procedure to set up the initial environment and make the initial call to the recursive procedure, and second, the recursive procedure itself that calls itself one or more times.



Cautions For Recursive Programming
While recursive programming is a powerful technique, you must be careful to structure the code so that it will terminate properly when some condition is met. In the Fact procedure, we ended the recursive calls when N was less than or equal to 1. Your recursive code must have some sort of escape logic that terminates the recursive calls. Without such escape logic, the code would loop continuously until the VBA runtime aborts the processing with an Out Of Stack Space error. Note that you cannot trap an Out Of Stack Space error with conventional error trapping. It is called an untrappable error and will terminate all VBA execution immediately. You cannot recover from an untrappable error.


c Program to Find Factorial of a Number without using Recursion

 Program to Find Factorial of a Number without using Recursion


Factorial of a Number :
Factorial of any number which should be non negative is equal to Product of all the integers less than or equal to that particular number. It is denoted by n! where n is any positive number and its factorial will be equal to :
n!=n*(n-1)*(n-2)*(n-3)... and so on till integer value 1 comes.
Let us take the example of 5! . It will be equal to 5*4*3*2*1 => 120 .
0! according to number systems is treated as 1. In this program, we shall use Recursion technique to find the Factorial of any positive number. Copy the Source code and save it as *.c . Compile and run thereafter the C Program.
#include <stdio.h>
main()
{
int n, i;
long fact=1;
printf("\nEnter any number: ");
scanf("%d", &n);
for (i=1; i<=n; i++)
fact = fact*i;
printf("\nFactorial = %ld", fact);
getch();
}

Recursion is a method of solving problems based on the divide and conquer mentality. The basic idea is that you take the original problem and divide it into smaller (more easily solved) instances of itself, solve those smaller instances (usually by using the same algorithm again) and then reassemble them into the final solution. 

Tuesday, April 30, 2013

c Program to Find Factorial of a Number using Recursion

 Program to Find Factorial of a Number using Recursion
What is Recursion in C Program :
Recursion refers to Calling the function again and again inside the body of any Program by the Same Function. In other words, It refers to thinking and then solving the problem. For Each Call of a function, the Program computes better result.

With Recursion , The Problem in C Programming can be reduced in each function call till the base value or result is reached beyond which no Call can be made or no more better result can be obtained.
Factorial of a Number :
Factorial of any number which should be non negative is equal to Product of all the integers less than or equal to that particular number. It is denoted by n! where n is any positive number and its factorial will be equal to :
n!=n*(n-1)*(n-2)*(n-3)... and so on till integer value 1 comes.
Let us take the example of 5! . It will be equal to 5*4*3*2*1 => 120 .
0! according to number systems is treated as 1. In this program, we shall use Recursion technique to find the Factorial of any positive number. Copy the Source code and save it as *.c . Compile and run thereafter the C Program.
#include <stdio.h>
long fact(int);
main()
{
int n;
long f;
printf("\nEnter number to find factorial: ");
scanf("%d", &n);
f = fact(n);
printf("\nFactorial: %ld", f);
getch();
}
long fact(int n)
{
int m;
if (n == 1)
return n;
else
{
m = n * fact(n-1);
return m;
}
}

Recursion refers to a method which solves a problem by solving a smaller version of the problem and then using that result plus some other computation to formulate the answer to the original problem. Often times, in the process of solving the smaller version, the method will solve a yet smaller version of the problem, and so on, until it reaches a "base case" which is trivial to solve.

c Program to Find Area of Square & Circumference of a Circle

Program to Find Area of Square & Circumference of a Circle


#include <stdio.h>
#define PI 3.142
main()
{
float len, r, area, circum;  //len is the length. r is the radius. circum is the  circumference
printf("\nEnter length of a square: ");
scanf("%f", &len);
area = len * len;
printf("\nEnter radius of a circle: ");
scanf("%f", &r);
circum = 2 * PI * r;
printf("\nArea of square = %.2f", area);
printf("\nCircumference of circle = %.2f", circum);
getch();
}


Basic :  The area of a square is given by the formula
area = width × height
But since the width and height are by definition the same, the formula is usually written as
area = s2
where s is the length of one side. In strictly correct mathematical wording the formula above should be spoken as "s raised to the power of 2", meaning s is multiplied by itself. But we usually say it as "s squared". This wording actually comes from the square. The length of a line s multiplied by itself, creates the square of side s. Hence "s squared".


You sometimes see the word 'circumference' to mean the curved line that goes around the circle. Other times it means the length of that line.
The word 'perimeter' is also sometimes used, although this usually refers to the distance around polygons.














c Program to Find Area of a Triangle using Hero’s Formula

// Program to Find Area of a Triangle using Hero’s Formula
#include <stdio.h>
#include <math.h>
main()
{
float a, b, c, s, area;
back:
printf("\nEnter three sides of a triangle: ");
scanf("%f %f %f", &a, &b, &c);
if (a==0 || b==0 || c==0)
{
printf("\nValue of any side should not be equal to
zero\n");
goto back;
}
if (a+b<c || b+c<a || c+a<b)
{
printf("\nSum of two sides should not be less than
third\n");
goto back;
}
s = (a + b + c) / 2;
area = sqrt(s * (s - a) * (s - b) * (s - c));
printf("\n\nArea of triangle: %.2f", area);
getch();
}


A formula for calcualting the area of a triangle when all sides are known is attirbuted to Heron of Alexandria but it is thought to be the work of Archimedes. At any rate, the formula is as follows:
A triangle has sides a, b, and c.
After Calculating S, where S = (a+b+c)/2
The Area of a Triangle = SQRT(s*(s-a)(s-b)(s-c))

c Program to Count Number of Words and Number of Characters in a String

//Program to Count Number of Words and Number of Characters in a String
#include <stdio.h>
#include <string.h>
main()
{
char str[20];
int i=0, word=0, chr=0;
printf("\nEnter any string: ");
gets(str);
while (str[i] != '\0')
{
if (str[i] == ' ')
{
word++;
chr++;
}
else
chr++;
i++;
}
printf("\nNumber of characters: %d", chr);
printf("\nNumber of words: %d", word+1);
getch();
}
Output of above program :

Enter string : c programming codes
Number of characters in string : 19
Number of words in string : 3

c Program to Copy String using strcpy()

// Program to Copy String using strcpy()
#include <stdio.h>
#include <string.h>
main()
{
char s1[20], s2[20];
printf("\nEnter string into s1: ");
gets(s1);
strcpy(s2, s1);
printf("\ns2: %s", s2);
getch();
}


(String Copy)

In the C Programming Language, the strcpy function copies the string pointed to by s2 into the object pointed to by s1. It returns a pointer to the destination.

Syntax

The syntax for the strcpy function is:
char *strcpy(char *s1, const char *s2);
s1 is an array where s2 will be copied to.
s2 is the string to be copied.

Returns

The strcpy function returns s1.

c Program to Copy one String to Another Without Using strcpy()

/* Program to Copy one String to Another Without Using strcpy() */
#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char string1[20], string2[20];
int i;
printf("Enter the value of STRING1: \n");
gets(string1);
for(i=0; string1[i]!='\0'; i++)
string2[i]=string1[i];
string2[i]='\0';
printf("\nThe value of STRING2 is:\n");
puts(string2);
getch();
}

step 1:It reads  array of strings
step 2:loop condition checks for whether  the end of the string ie '\0'.If that reaches the end ,the
loop will stop otherwise the content of the string 1 will move to the string 2
puts(string2) print the string

c Program to Copy Contents of One File to Another


// Program to Copy Contents of One File to Another
#include <stdio.h>
main()
{
FILE *fp1, *fp2;
char ch;
fp1 = fopen("abc.txt", "r");
fp2 = fopen("xyz.txt", "w");
while((ch = getc(fp1)) != EOF)
putc(ch, fp2);
fclose(fp1);
fclose(fp2);
getch();
}


 putc(), fputc(), putchar()

Write a single character to the console or to a file.

Prototypes

#include <stdio.h>

int putc(int c, FILE *stream);
int fputc(int c, FILE *stream);
int putchar(int c);

Description

All three functions output a single character, either to the console or to a FILE.
putc() takes a character argument, and outputs it to the specified FILE. fputc() does exactly the same thing, and differs from putc() in implementation only. Most people use fputc().
putchar() writes the character to the console, and is the same as calling putc(c, stdout).

fclose

int fclose ( FILE * stream );
Close file
Closes the file associated with the stream and disassociates it.

All internal buffers associated with the stream are disassociated from it and flushed: the content of any unwritten output buffer is written and the content of any unread input buffer is discarded.

Even if the call fails, the stream passed as parameter will no longer be associated with the file nor its buffers.

Parameters

stream
Pointer to a FILE object that specifies the stream to be closed.

fopen

FILE * fopen ( const char * filename, const char * mode );
Open file
Opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE pointer returned.

The operations that are allowed on the stream and how these are performed are defined by the mode parameter.

The returned stream is fully buffered by default if it is known to not refer to an interactive device (see setbuf).

The returned pointer can be disassociated from the file by calling fclose or freopen. All opened files are automatically closed on normal program termination.

The running environment supports at least FOPEN_MAX files open simultaneously.

Parameters

filename
C string containing the name of the file to be opened.
Its value shall follow the file name specifications of the running environment and can include a path (if supported by the system).
mode
C string containing a file access mode. It can be:
"r"read: Open file for input operations. The file must exist.
"w"write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
"a"append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.
"r+"read/update: Open a file for update (both for input and output). The file must exist.
"w+"write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.
"a+"append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist. 

c Program to Convert Time in Seconds to Hours, Minutes and Seconds


/*
Program to Convert Time in Seconds to Hours, Minutes and Seconds
*/
#include <stdio.h>
main()
{
long sec, hr, min, t;
printf("\nEnter time in seconds: ");
scanf("%ld", &sec);
hr = sec/3600;
t = sec%3600;
min = t/60;
sec = t%60;
printf("\n\nTime is %ld hrs %ld mins %ld secs", hr, min, sec);
getch();
}
hr = sec/3600;
This program follows the general logic of converting second to hour.ie divide the total second by 3600 thus we get the Hour,
 t = sec%3600
Then make a modular division on the total second ,thus we get the remaining seconds that can not form a hour.
min = t/60;
divide the 't' (seconds)with 60 ,then we get the remaining minutes.
sec = t%60;
modular division on the 't' result in the remaining seconds....

c Program to Convert Temperature from Degree Centigrade to Fahrenheit


/*
Program to Convert Temperature from Degree Centigrade to Fahrenheit
f = (1.8*c) + 32
*/
#include <stdio.h>
main()
{
float c, f;
printf("\nEnter temperature in degree Centigrade: ");
scanf("%f", &c);
f = (1.8*c) + 32;
printf("\n\nTemperature in degree Fahrenheit: %.2f", f);
getch();
}

This is a simple program.you just care about the formula ' f = (1.8*c) + 32' and input the 'c' value.

c Program to Concatenate Two Strings without using strcat()


// Program to Concatenate Two Strings without using strcat()
#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char string1[30], string2[20];
int i, length=0, temp;
printf("Enter the Value of String1: \n");
gets(string1);
printf("\nEnter the Value of String2: \n");
gets(string2);
for(i=0; string1[i]!='\0'; i++)
length++;
temp = length;
for(i=0; string2[i]!='\0'; i++)
{
string1[temp] = string2[i];
temp++;
}
string1[temp] = '\0';
printf("\nThe concatenated string is:\n");
puts(string1);
getch();
}


Concatenation of strings means taking two strings and joining them sequentially into one. For example, you can use the + operator to concatenate two strings:
var str1:String = "green";
var str2:String = "ish";
var str3:String = str1 + str2; // str3 == "greenish"

c Program to Concatenate Two Strings using strcat()


// Program to Concatenate Two Strings using strcat()

#include <stdio.h>
#include <string.h>
main()
{
char s1[20], s2[20];
printf("\nEnter first string: ");
gets(s1);
printf("\nEnter second string: ");
gets(s2);
strcat(s1, s2);
printf("\nThe concatenated string is: %s", s1);
getch();
}

Concatenation of strings means taking two strings and joining them sequentially into one. For example, you can use the + operator to concatenate two strings:
var str1:String = "green";
var str2:String = "ish";
var str3:String = str1 + str2; // str3 == "greenish"

c Program to Compare Two Strings Without using strcmp() .


//Program to Compare Two Strings Without using strcmp()

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char string1[5],string2[5];
int i,temp = 0;
printf("Enter the string1 value:\n");
gets(string1);
printf("\nEnter the String2 value:\n");
gets(string2);
for(i=0; (string1[i]!='\0')||(string2[i]!='\0'); i++)
{
if(string1[i] != string2[i])
{
temp = 1;
break;
}


}
if(temp == 0)
printf("Both strings are same.");
else
printf("Both strings not same.");
    return 0;
}

It takes the 2 strings .Let it be string1 and string2 .At the beginning of each array ,the for loop checks whether the string values at the corresponding positions are equal or not.If it is not ,then temp takes value 1 and exit(break) from the loop.The loop continue until the end of strings ie '\0'.If the temp value is '0' then the strings are same...

c Program to Compare Two Strings using strcmp()


/*Program to Compare Two Strings using strcmp() /
#include <stdio.h>
#include <string.h>
main()                        
{
char s1[20], s2[20];
int result;
printf("\nEnter first string: ");
gets(s1);
printf("\nEnter second string: ");
gets(s2);
result = strcmp(s1, s2);
if (result == 0)
printf("\nBoth strings are equal");
else
printf("\nBoth strings are not equal");
getch();
}

String comparison is the process of comparing whether two strings  are same or not.The function which used for this purpose is strcmp(). strcmp() is defined in 'string.h'. It's syntax is
strcmp(first string,second string);
If the two strings are equal ,it returns '0' . By using an if condition ie
if(value == 0),we get the answer...

c Program to Check Whether the Given Number is an Armstrong Number


/*
Program to Check Whether the Given Number is an Armstrong Number
*/
#include <stdio.h>
main()
{
int n, temp, d, arm=0;
printf("\nEnter any number: ");
scanf("%d", &n);
temp = n;
while (temp > 0)
{
d = temp%10;
temp = temp/10;
arm = arm + (d*d*d);
}
if (arm == n)
printf("\n\n%d is an Armstrong number\n", n);
else
printf("\n\n%d is not an Armstrong number\n", n);
getch();
}


An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3^3 + 7^3 + 1^3 = 371.
Write a program to find all Armstrong number in the range of 0 and 999.

For finding whether a number is Armstrong or not we must follow the following steps

step 1:  take each digit separately from the   right side. Using modular division with 10 satisfies our need..

d = temp%10;
step 2: 
 temp = temp/10; This step makes a number to reduce it's width from right side ie 371 to 37
step3:
Don't forgot to set the value of arm to 0.
(d*d*d) it produces the cube of the number.
arm = arm + (d*d*d);while checking this number to the original number we will get the answer.

c Program to Check Whether a Character is a Vowel or not


/*
Program to Check Whether a Character is a Vowel or not by using
switch Statement
*/
#include <stdio.h>
main()
{
char ch;
printf("\nEnter any character: ");
scanf("%c", &ch);
switch (ch)
{
case 'a':
case 'A':
printf("\n\n%c is a vowel", ch);
break;
case 'e':
case 'E':
printf("\n\n%c is a vowel", ch);
break;
case 'i':
case 'I':
printf("\n\n%c is a vowel", ch);
break;
case 'o':
case 'O':
printf("\n\n%c is a vowel", ch);
break;
case 'u':
case 'U':
printf("\n\n%c is a vowel", ch);
break;
default:
printf("\n\n%c is not a vowel", ch);
}
getch();
}
c Program to Check Whether a Character is a Vowel or not

c Program to Check Whether a Character is a Vowel or not

c Program to Calculate the Net Salary.

c Program to Calculate the Net Salary.
/*
Basic salary of an employee is input through the keyboard. The DA
is 25% of the basic salary while the HRA is 15% of the basic
salary. Provident Fund is deducted at the rate of 10% of the gross
salary(BS+DA+HRA).
Program to Calculate the Net Salary.
*/
#include <stdio.h>
main()
{
float basic_sal, da, hra, pf, gross_sal, net_sal;
printf("\nEnter basic salary of the employee: Rs. ");
scanf("%f", &basic_sal);
da = (basic_sal * 25)/100;
hra = (basic_sal * 15)/100;
gross_sal = basic_sal + da + hra;
pf = (gross_sal * 10)/100;
net_sal = gross_sal - pf;
printf("\n\nNet Salary: Rs. %.2f", net_sal);
getch();
}

c Program to Calculate the Net Salary.

Monday, April 1, 2013

visual c++(mfc) program for displaying user defined window

visual c++(mfc) program for displaying user defined window

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
myframe()
{
    CString my;
    HBRUSH hb;
    hb=(HBRUSH)::CreateSolidBrush(RGB(125,0,255));
    my=AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW),
        AfxGetApp()->LoadStandardCursor(IDC_CROSS),
        hb,AfxGetApp()->LoadStandardIcon(IDI_QUESTION);
Create(my,"my window");
}
};
class myapp:public CWinApp
{
public:
virtual BOOL InitInstance()
{
m_pMainWnd=new myframe();
m_pMainWnd->ShowWindow(1);
m_pMainWnd->UpdateWindow();
return TRUE;
}
};
myapp app;


History of visual c++ language

As the Microsoft Windows and the benefits of the graphical user interface (GUI) became widely accepted, the programming for Windows became in high demand. Programming for Windows is different from old-style batch or transaction-oriented programming. An essential difference between them is that a Windows program processes user input via messages from the operating system, while an MS-DOS program calls the operating system to get user input.
Visual C++ is a textual language which uses a graphical user interface builder to make programming decent interfaces easier on the programmer. 


 

Significant Language Features of visual c++

C++ is one of the components of Visual C++. However, its compiler can process both C source code and C++ source code. Further more, the version 4.0 compiles Fortran code as well.
Visual C++ also includes a large and elaborate collection of software development tools, all used through a windowed interface.
The 
Microsoft Visual C++  includes the tools listed below.
  • Microsoft Foundation Classes (MFC)
    A large and extensive C++ class hierarchy library that make the Windows application development easier.
  • App Wizard
    A code generator that creates a working skeleton of a Windows application with features, class names, and source code file names. It gets a programmer started quickly with a new application.
  • Class Wizard
    A program which generates code for a new class or a new function. It writes the prototypes, function bodies, and code to connect the messages to the application framework.
  • App Studio
    A resource editor which includes wysiwyg menu editor and a powerful dialog box editor.

visual c++(mfc) program to display simple message box

visual c++(mfc) program to display simple message box.

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
myframe()
{
Create(0,"my mfc");
}
OnLButtonDown()
{
    MessageBox("do u want to save?","hai",MB_YESNOCANCEL|MB_ICONQUESTION);
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
virtual BOOL InitInstance()
{
m_pMainWnd=new myframe();
m_pMainWnd->ShowWindow(1);
m_pMainWnd->UpdateWindow();
return TRUE;
}
};
myapp app;

 Visual c++
An application development tool developed by Microsoft for C++ programmers. Visual C++ supports object-oriented programming of 32-bit Windows applications with an integrated development environment (IDE), a C/C++ compiler, and a class library called the Microsoft Foundation Classes (MFC). The IDE includes an AppWizard, ClassWizard, and testing features to make programming easier. Visual C++ was introduced in 1993, and Release 4.0 became available in 1996.

visual c++(mfc) program to display dialog box

visual c++(mfc) program to  display dialog box

#include<afxwin.h>
#include<afxdlgs.h>
#include"resource.h"
class myframe:public CFrameWnd
{
public:
      myframe()
      {
        Create(0,"my mfc",WS_OVERLAPPEDWINDOW|WS_MINIMIZEBOX|WS_VSCROLL|WS_HSCROLL,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1),0,0);
      }
      CFontDialog fd;
      CFont f;
      void font()
      {
          int a,b;
          CString s;
          BOOL i,u,bd,s1;
          COLORREF c1;
          CClientDC dc(this);
          if(fd.DoModal()==IDOK)
          {
              s=fd.GetFaceName();
              a=fd.GetSize();
              b=fd.GetWeight();
              i=fd.IsItalic();
              u=fd.IsUnderline();
              bd=fd.IsBold();
              s1=fd.IsStrikeOut();
              c1=fd.GetColor();
              f.CreateFont(a,0,0,0,b,i,u,s1,0,0,0,0,0,s);
              dc.SelectObject(&f);
              dc.SetTextColor(c1);
              dc.TextOut(10,20,"HAVE A NICE DAY");
          }
      }
   
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_COMMAND(ID_MENU_FONT,font)
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
         virtual BOOL InitInstance()
         {
            m_pMainWnd=new myframe();
            m_pMainWnd->ShowWindow(1);
            m_pMainWnd->UpdateWindow();
            return TRUE;
         }
};
myapp app;


definition
A program is a list of detailed instructions.
A program is simply a list of instructions that tells the computer what to do. Computers are only dumb machines. They cannot think; they can only execute your orders within the programs that you write. Without programs, computers are worthless.

A program is to a computer what a recipe is to a cook. A recipe is nothing more than a program (a list of instructions) that tells the cook exactly what to do. The recipe's end result is a finished dish, and the end result of a computer program is an application such as a word processor or a payroll program. By itself, your computer does not know how to be a word processor. By following a list of detailed programming instructions written by a programmer, however, the computer performs the actions necessary to do word processing.

If you want your computer to help you with your household budget, keep track of names and addresses, or play a game of solitaire, you have to supply a program so that it knows how to do those things. You can either buy the program or write one yourself.

There are several advantages to writing your own programs. When you write your own programs, they do exactly what you want them to (you hope!). Although it would be foolish to try to write every program that you need to use (there is not enough time, and there are many good programs on the market), some applications are so specific that you simply cannot find a program that does exactly what you want..

visual c++(mfc) program to display the coordinates

visual c++(mfc) program to display the coordinates

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
          myframe();
          void OnLButtonDown(UINT,CPoint);
          DECLARE_MESSAGE_MAP()
};
         myframe::myframe()
          {
            Create(0,"my mfc",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX|WS_VSCROLL|WS_HSCROLL,CRect(20,20,200,200));
          }
void myframe::OnLButtonDown(UINT n,CPoint p)
          {
              char s1[20],s2[20];
              CString s;
              CClientDC dc(this);
              s=strcat(itoa(p.x,s1,10),itoa(p.y,s2,10));
              dc.TextOut(p.x,p.y,s);
          }                          // visual c++(mfc) program to display the coordinates

BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
       virtual BOOL InitInstance()
       {
         m_pMainWnd=new myframe();
         m_pMainWnd->ShowWindow(1);
         m_pMainWnd->UpdateWindow();
         return TRUE;
       }
};
myapp app;

Coordinates (x, y) are used to give positions on a graph. The x-axis is across, the y-axis is vertical.


  • The point (0,0) is called the origin.
  • The horizontal axis is the x-axis.
  • The vertical axis is the y-axis
The x-axis is horizontal, and the y-axis is vertical.
One way to remember which axis is which is 'x is a cross so the x axis is across'.

Coordinates

Coordinates are written as two numbers, separated by a comma and contained within round brackets. For example, (2, 3), (5, 7) and (4, 4)
  • The first number refers to the x coordinate.
  • The second number refers to the y coordinate.
Coordinates are written alphabetically - so x comes before y (x, y). One way to remember is 'you go along the hallway before you go up the stairs'


Plotting coordinates

When describing coordinates, always count from the origin.
For example, to describe the position of point A, start at the origin and move two squares in the horizontal (x) direction. Then move three squares in the vertical (y) direction.

visual c++(mfc)program for dealing with client area

visual c++(mfc) program for dealing with client area .
#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
     myframe()
     {
       Create(0,"my mfc");
     }
     void OnLButtonDown()
     {
         MessageBox("clientarea",0,0);
     }
     void OnNcLButtonDown(UINT x,CPoint p)
     {
         CClientDC dc(this);
             switch(x)
         {
case HTMENU:MessageBox("MENU","my program");break;
case HTCAPTION:MessageBox("CAPTION","my program");break;
case HTCLOSE:MessageBox("CLOSE","my program");break;
case HTTOP:MessageBox("TOPBOUNDARY","my program");break;
case HTBOTTOM:MessageBox("BOTTOM BOUNDARY","my program");break;
case HTLEFT:MessageBox("LEFT BOUNDARY","my program");break;
case HTRIGHT:MessageBox("RIGHT BOUNDARY","my program");break;
case HTZOOM:MessageBox("MAXIMUM","my program");break;
case HTREDUCE:MessageBox("MINIMUM","my program");break;
case HTVSCROLL:MessageBox("VERTICAL SCROLL BAR","my program");break;
         }
     }

     DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_NCLBUTTONDOWN()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
      virtual BOOL InitInstance()
      {
        m_pMainWnd=new myframe();
        m_pMainWnd->ShowWindow(1);
        m_pMainWnd->UpdateWindow();
        return TRUE;
      }
};
myapp app;

 As I understand it MFC are objects that consists of blocks of code that performs a particular function in a Windows environment. These objects enable the programmer to create Windows programs more speedily by using an existing library.

Examples of these functions are classes that enables the user to exit from a dialog by clicking on an exit button or selecting a particular option from a list.

M Visual C++ contains the full library of Microsoft classes and an environment in which to build programs, as you view its gradual development.


What is client area in vc++?

 It's the area inside a form, control or window without including any borders or frames around it.

 What is meaning of   window's client area?
 The client area is the inside area of window excluding the title bar, tool bars, status bar, scroll bars. For example in case of Internet Explorer the area in which the web pages are displayed.

visual c++(mfc) program to choose a menu item using keyboard accelerator key

             /*TO CHOOSE A MENU ITEM USING KEYBOARD ACCELERATOR KEY*/


#include<afxwin.h>
#include"resource.h"
class myframe:public CFrameWnd
{
public:
          myframe()
          {
          LoadAccelTable(MAKEINTRESOURCE(IDR_ACCELERATOR1));
            Create(0,"my mfc",WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1));
          }
          void line()
          {
              RedrawWindow();
              CClientDC dc(this);
              dc.LineTo(100,100);
          }
       
             
          void rectangle()
          {
              RedrawWindow();
              CClientDC dc(this);
              dc.Rectangle(100,100,200,200);
          }
       
          DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_COMMAND(1,line)
ON_COMMAND(2,rectangle)
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
        virtual BOOL InitInstance()
        {
           m_pMainWnd=new myframe();
           m_pMainWnd->ShowWindow(1);
           m_pMainWnd->UpdateWindow();
           return TRUE;
        }
};
myapp app;


MFC Menus


Menu programming is the next step to be learnt in MFC after learning message maps. MFC provides two ways of programming menus. One is by using the resource option and the second is by using the dynamic menu option. This part of MFC Tutorial discusses about the Resource option.
    The following steps will explain how to add a menu to this MFC Tutorial application.

    Step 1:
        Create the project with out adding any files by selecting "Empty project" option.
    Step 2:
        After the project gets created, click on Project --> Add To Project --> New and select SourceFile (.cpp File) option. Give any name to the file and click OK.

    Step 3:
        Copy the previous MFC Tutorial 2 code. Do not forget to choose the MFC Library by clicking Menu --> Project --> Settings --> General --> Microsoft Foundation Classes as "Use MFC as Shared Library".
    Step 4:
        Choose Menu --> Insert --> Resource. Select Menu from the list of resources. Click "New" and create one popup item as "File" and one menu item under this "File" as "New". Press enter on this "New" menu item and open the properties. Enter IDM_FILE_NEW as the menu resource ID in the resource id box. Press the Enter key again.
    Step 5:
        A new resource file will be created. Save this resource file.
    Step 6:
        Click Project --> Add To Project --> Files and select the two new filesScript1.rc and resource.h.
    Step 7:
        Now add the highlighted code into the project at the appropriate places. This code shows you how to
  • load the menu resource into a CMenu class
  • set the menu to the window
  • writing handlers for the menu items.



Using ProcessMessageFilter to handle dialog-based accelerator keys

Let's say you have a menu in your dialog based app. And you have an accelerator key for some particular task. You'll soon be disappointed to find that the hotkey does not work. The problem is that the modal dialog app's message loop does not call TranslateAccelerator. I do not know why this is so. Presumable the Microsoft team decided that people shouldn't use dialog based apps to write complicated applications, with hotkeys and menus.
But as usual they have suggested a workaround too. Here's is how you go about implementing it. I'd like to state again, that even though this is a Microsoft recommended technique there will be a good majority of MFC gurus, like Joseph Newcomer for example, who would tell you that you shouldn't be doing this. But then sometimes you have to sacrifice elegance for getting things done quickly and with minimum effort.
  • Add a member variable to your CWinApp derived class.
  • HACCEL m_haccel;
  • Use the resource editor to create a new Accelerator, by default it will be named IDR_ACCELERATOR1. And add a new accelerator key that is a short cut for some menu item.
  • Put the following line in your InitInstance just before the line where the CDialog derived object is declared
  • m_haccel=LoadAccelerators(AfxGetInstanceHandle(), 
            MAKEINTRESOURCE(IDR_ACCELERATOR1));
  • Now override ProcessMessageFilter and modify the function so that it looks like :-
    BOOL CPreTransTestApp::ProcessMessageFilter(int code, LPMSG lpMsg) 
    {
        if(m_haccel)
        {
            if (::TranslateAccelerator(m_pMainWnd->m_hWnd, m_haccel, lpMsg)) 
                return(TRUE);
        }
     
        return CWinApp::ProcessMessageFilter(code, lpMsg);
    }
All we did was to call TranslateAccelerator and if it succeeds then we don't need to call the base class ProcessMessageFilter, as the message has been handled. So we return TRUE.