Showing posts with label Pakistan. Show all posts
Showing posts with label Pakistan. Show all posts

Saturday, 6 December 2014

Factorial Calculator in C


//this is a small program that will get you how to calculate factorial in C


//------------------------------------------------------------------------------
#include<stdio.h>

#include <conio.h>
int main()
{
int w=1, x ,  y , z=1;


printf("factorial theorem\n");


scanf("%d",  &y );


for (x=1;x<y ; x++){

    z=x*z;

    printf("%d!=%d\n",w, z);
    w++;
    
}

getch();


}


/*
x=loop variable.......
y=limit of table
w=value--jis ka factorial at the moment liya jaa rha hai i.e. 0! ,1!,2!....
z= answer of factorial
*/

Let's Start with C Programming - 1st program

Let us start with C-ANSI programming. 
I will post all the material of C programming as much as I learnt.

Actually C was 1st programming language that I learn , to Complete Course Requirements of My 1st Semester of Electrical Engineering. I really Enjoyed this Course, after 6 months of starting it , i can make conversation in 5 Different programming languages.

let's start with 1st program, that is Assalam u Alikum World program

C code 
 //-----------------------------------------------------------------------------

#include<stdio.h>
int main()
{
printf("Assalam u Alikum World \n"); 
return 0;
}
//------------------------------------------------------------------------------
the above code segment is 1st program of C language which is usually taught.

#include<stdio.h>
this line indicates compiler to include library named in "<>"
Stdio.h is standard Input Output Library in C.

Int main()
 it indicates initialization of main function of integer type.
At this stage i will only say that C language program  includes many function, and "main" function is most important , in which we write the basic code.

{}
these brackets indicate boundary of a block/function.

printf("Assalam u Alikum World \n");
printf() is function for displaying something as output on screen.

return 0 ;
indicates successful termination.



For C language I will Recommend Following Books
The C programming Language By Brian W. Kernighan and Dennis M. Ritchie.
 C How to Program by Dietel and Dietel

Scientific Calculator using Java

Assalam u Alikum Everyone!

Once I made a simple Java Calculator - I have decided to make it open source :)




so here goes the complete code for this java calculator.


import java.awt.FlowLayout;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

    
public class Calculator
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(new Runnable()
         {
            public void run()
            {  

               CalculatorFrame frame = new CalculatorFrame();
               frame.setSize(800, 211);
     
               JLabel label= new JLabel("<html><FONT SIZE=28><font color=#FF0000>A</font><font color=#00FF00>H</font><font color=00FFFF>M</font><font color=#FFFF00>A</font><font color=#0000FF>D</font>"
                       + "<font color=FF00FF> O</font><font color=#FF0000>S</font><font color=FF00FF>A</font><font color=#C0C0C0>M</font><font color=#FF0000>A</font></FONT> presents <br></FONT>" 
                       +"NUST School of Electrical Engineering<br> and Computer Science<br>" +
                       "<br>Scientific Calculator v3.0<br>"  + 
                       "<br>FB.ME/FRONTLINE.FIGHTER<br>FRONTLINE.FIGHTER@LIVE.COM"+
                       "<<br>Any Comments / Critisim is HeartIly accepted",JLabel.RIGHT);
            
            Container contentPane = frame.getContentPane();
         contentPane.add(label);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               frame.setVisible(true);
            }
         });
   }
}

/**
 * A frame with a calculator panel.
 */
class CalculatorFrame extends JFrame
{
   public CalculatorFrame()
   {
      setTitle("Scientific Calculator by Mohammed Ahmad Osama - fb.me/frontline.fighter");
      CalculatorPanel panel = new CalculatorPanel();
      add(panel);
      pack();
   }
}

/**
 * A panel with calculator buttons and a result display.
 */
