Monday, June 2, 2014

6. Switch Statement

Switch Statement

Let us consider a program segment.

int ch;
printf("Enter a direction code (1-4) : ");
scanf("%d",&ch);

if(ch==1)
   {  printf("North");}
else
  {
     if(ch==2)
       { printf("South");}
     else
        {
           if(ch==3)
             { printf("East");}
           else
              {
                if(ch==4)
                  { printf("West");}
                else
                   { printf("Invalid Direction"); }
              }
        }
  }


it prints one of the String "North","South","East","West" based on the value of integer variable ch if it is in the range of 1 to 4 other wise it prints "Invalid Direction".

The above program segment much ambiguous in remembering the braces starts and its closing. It can be easy rewritten using the switch statement.

int ch;
printf("Enter a direction code (1-4) : ");
scanf("%d",&ch);

switch(ch)
  {
      case 1: printf("North");
                  break;
      case 2: printf("North");
                  break;
      case 3: printf("North");
                  break;
      case 4: printf("North");
                  break;
      default: printf("Invalid Direction.");
   }

//===============Statements after switch statement=============
--------------------------------
--------------------------------

The switch statement is composed of multiple case statements followed by value with which variable in the switch is compared and on returning true corresponding case is executed. Break statement is necessary as it transfer the control to out of the switch statement after the execution of a case. if the variable does not math with any value there is optional default: block at the end of switch statement which got executed. there is no need of break statement after the last case though it is default case or some other case if default is not present.


EXAMPLE :

!under construction please re-visit soon for more information





Saturday, May 24, 2014

5. Decision Making

Decision Making


In programming very often we need to execute a statement or a group of statements based on some logical condition. Consider a flow chart :


The set of statements in the rectangle will be executed only when the logical condition return true. The syntax for if statement is like this

-----------------------------------
  some statements before if statements
-----------------------------------
if (logical condition)
  {
    //Set of statements that execute only if logical condition return true
    ..................................................
    ---------------------------------
    ---------------------------------
  }

------------------------------------
  some statements after if statements
------------------------------------

A program which demonstrate the use of if statement

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

void main()
  {
    int a,b;
    clrscr();
    printf("Outer radius of washer : ");
    scanf("%d",&a);
    printf("Inner radius of washer : ");
    scanf("%d",&b);

    if (a>b)
     {
        printf("Washer design is possible.");
      }

    getch();
}


The above has a bug that it provides no information if the washer design is not possible. Such bug can be eliminated by using if else statement. The syntax for if else statement is like this.


-----------------------------------
  some statements before if statements
-----------------------------------
if (logical condition)
  {
    //Set of statements that execute only if logical condition return true
    ..................................................
    ---------------------------------
    ---------------------------------
  }
else
 {
  //Set of statements that execute only if logical condition return false
    ..................................................
    ---------------------------------
    ---------------------------------
  }
------------------------------------
  some statements after if statements
------------------------------------



The previous program can be rewritten as


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

void main()
  {
    int a,b;
    clrscr();
    printf("Outer radius of washer : ");
    scanf("%d",&a);
    printf("Inner radius of washer : ");
    scanf("%d",&b);

    if (a>b)
     {
        printf("Washer design is possible.");
      }
   else
     {
       printf("Washer design is not possible.");
     }
    getch();
}
   

After executing one of the blocks either true or false, the control comes on the statements just after the else block. in above program getch() is the candidate statement on which control comes after if else statement.



Few words about logical conditions.


in above programs a>b is the logical condition which return true or false on basis of values of a and b.
to make such logical conditions other operators which may be used are these

Relational Operators
Mathematical Operator C/C++ Operator
< <
> >
<=
>=
= = =
!=


a>b      can be written as a>b    in c/c++
ab      can be written as a>=b  in c/c++
a<b      can be written as a<b    in c/c++
ab      can be written as a<=b  in c/c++
a=b      can be written as a==b  in c/c++
ab      can be written as a!=b   in c/c++

There are few Logical Operators which are used to combine relational expressions like (a<b), (a<=b) etc.

Logical Operators performs logical operations on relations and returns true and false based on the candidate relational expressions. Explanation of these is as below.

Logical Operators
OperatorOperation PerformedExampleDescription
&&AND(a<b)&&(a<c)Returns true if a<b and a<c both returns true other wise false
||OR(a<b)||(a<c)Returns true if any one or both (a<b), (a<c) returns true otherwise false.
!NOT!(a<b)Returns true if a<b returns false, Returns false if a<b return true.


Let we want to find greater value among three integers assuming all a,b and c have different values, the required c program is


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

void main()
  {
    int a,b,c;
    clrscr();
    printf("Value of a  : ");
    scanf("%d",&a);
    printf("Value of b  : ");
    scanf("%d",&b);
    printf("Value of c  : ");
    scanf("%d",&c);
    if  ((a>b) && (a>c)) // Logical operator combining two conditions a>b and a>c
     {
        printf("%d is greater",a);
      }
   else
     {
       if (b>c)
         { printf("%d is greater ",b); }
      else
         { printf("%d is greater ",c);
     }
    getch();
}




Thursday, May 22, 2014

2. Basic Electronics PART 2

Basic Electronics PART 2

Any electronic circuit though it is big or small is composed of so may components. Each and every component has almost same importance. So it is very to install every component as per its rules and regulations defined in its datasheet. It is commonly observed that experimenters make very big and complex circuits very easily,but they lack vary basic knowledge about the properties and behavior of different components.

Electronic components are normally very sensitive, so a very little mistake may damage these components easily.So very basic information is very important to provide here.


Multimeter

Before information  about different components we have to go through use of multi-meter.






!Article is under construction. Please come back soon to view complete article




Tuesday, May 20, 2014

1. Basic Electronics PART 1

Basic Electronics PART 1


Potential :


In classical electromagnetism the electric potential at a point is equal to the electric potential energy ( measured in jouls ) of a  charged particle at a location divided by the charge ( measured in coloumbs ) of that particle. it is measured in Volts.

Potential Difference :


The Potential Difference is measure of difference of potential between two points.It is again measured in Volts. It causes the flow of electrons in a conductor from high potential to low potential.

Current :

Flow of electrons in a conductor is called current. Rate of flow of electrons is measured in Ampere.it is denoted by symbol I.

Resistance :


It is the property of matter by virtue of which it opposes the flow of electrons. It is measured in Ohms. More the resistance means less the flow of current at the same potential difference. Resistance of different materials is different. Copper causes less resistance than Iron and Iron causes less resistance than wood. thus the current flows easily in copper and too much less in wood.

Relation between Voltage,Current and Resistance ( Ohm's law ) 

Ohm's law states that potential difference between two point of a conductor is directly proportional to the current  flowing through it while keeping the other parameters (temperature etc) kept constant.


                 V    I

where

  V       Potential Difference (Volts)
  I        Current (Ampere)
   Sign of proportionality

To remove the sign of proportionality we have to add constant on the right side of equation.

V = R X I     .....................eq(1)

Where R is the Resistance of Conductor. The value of R can be calculated as

R= V/I          ....................eq.(2)


From eq (2) we can say that in a conductor if potential difference across a conductor is 1 V and current flowing throw it is 1 A then the resistance of that conductor is said to be 1Ω.

Power :  


Power is the amount of current times the voltage level at a given point measured in wattage or watts.

means

P= VI

Heat :

Current flowing throw a conductor also produces heat. which can be calculated as

H=P . t

where t is time is seconds.

and Heat (H) is calculated in joules (J)


Other relations between V,I,R,P,H and t are

R=V/I                         V=I.R                 I=V/R

P=V.I                           P=I² .R               P=V²/R

H=P.t                          H=V.I.t               H=V²/R . t





====*====
 






...






  






4. Using scanf for dynamic input

Using scanf for dynamic input


When we assign a value to a variable using assignment statement like

a=10;

its value is hard-coded means can't changed by the computer operator at runtime(while executing). To make more dynamic program variables values can be read from console ( normally keyboard ) using scanf function, but proper care must be taken while selection which variables must be read from console and which are to be hard-coded.

Consider a program which reads radius of circle from the keyboard at run-time and calculates its area.

mathematical expression for calculation area of circle will be

Area = PI * radius * radius;

at there Area depends on value of PI and radius. How ever value of PI is fixed (3.14) and thus to be hard-coded and value of radius is to be read from keyboard. however special keyword (const can be used while declaring PI ) which prevents accidental change of value of PI.

The syntax of scanf function is


scanf("control string", list of variables with & sign with each variable);

let we want to read the value of  two float variables a,b the scanf statement will be

scanf("%f %f",&a,&b);

it is recommended that use scanf function for one variable at time. it will prevent computer operator form feeding invalid inputs.

Control String : used in scanf consists of only type specifiers and spaces only, how ever general text can be used to read more complex formatted input.

The program to read the radius of a circle which prints area can be written as

==================================================================
#include <stdio.h>
#include <conio.h>
    
void main()
  { float r,pi,a;                                         // defines two float variables r and pi
     clrscr();                                             //clears the screen
     pi=3.14;                                           // defining value of pi

     printf("Enter radius of circle  : ");       // printing a message for operator to input value of r however actual value is read by scanf statement);
     scanf("%f",&r);

     a=pi * r * r;                                    // calculating area of circle and storing it in a

     printf ("Area of circle  : %f",a);       // prints output for operator

     getch();
   }
=======================================================================

Some more words

    1.    ( & ) sign used with each variable in scanf function sends the address of corresponding variable to the scanf function which helps scanf function to place value read from keyboard at appropriate memory location.

    2.    For  more complex input general text can be used in control string.
           Let we want to read a date, it involves day,mon and year each as integer. program to read a formatted date and print formatted date will be.

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

void main()
 { int d,m,y;
    clrscr();
    printf("Enter date of birth (dd/mm/yyyy) : "); // just a message to the operator no other function
   
    scanf("%d/%d/%d",&d,&m,&y);                // read value of d,m,y in the format d/m/y
                                                                      // at here / 's are used to enforce formatted input

    printf("Date of birth : %02d/%02d/%04d",d,m,y); //prints date in proper format

   getch();
 }



/'s are just to enforce input in format dd/mm/yyyy however we can use - 's to enforce the format as dd-mm-yyyy

%04d enforces the value of y in four spaces right aligned with leading 0;s on the left


code snippet 

int a=10;
printf("%5d",a); 

will print 00010 as output

========================================================================







Monday, May 19, 2014

3. First C Program

First C Program



======================================================================
#include <stdio.h>
#include <conio.h>
void main()
  {
     int a,b,c;
     clrscr();
     a=10;
     b=20;
     c=a+b;
     printf("%d",c);
     getch();
  }
======================================================================

Program Explanation


#include <stdio.h>
#include <conio.h>
                    are used to add required header files.

void main()  
                   main function which tells the compiler for entry point of program

{   }   
                start and end of a block


int a,b,c;
                declares thee variables (a,b,c) of type signed integer each of 16 bytes.

clrscr()
                a function being used to clear the output screen. it works only when conio.h header file is included using #include

a=10;
b=20;
              stores 10 in a and 20 in b

c=a+b;
              adds value of a and b and stores it in c

printf("%d",c);
              prints the value of c on the output screen. it is available only if stdio.h header file is included.

getch();
              A function used to read a single character from keyboard  but at here it is used to make the output static. the output screen generally displayed only for a fraction of second after execution. and then program terminates and c IDE is displayed again back. To prevent getch() is used because it waits until user doesn't press a key and in results it prevent termination of protram.



How to use printf

printf is used for formatted output. The general syntax of printf is

printf("control string",list of variables);

Control string consists of 

    
    Type Specifiers               %d  %f    %c etc
    Control Characters         \n \r \t etc
    General Text                  anything other is considered as general text

    Let us create printf statement for the output (for above program)

    30 is obtained by adding 10 and 20

    Step 1.
       Replace each numeric or character value coming from variable with corresponding type specifier.

       the result will be

       %d is obtained by adding %d and %d

       becaues 30 comes from c, c is integer, , %d is type specifier for int
       similar is the case for 10 and 20


      now list of the variables will be c,a,b because first %d is for c , second is for a and third is for a. thus the final printf statement for the required output will be

printf("%d is obtained by adding %d and %d",c,a,b);

and the complete required program will be

======================================================================
#include <stdio.h>
#include <conio.h>
void main()
  {
     int a,b,c;
     clrscr();
     a=10;
     b=20;
     c=a+b;
     printf("%d is obtained by adding %d and %d",c,a,b);
     getch();
  }
======================================================================
    

control characters are used to control the output behavior 
ie \n i use to print remaining text in new line.
the complete escape sequence is

Escape sequence
Hex value
Connotation
\a
07
Alarm (Beep, Bell)
\b
08
Backspace
\f
0C
Formfeed
\n
0A
Newline (Line Feed); see notes below
\r
0D
Carriage Return
\t
09
Horizontal Tab
\v
0B
Vertical Tab
\\
5C
Backslash
\'
27
Single quotation mark
\"
22
Double quotation mark
\?
3F
Question mark
\0
00
Null (string terminator)

  printf("Hello\nWorld");  // will print World in next line

  will print

  Hello
  World
                                                         ---------------------------------------------







     

2. Introduction to data types in C/C++

Data Types in C/C++

  C/C++ supports many data types. Out of all of these three are main.

i)  Integer
ii) Float
iii) Character