class CalculatorPanel extends JPanel
{
   public CalculatorPanel()
   {
      setLayout(new BorderLayout());

      result = 0;
      lastCommand = "=";
      start = true;

      // add the display

      display = new JButton("0.00000");
      display.setEnabled(false);
      add(display, BorderLayout.NORTH);
display.setBackground(Color.cyan);


      ActionListener insert = new InsertAction();
      ActionListener command = new CommandAction();

      // add the buttons in a n x n grid

      panel = new JPanel();
      
     
      panel.setLayout(new GridLayout(6, 6));
//1

      addButton("7", insert);
      addButton("8", insert);
      addButton("9", insert);
      addButton("/", command);
addButton("Sin", command);
addButton("ArcSin", command);
//2
      addButton("4", insert);
      addButton("5", insert);
      addButton("6", insert);
      addButton("*", command);
      addButton("Cos", command);
addButton("ArcCos", command);
//3
      addButton("1", insert);
      addButton("2", insert);
      addButton("3", insert);
      addButton("-", command);
      addButton("Tan", command);
addButton("ArcTan", command);
//4
      addButton("0", insert);
      addButton(".", insert);
      addButton("=", command);
      addButton("+", command);
      addButton("AC", command);
     addButton("Sinh", command);
   
   //5  
   
    


addButton("Cbrt", command);
addButton("Cube", command);
addButton("Ln", command);
addButton("Log", command);
addButton("e", command);

addButton("cosh", command);
//6
addButton("Sqrt", command);
addButton("Sqr", command);
addButton("|x|", command);
addButton("Inverse", command);
addButton("!", command);
addButton("Tanh", command);


      add(panel, BorderLayout.CENTER);
   }

   /**
    * Adds a button to the center panel.
    * @param label the button label
    * @param listener the button listener
    */
   private void addButton(String label, ActionListener listener)
   {
      JButton button = new JButton(label);
      button.setForeground(Color.magenta);
      button.addActionListener(listener);
      panel.add(button);
   }

   /**
    * This action inserts the button action string to the end of the display text.
    */
   private class InsertAction implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         String input = event.getActionCommand();
         if (start)
         {
            display.setText("");
            start = false;
         }
         display.setText(display.getText() + input);
      }
   }

   /**
    * This action executes the command that the button action string denotes.
    */
   private class CommandAction implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         String command = event.getActionCommand();

         if (start)
         {
            if (command.equals("-"))
            {
               display.setText(command);
               start = false;
            }
            else lastCommand = command;
         }
         else
         {
            calculate(Double.parseDouble(display.getText()));
            lastCommand = command;
            start = true;
         }
      }
   }

   /**
    * Carries out the pending calculation.
    * @param x the value to be accumulated with the prior result.
    */
    
  // Evaluate n!
  
    //double i,j=1;
   public void calculate(double x)
   
   {  

 
        
 // x=Math.toDegrees(x);
   
      if (lastCommand.equals("+")) result += x;
      else if (lastCommand.equals("-")) result -= x;
      else if (lastCommand.equals("*")) result *= x;
      else if (lastCommand.equals("/")) result /= x;
       else if (lastCommand.equals("Inverse")) result = 1/x;
      else if (lastCommand.equals("=")) result = x;
      else if (lastCommand.equals("AC")) result =      0;
      
      
      else if (lastCommand.equals("Sin")) result =Math.sin(x);
      else if (lastCommand.equals("Cos")) result =Math.cos(x);
      else if (lastCommand.equals("Tan")) result =Math.tan(x);
      
       else if (lastCommand.equals("ArcSin")) result =Math.asin(x);
      else if (lastCommand.equals("ArcCos")) result =Math.acos(x);
      else if (lastCommand.equals("ArcTan")) result =Math.atan(x);
     
      else if (lastCommand.equals("Cosh")) result =      (Math.exp(x) + Math.exp(-x)) / 2.0;
      else if (lastCommand.equals("Sin")) result =      (Math.exp(x) - Math.exp(-x)) / 2.0;
      else if (lastCommand.equals("Tanh")) result =((Math.exp(x) - Math.exp(-x)) /(Math.exp(x) + Math.exp(-x)));
      
     
      else if (lastCommand.equals("Sqrt")) result =      Math.sqrt(x);
       else if (lastCommand.equals("Cbrt")) result =      Math.cbrt(x);
       else if (lastCommand.equals("Sqr")) result =Math.pow(x,2);
        else if (lastCommand.equals("Cube")) result =Math.pow(x,3);
      else if (lastCommand.equals("e")) result =      Math.exp(x);    
      else if (lastCommand.equals("|x|")) result =      Math.abs(x);
      else if (lastCommand.equals("Ln")) result =      Math.log(x);
      else if (lastCommand.equals("Log")) result =      Math.log10(x);
      
   // else if (lastCommand.equals("!")) result = j;
     // else if (lastCommand.equals("=")) result = x;
     // else if (lastCommand.equals("=")) result = x;
     // else if (lastCommand.equals("=")) result = x;
      
      
      display.setText("" + result);
   }

   private JButton display;
   private JPanel panel;
   private double result;
   private String lastCommand;
   private boolean start;
}

433 Mhz RF Transmitter Receiver - Arduino Coding

Assalam u Alikum Everyone!

Today, as my very First post on this blog, I am going to explain the test working of 433 Mhz RF Transmitter Receiver using Arduino. You people will surely Enjoy this post.. :)


Component List
  1. 2x Arduinos
  2. Tx Rx pair of 433 Mhz RF Device
  3. RGB Led
  4. Portable Power sources for portability

I used Arduino Uno and Nano and sent a Text String over RF and received  the string displayed it in Serial Terminal and used RGB Led as message flag.


So here is the transmitter code
#include <VirtualWire.h> //library to be used
char cad[] = {"Bismillah Allah u akbar"} ;//Message
int cad_len = sizeof(cad) / sizeof(char);// Message length calculation
void setup() {
  vw_setup(2000);
  vw_set_tx_pin(3); // 433Mhz TX pin -? Arduino Digital 3
}
void loop() {
  vw_send((uint8_t  *)cad, strlen(cad));//Transmission
  delay(400);
} 

And here goes the transmitter code
#include <VirtualWire.h>
void setup() {
  Serial.begin(9600);
  vw_setup(2000);
  vw_rx_start();
  vw_set_rx_pin(3); // 433 Mhz Rx to Arduino Digital 3
}
String msg;
void loop() {
  msg = "\0";
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  if ( vw_get_message(buf, &buflen) ) // if some data is coming i.e. message buffer is not empty
  {
    for (int i = 0; i < buflen; i++)    {
      msg += String(char(buf[i])); // add data to message string
    }
    if (msg != "\0")
      Serial.println(msg); //print msg rcvd ob serial terminal
    delay(100);
  }
}

A more complex approach to Rx 
if a clean message is  received, RGB Led shows Green. If msg is corrupted , Red Leds is On. and when no message is received Blue Led remains ON
#include <VirtualWire.h>
#define GREEN A1
#define BLUE A0
#define RED A2
void setup() {
  Serial.begin(9600);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  pinMode(RED, OUTPUT);
  vw_setup(2000);
  vw_rx_start();
  vw_set_rx_pin(3); // 433 Mhz Rx to Arduino Digital 3
}
String msg;
char bufchar;
bool bl;
void loop() {
  msg = "\0";
  bl = 0;
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;

  if ( vw_get_message(buf, &buflen) ) // if some data is coming i.e. message buffer is not empty
  {
    bl = 1;
    for (i = 0; i < buflen; i++)    {
      bufchar = char(buf[i]);
      msg += String(bufchar); // add data to message string
    }
    if (msg.equals("Bismillah Allah u akbar"))
      /*heck , if data Recived is True, Switch On Green Led.
      If data is corrupted switch on Red Led*/
    {
      Serial.println("Msg rcvd");
      digitalWrite(GREEN, HIGH);
      digitalWrite(BLUE, LOW);
      digitalWrite(RED, LOW);
    }
    else {
      Serial.println("Msg Error");
      digitalWrite(GREEN, LOW);
      digitalWrite(BLUE, LOW);
      digitalWrite(RED, HIGH);
    }
    Serial.println(msg); //print msg rcvd ob serial terminal
    delay(100);
  }

  if (bl == 0)
  { // if no data is recieved switch on Blue Led
    digitalWrite(GREEN, LOW);
    digitalWrite(BLUE, HIGH);
    digitalWrite(RED, LOW);
  }

  delay(100);

}
 I have added self explanatory comments. I hope this tutorial has helped you. Stay Tuned