i) Integer 

     Integer data type is used used to store simple numeric values which excludes decimal point. it is a 16 bit data type. 
Integer is of two types signed and unsigned integer

In signed mode it can store values ranging from -32768 to 32767. the keyword used to create signed integers is int   the type specifier for signed integer is %d

In un-singed mode  it can store values ranging from 0 to 65535. the keyword used to create unsigned integers is unsigned int. The type specifier for signed integer is %u.

ii) Float 
        Float data type is used to store simple numeric values but with decimal point only. it is 32 bit data type. Type specifier for Flaot variable is %f. The keyword used to create float variables is float

iii) Character
       Character variables are used to store single single character at a time. The keyword used to create Character type variables is char. Type specifier for character type variable is %c.


Some Examples of Integer, Float and Character type variable declaration

int a;
int a,b,c;
int year,years,cou,n;

float amt,length,bredth;
float amount,roi;

char ch;
char em;

Assignment statement

Assignment statement is used to store values in variables. General syntex for assignment statement is 

variable =  variable | constant | expression

i.e.

a=10;
b=20;
c=a+b;
d=c;


1. Introduction to C IDE

Introduction to C IDE


  Different parts of a C/C++ Language IDE is shown Below



As show above Program window is used to type program by the programer
Vertical and horizontal bars are used for navigation through program window
Cursor location place is used to show location of cursor in the program window
Run menu is used to compile, link and run the program in active program window

Basic structure of a simple c/c++ program

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

void main()
  {



  }
===============================================================

In Above #include is used for adding required library files in the program
stdio.h and conio.h are library header files related to some screen input/output and screen function used later

void main() is the main entry function. it tells c compiler from where to start the execution of the program.
The main program is always written within the { } placed after void main() function.