Sie sind auf Seite 1von 30

1

Ashfaq Ahmed Waraich


ashfaqmbd@gamil.com
0300 755 3280









































2


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280

Languages
A programming language is a means for you, to generate those
instructions so that the computer can manipulate the data in the
way you want it manipulated.
Computer is such a device that manipulates numbers. Some of the
numbers are interpreted as instructions by the computer while
some as data.
Types Of Languages.
(1). Low Level Languages.
(2). High Level Languages.

(1)-Low Level Languages.
The languages, which are close to machine language,
computer's own language, are called low level languages and these
languages are far from human languages like English.

Advantages.
Programmes are highly efficient.
Programmes require minimum time to run.
Minimum instructions are required.

Disadvantages
Programmes are difficult to read and write.
Programmes are not portable, i.e. a programme written on a
computer will not run on another computer. Everytime a
programme will be written on every new computer.
Languages are difficult to learn and use.

Examples:
Assembly language, Machine language etc.

High Level Languages.
High level languages are those which are closer to human
languages like English and far from machine language.

Advantages
Programmes are easily readable and easy to write as well.
Languages are easily learnt and used.
Programmes are portable i.e. programmes are hardware
independant.

Disadvantages.
3


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
Programmes require more time to run than low languages
programmes.
Programmes are not highly efficient.

High level languages can be further subdivided into Procedural
languages and Object Oriented Languages.

Examples:
FORTRAN, PASCAL, COBOL
C language is somewhat between high level and low level
languages.


The C Language

C is somewhat between high level languages and low level
languages.
Authors of c are Brian.W.Kernighan and Denis M.Ritchie.
Both the authors wrote c to exploit native capabilities of
implemented computer.
Programmes are much efficient and almost nearer to low
language programmes
Portable programmes can be written as well
C falls in block structured, procedural language category of
high level languages.

Source Code
Programme written by a programmer using any language is
called source code. This is a text file only understandable to
human beings. This code is not understandable to computers
because a computer can understand only machine language.

Compiler-Compilation
The source code that is written by a programmer is not
understandable to computer. To make it understandable to
computer, this source code should be translated to such a language
that can be easily understood to computer so that the computer
may know what we want it to be done. The process of translation
into such a form is called Compilation and a programme that
performs this job is called Compiler. Almost every language comes
with its own builtin compiler.

Object Code
When source code is translated into such a code that is
understandable to computer. This resulting code is called Object
4


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
code. Through this code computer knows what we want to do via
programme.

Integrated Development Environment (IDE).
IDE of any language is such environment where you can
write,compile,debug and run your programmes.
So an environment that offers you all these features is called
Integrated Development Environment as its name implies it
integrates all above features from writing a programme to running a
programme and you dont need to switch different programmes to
do all these tasks.









Some important shortcuts for c language

F1
F2
F3
F4
F5
F6
F7
F8
F9
F10
ALT+0
ALT(1..9)
ALT+F1
ALT+F3
ALT+F4
ALT+F5
ALT+F7
ALT+F8
ALT+F9
CTRL+DEL
CTRL+F1
CTRL+F2
CTRL+F3
CTRL+F9
Help
File Save
File Open
Run Go To Cursor
Window Zoom
Window Next
Run Trace Into
Run Step Over
Compile(make exe)
None;takes you to menu bar
Window List
None;displays window through 1 to 9
Help previous topic
Window close
Debug inspect
Window user screen
Search previous error
Search next error
Compile to obj
Edit clear
Help topic search
Run programme reset
Debug call stack
Compile+Run

5


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280



Basic Structure Of C Programme
Let us investigate the various elements of c programme.

#include <iostream.h>
void main(void)
{
Cout<<"AshfaqAhmad Waraich";
}

(a). Function Definition
First note the word "main". All c programmes are divided into
units called Functions. Note that main() is a function. Every c
programme consists of one or more functions, this programme has
only one. No matter how many functions there are in c programme,
main() is the one to which control is passed from the operating
system when the programme is run, it is the first function
executed.
The word "void" preceding main, specifies that the function
main() would not return a value. The second void, in parenthesis
specifies that the function takes no argument.

(b). Delimiters
Following the function definition are braces, which signal the
beginning and end of the body of the function. The opening brace
"{" indicates that a block of code that forms a distinct unit is about
to begin. The closing brace "}" terminates the block of code. There
is only one statement between the braces; the one beginning with
cout.
Opening and closing braces are not only used in functions but
also in decision-making and loop statements.
(c). Statement Terminator
A statement in c is terminated with a semicolon. C pays no
attention to carriage return, i.e. you can write a statement in two
lines provided that statement is terminated on second line using
semicolon. In fact, c compiler pays no attention to any whitespace
characters, the carriage return, the space, and the tab. You can
put as many or few characters in your programme as you like; they
are invisible to the compiler.
Variables
Variable is a space in the computer's memory set aside for a
certain kind of data and given a name for easy reference.
6


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
Variables are usesd so that the same space (memory location)
can hold different values at different times. You can take an
example of a mathematical expression which contains three
variables x,y,z. The value of x is depending on value of y and z i.e.
x=y+z
Whenever this expression is manipulated, for example we put
different values for y and z, so their addition put new value in x
everytime, let say we give y=2 and z=3 for first time, so x will hold
5 and again we change y=4 and z=8 then x=12. Same is the case
with memory variables, everytime the programme runs, variables
can hold different data.

Constants and Variables
The power of computer language comes from the ability to
use variable, which can hold many different values in programmes
statement. Let us write our previous programme again to use a
variable instead of a constant

#include <iostream.h>
void main(void)
{
int num;
num=2;
cout<<("This is number two:"<<num;
}


How To Define or Declare Variables
The statement
int num;
Is an example of variable definition or variable declaration. The
definition consists of type name (data type) and name of the
variable i.e.




Int num;


Type variable
In c program, all variables must be defined, if you have more than
one varibles of same type, you can define them all with one type
name, separating the variable names with the commas;
7


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
int rollno,age,clas;
When you define a variable, the compiler set aside an
appropriate amount of memory to store that variable. For an
integer variable, compiler will set aside two bytes of memory.
These two bytes are larger enough to hold numbers from 32768 to
32768. Actually the amount of memory used for a variable is
dependent on the particular computer system and compiler being
used. Turbo c++ operates with two bytes. Borland c++ compiler
operates with four bytes i.e. you can make an integer variable to
hold values from 2147483648 to 2147483647. Anyhow, turbo c++
compiler is under our discussion, so we will follow as 2-byte for an
integer variable.

Some Other Data Types or Variable Types

There are, of course, other types of variables besides integer, we
shall sumamrize them here and then give examples of the uses of
the more common types.

Type Name Memory
Space(bytes)
Range Exampl
es
Int/signed int 2 -32768 to 32767 5,10,45
55
Char 1 -128 to 128 a,1,
10
Long int 4 -2147483648 to
2147483647
35540
Float 4 10
38
to 10
-38
(
precision

6 digits)
2.12546
Double 8 10
308
to 10
-308

(pricision 15 digits)
5.15246
8
Long double 10 10-
4932
to 10
4932

(precision 19 digit)

Short 2 Same as int Same as
int
Unsigned int 2 0 to 65535
Signed char 1 0 to 255
Signed char 1 -128 to 127


How To Initialize Variables
It is possible to combine a variable definition with an
assignment operator(=) so that a variable is assigned a value at the
same time it is defined. For example the following programme:-
8


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
#include <iostream.h>
void main(void)
{int event=5;
char heat=C;
float time=27.25;
cout<<The winning time in heat<<heat<<of event<<event
<<was<<time);
}


Input/Output
its all pretty well to store data in the computer and make
calculations with it but you also need to be able to input new data
into the computer and print the results of your calculations. Now
we will examine input and output functions. We are already
considering ouput operator cout and we will introduce two input
operators cin and a function getche().

Escape Sequences
We saw previously that new line character, \n, when inserted
in cout format string would print the carriage return. The new line
character is an example of Escape Sequence, so called because the
blackslash symbol is considered an escape character, it causes an
escape from the normal interpretation of a string so that the next
character is recognized as having a special meaning. Examples
would make it clarify. This example also includes another escape
sequence \t, which means tab.

#include <iostream.h>
void main(void)
{
Cout<<\nEach \t word \t is \n tabbed \t over
\t once;
}
turbo c++ tabs over eight character when it encounters the \t
character. The tab and newline are probably the most often used
escape sequences, but there are others as well. The following list
shows the common escape sequences.
\n Newline
\t Tab
\b Backspace
\r Carriage return
\f Form feed
\ Single quote
9


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
\ Double quote
\\ Backslash
\a Beep
\xdd ASCII code in hexadecimal notation, each d
represents a digit.
\odd ASCII code in octal notation, each d represents a
digit.

The Cin operator
cout is an input operator unlike cout that was output. cin is
an input operator so that it will be used to store data in memory.
Here is a programme that uses cin.

#include<iostream.h>
void main(void)
{
float years,days;
cout<<Please type your age in years:;
cin>>years;
days=years*365;
cout<<You are <<days<<days old;
}


Operators
Operators are words or symbols that cause a programme to do
something to variables. Most common operators are: Arithmetic
operators, Relational operators and increment/Decrement
operators.
Arithmetic Operators
C uses the four arithmetic perators that are common in most
programming languages and one the remainder operator, which is
not so common.
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder or modulus oprator.

Here is a programme that uses several arithmetic operators.
It converts temperatures in Fahrenheit to Centigrade.


10


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280

#include <iostream.h>
void main(void)
{
int ftemp,ctemp;
cout<<Enter temperature in degrees Fahrenheit:;
cin>>ftemp;
ctemp=(ftemp-32)*5/9;
cout<<Temperature in Degrees Centigrades is<<ctemp);
}

Arithmetic Assignment Operator
Consider the following statement
Total=total+number;
Here the value in number is added to the value in total and
the result is placed in total. In c language this statement can be
written as
Total+=number;
Here above the statement makes use of plus-equal operator.
All the arithmetic operators can be combined with the equal sign in
the same way.

#include <iostream.h>
void main(void)
{
int total=0;
int count=10;
cout<<Total=<<total;
total+=count;
cout<<\nTotal=<<total;
total+=count;
cout<<\nTotal=<<total;
}


In addition to the plus operator all other arithmetic operators could
be use as well
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Remainder assignment

11


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280

Increment Operator
C/C++ uses another operator that is not common in other
languages, the increment operator. Consider the following
programme.

#include <iostream.h>
void main (void)
{
int num=0;
cout<<Number=<<num;
cout<<\nNumber=<<num++;
cout<<\nNumber=<<num;
}

Another modified version of above programme is as under.

#include <iostream.h>
void main (void)
{
int num=0;
cout<<Number=<<num;
cout<<\nNumber=<<++num;
cout<<\nNumber=<<num;
}

The effect of (++) is same as num= num+1. If we use num++
and then print the value of num we shall find the original value of
num, while if we use ++num and then print the value of num we
shall find the incremented value of num. Actually cout, when
prints num++ , it prints the original value and then increments the
num while cout, when prints ++num, it increments num and then
prints the incremented value.
(- -) i.e. Decrement operator can also be used in the same way as
(++).

Relatioal Operators
Relational operators are the vocabulary the programme uses
to ask questions about variable. Let us look at an example, in this
case less than operator < is in our view.


12


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
#include <iostream.h>
void main(void)
{
int age;
age=15;
cout<<\n Is age less than 21<<age<21;
age=30;
cout<<printf\n Is age less than 21?<<age<21;
}
The output would be in form of 1 (true) or 0 (false) depending upon
conditions.
There are other six relational operators.
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to

Comments
Comments are statements that are written in c programme
but they are simple english statements so they do not follow any
syntax of c language. Comments are view or opinions of a
programmer inside a programme on different locations. A c
compiler ignores such statements whenever it encounters. But we
make a statement to be ignored by a compiler by using special
symbols to indicate that a statement following a symbol is a
comment. In other words a compiler is forced to ignore these
statements. There are two main methods of making comments
statements. First, insert // symbols before a comment if the
comment is a single line. On the other hand if your comment is on
more than one lines then at the beginning of the comment insert /*
symbol and while ending a comment insert */ symbols.
Comments are of much importance as they are a overview of
the programme, what a programmer wants to do through this
programme. For example to tell a reader the purpose of the
programme that converts fahrenheit temperature to centigrade,you
can include such a comment at the beginning of your programme as
//this programme has been written to convert fahrenheit
temperatur to centigrade temperature. Comments increase the
readibility of a programme.

Loops
Almost always, if something is worth doing, it is worth doing
more than once. You can think of several examples of this from
13


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
real life, such as going to the movies and eating a good dinner.
Programming is the same way; we frequently need to perform an
action over and over, often with variations in the details each time.
The mechanism that meets this need is the loop.
There are three major loop structures in c; the For loop, the
While loop and a cousin of the while loop called do while loop.

FOR Loop
It is often the case in programming that you want to do
something a fixed number of times. Perhaps you want to calculate
the paychecks for 120 employees or print the squares of all the
numbers from 1 to 50. The for loop is ideally suited for such cases.
Lets look at an example of a for loop.


#include <iostream.h>
void main (void)
{
int count;
for(count=0; count<=10; count++)
cout<<\n count=<<count;
}

Structure of the for loop
Count=0; initialize expression
Count<10; test expression
Count++ increment expression

For(init exp; test exp; inc/dec exp)
{
statement(s);
}

Reversing a for loop
We can reverse a for loop as by assigning highest value to
initialize expression, lowest value to test expression as well as
decreasing the iterations.
#include <iostream.h>
void main (void)
{
int count;
for(count=10; count>=1; count- -)
cout<<\n count=<<count;
}
14


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280

Multiple Statements in a loop
Two or more statements can also be used in the body of for
loop. This kind of statement, consisting of more than one
statements is called compound statement and a compound
statement is always enclose in braces.
Void main(void)
{
int count,total;
for(count=0; total=0;count<10;count++)
{
total=total+count;
cout<<\ncount=<<count<<total=<<total;
}
}




Some More Example Programmes for The Demonstration of FOR
Loop
This first programme asks the user to input five numbers but
by the use of for loop, the programme does not need to print five
statements but a single cout and a single cin.


Programme 1 Programme 2 (ASCII table)
Void main(void)
{
int I,n;
for(I=0; I<5; I++)
{
Cout<<Enter a number;
Cin>>n;
}//close of for loop
}//close of main
Void main(void)
{
Int n;
for(n=32; n<=255; n++)
{
Cout<<n<<char[n];
}
}

Programme 3 Programme 4
Void main(void)
{
int cols;
for(cols=1; cols<40; cols++)
{
#include <iostream.h>
#include <dos.h>
Void main(void)
{
int I;
15


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
Cout<<\X<<db;

}
}
for(I=0; I<10; I++)
{
delay(200);
cout<<I;
}
}

Nested For Loops
We can also define a loop within the body of another loop. This
process is called nesting a loop. So nested for loop will be such a
loop in which a for loop will be defined within a for loop. For loop
inside a for loop is nested for. An outer loop and an inner loop. The
inner loop will run on the basis of outer loops final value..
Example 1 Example 2 Example 3
Void main(void)
{
for(int I=0; I<3; I++)
{
for(int j=0; j<2; j++)
{
Cout<<\n <<j;
}
}
Void main(void)
{
int cols,rows;
for(rows=1; rows<13;
rows++)
{
Cout<<\n;
for(cols=1;cols<13;
cols++)
cout<<cols*rows;
}
}
Void main(void)
{
int cols,rows;
for(rows=1;
rows<=22; rows++)
{
Cout<<\n;
for(cols=1; cols<=40;
cols++)
cout<<\xDB;
}
}

Assignment:
Write a programme using nested for to draw a table of any
numberr?

WHILE Loop
The second kind of loop structure available in c is the while
loop. Although at first glance this structure seems to be simpler
than the for loop, it actually uses the same elements but they are
distributed throughout the programme.

Void main(void)
{
int count=0;
int total=0;
while(count<10)
{
total=total+count;
cout<<\ncount<<count++<<
16


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
total=<<total;
}
}
The loop variable count is initialized outside the loop in the
declaration int count=0. When the loop is first entered, the
condition count<10 is tested. If it is false, the loop terminates. If
it is true, the body of the loop is executed. The increment
expression is buried in the body of the loop. When the cout<<
statement that forms the loop body has finished printing, count is
incremented by the ++ operator.

For VS. While
In situations where the number of iterations in a loop are
known in advance, while loops are actually less appropriate, in this
case the for loop is a more natural choice, because we can use its
explicit initialize, test and increment expression to control the
loop.
The while loop shines in situations where a loop may be terminated
unexpectedly by
conditions developing within the loop
Void main(void)
{
int count=0;
cout<<\n Enter a phrase;
while(getche() !=\r)
count++;
cout<<\n character count is
<<count;
}
//This is modified version of
previous example
Void main(void)
{
int count=-1;
char ch=a;
cout<<\nEnter a phrase;
while(ch!=\r)
{
ch=getche();
count++;
}
Cout<<\ncharacter count is
<<count;
}

Nested While loop
Just as for loop can be nested, so can while loops. The following
program shows a while loop within a for loop.

17


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
Void main(void)
{
int I;
char ch;
for(I=0; I<5; I++)
{
Cout<<\n Type in a letter from a to e \n;
while((ch=getche())!=d)
{
Cout<<\n sorry<< ch<< is incorrect \n;
Cout<<Try Again;
}
Cout<<\nThats it \n;
}
Cout<<Good Bye\n;
}




Another application for nesting while is

Void main(void)
{
int number=1;
long answer;
while(number!=0)
{
Cout<<\n Enter a number;
Cin>>number;
answer=1;
while(number>1)
answer=answer*number- -;
cout<<Factorial
is:<<answer<<\n;
}
}

Using While Loops and For loops
Generally speaking, if at the time you enter the loop you
already know how many times you want to execute it. You are
probably better off with the for loop. If on the other hand, the
conditions for terminating the loop are imposed by outside world,
such as the user typing a certain character then you are better off
with the while loop.
18


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280

The Do While loop
This loop is similar to the while loop. The difference is that in the
do loop the test condition is evaluated after the loop is executed
rather than before.
Void main(void)
{
int count=0;
int total=0;
do
{
total=total+count;
cout<<\n count=<<count++<< total=<<total;
}
while(count<10);
}

The do loop, unlike the other loops we examined has the
keywords: do and while. The do keyword marks the beginning of the
loop; it has no other function. The while keyword marks the end of
the loop and contains the loop expression.
An important detail to note is that this loop, unlike for and
while loops is terminated with a semicolon. The operation of the
do loop is sort of an upside-down version of the while loop. The
body of the loop is first executed, then the rest condition is
checked. If the test condition is true the loop is repeated.
The important point to note is that the body of the loop will
always be executed at least once, because the test condition is not
checked until the end of the loop.
When would you use a do loop? Any time you want to be sure the
loop is executed at least once.

Break & Continue Statements
These two statements can be used with any of the loops
described earlier.
The break statement bails you out of a loop as soon as it is
executed. It is often used when an unexpected condition occurs;
one that the loop test condition is not looking for.
The continue statement is inserted in the body of the loop and
when executed, takes you back to the beginning of the loop,
bypassing any statements not yet executed. Continue is a bit
suspect in that it can make a programme difficult to read and debug
by confusing the normal flow of operations in the loop, so it is
avoided by c programmers whenever possible.
19


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280

Decision Making Structures
Computer languages, too, must be able to perform difficult sets of
actions depending on circumstances. C has three major decision-
making structures, the IF statement, the IF-ELSE statement and the
SWITCH statement. A fourth, somewhat less important structure is
the conditional operator.

The IF statement
Like most languages, c uses the keyword if to introduce the basic
decision-making statement.
Void main(void)
{
char ch;
cout<<Type a character;
ch=getche();
if(ch==y)
cout<<\nYou typed y;
}
The statement is surprisingly similar to that of the while
statement. The keyword if is followed by parenthesis which
contains a conditional expression using a relational operator. After
that comes body of IF.

Nested-IF statements
Like loop statements, if can also be nested.
Void main(void)
{
Cout<<\n Type characters:\n;
if(getche()==n)
if(getche()==o)
cout<<\n you typed no;
}
In the above example, the inner if would not be reached unless the
outer one is true, and the cout would not be executed unless both if
statements are true.



IF-ELSE statement
The IF statement by itself will execute a single statement or a
group of statements when the test expression is true. It does
nothing when it is false. Can we execute a group of statements if
and only if test expression is not true?. Of course, this is the
purpose of the else statement.
20


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280

Example Example
Void main(void)
{
char ch;
cout<<\nType character \n;
ch=getche();
if(ch==y)
cout<<\n You typed y;
else
cout<<\n You did not type y;
}
Void main(void)
{
int x,y;
for(y=1; y<9; y++)
if((x+y)%2==0)
cout<<\xDB\xDB;
else
cout<< ;
cout<<\n;
}
}

Nested IF-ELSE statement
It is perfectly possible to nest an entire if else construct within
either the body of an if statement or the body of an else statement.

Void main(void)
{
int x,y;
for(y=1; y<24; y++)
{
for(x=1; x<24; x++)
{
if(x==y)
cout<<\xDB;
else if (x==24-y)
cout<<\xDB;
else
cout<<\xB0;
cout<<\n;
}
}

Note that in the above example how the second if else
construction which draws the second line is nested inside the first
else statement. If the test expression in the first if statement is
false then the test expression in the second if statement is checked.
If it is false as well, the final else statement is executed.

21


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
ELSE-IF construct
Void main(void)
{
int average;
cout<<Enter your average marks;
cin>>average;
if((average>60)&&(average<70))
cout<<\nGrade=A;
else if((average>50)&&(average<60))
cout<<\nGrade=B
else if((average>40)&&(average<50))
cout<<\nGrade=C;
else if((average>33)&&(average<40))
cout<<\nPass;
else
cout<<\nFail;
}


Break Statement
In the next section we shall look at the switch statement,
which provides an alternative to the else if construct. However,
the switch statement relies on another statement, break.
Void main(void)
{
float guess,incr;
char ch;
cout<<\nThink of a number between 1 and 99 and I shall ;
cout<<\n guess what it is. Type e for equal, g for greater
than;
cout<<\nand l for less than;
incr=guess=50;
while(incr>1.0)
{
Cout<<\n Is your number grater than or less than %.0f?,guess;
incr=incr/2;
if((ch==getche())==e)
break;
else if(ch==g)
guess=guess+incr;
else
guess=guess-incr;
}
Cout<<\nThe number is %.0f. Am I not clever?,guess;
}
22


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280


SWITCH Statement
The switch statement is similar to the else if construct but has more
flexibility and a clear format.
Vod main(void)
Float num1=1.0,num2=1.0;
Char op;
While(!(num1==0.0 && num2==0.0))
{
Cout<<\n\n Enter number,operator,number\n;
Cin>>num1>>op>>num2;
switch(op)
{
case+:
cout<<num1<<num2;
break;
case*:
cout<<num1*num2;
break;
case-:
cout<<num1-num2;
break;
default:
cout<<Unknown Operator;
}
}
}
The break statements are necessary to terminate the switch
statement. When the body of statements in a particular case has
been executed, the break statement has the effect of immediately
taking the programme out of the structure it finds itself in, without
break, the programme will execute not only the statements for a
particular case but all the statements for the following case as well.


The Conditional Operator
It consists of two symbols used on three different expressions
and thus it has the distinction of being the only ternary operator in
C. The conditional operator has the form
Condition? Expression1: Expression2
Condition is evaluated (true/false). If it is true, the entire
conditional expression takes on the value of expression1. It is false,
the conditional expression takes on the value of expression2.
23


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
Max=(num1>num2)? Num1:Num2;
Two values num1 and num2 are being compared. If num1 is greater
than num2 then it will be assigned to the max variable otherwise
num2, which is obviously greater than num1 will be assigned to
max. In any case at the end max would have the larger value of
two given values.

FUNCTIONS
A computer programme cannot handle every task alone.
Instead, it calls on other program-like entities called functions in c-
to carry out specific task.
Simple function
Void line(void);
Void main(void)
{
line();
cout<<\xDBAshfaq Ahmad Waraich\xDB\n;
line();
}
void line(void)
{
int j;
for(j=1; j<=20; j++)
cout<<\xDB;
cout<<\n;
}

Structure Of Function
The previous programme looks almost like two little
programmes but actually each of these programmes is a function. It
does not matter if main() is the first function in the listing, you can
place other functions before it and main() will still be executed.
In this example main() calls the function line(), calls means to
cause to be executed. There are three programme elements
involved in using a function: function definition, the call to the
function and the function prototype.

1. The Function Definition.
The function itself is referred to as the function definition. The
function starts with a line that includes the function name among
other elements.
Void line (void) //note no semicolon.
24


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
The line is declarator. The first void means that line could not
return anything and the second void means that it takes no
arguments.
Note that the declarator does not end with a semicolon. It is not a
programme statement whose execution causes something to
happen. Rather it tells the compiler that a function is being
defined.
The function definition continues with the body of the function: the
program statements that do the work.

2. Calling the Function.
As with the c library function we have seen such as cout and
getch(), our user written function line() is called from main(),
simply by using its name, including the parenthesis following the
name. The parenthesis let the compiler know that you are referring
to a function and not a variable or something else. Calling a
function like this is a c statement, so it ends with a semicolon.
line ();

this function call causes control to be transferred to the code in the
definition of line(). This function call causes drawing its rows of
square on the screen, and then return to main(), to the statement
immediately following the function call.

3. Function Prototype.
This is the line before the beginning of main():
Void line (void);
This looks very much like the declarator line at the start of the
function definition, except that it ends with a semicolon. What is
purpose?
You have already seen many examples of variables in c programs.
All the variables were defined by name and data type before they
were used. A function is declared in a similar way at the beginning
of a programme before it is called. The function definition (or
prototype-mean same thing) tells the compiler the name of the
function, the data type, the function returns (if any) and the
number and data types of the functions arguments (if any).

Local or AutomaticVariables
The variable j used in the line() function is known only to
line(); it is invisible to the main() function. If we add the following
statement to main () (without declaring a variable j)
Printf(%d,j);
We would get a compiler error because main() would know nothing
about this variable. We could declare another variable also called j
25


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
in the main(), it would be a completely separate variable, known to
main() but not to line(). Variables defined in a function are
unknown outside the function. The question of which function
know about a variable and which does not is called visibility of a
variable. A local variable will be visible to the function it is defined
in but not to others.
A local variable used in this way in a function is known in c as
an automatic variable, because it is automatically created when a
function is called and destroyed when the function returns. The
length of time a variable lasts is called its lifetime.

Functions that return a value.
A function that uses no arguments but returns a value perform
a similar role as you call 14 through your telephone set and it
returns current time. So you are saying nothing just calling and it
gives you back time because computer is on other side. You call
the function, it gets a certain piece of information and returns it to
you. The function getche() operates in just that way, you call it-
without giving it any information and it returns the value of the first
character typed on the keyboard.
Suppose we want to write a programme that takes upper case
letters from us and returns us lower case letters.

Programme
Char getlc(void);
Void main(void);
{
char chlc;
cout<<\nType a for first selection, b for second selection;
chlc=getlc();
switch(chlc)
{
case a:
cout<<\n you typed an a.;
break;
case b:
cout<<\n you typed an b.;
break;
default:
cout<<\n you choosed a non existing selection.;
}
}
char getlc(void)
{
char ch;
26


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
ch=getche();
if(ch>64 && ch<91)
ch=ch+32;
return(ch);
}

The Rreturn Statement
The return statement has two purposes. First, executing it
immediately transfers control from the function back to the calling
programme. Second, whatever, is inside the paranthesis following
return is returned as a value to the calling programme.
The return statement need not be at the end of the function. It
can occur anywhere in the function. We can modify the previous
programmes getlc() function to utilize this return statement.

Char getlc(void)
{
char ch;
ch=getche();
if(ch>64 && ch<91)
return(ch+32);
else
ch=ch+32;
return(ch);
}

Using Arguments to Pass Data to Functions
The mechanism used to convey information to function is the
arguments.
27


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
Void bar(int);
Void main(void)
{
Cout<<\nAwais Arshad Waraich\t);
bar(27);
cout<<Ali Shavez Waraich\t;
bar(41);
cout<<Anas Shahbaz Waraich\t;
bar(34);
cout<<Asad Shahbaz Waraich\t;
bar(22);
cout<<Bilal Hussain Waraich\t;
bar(15);
cout<<Sheraz Javed Waraich\t;
bar(17);
}
void bar(int score)
{
int j;
for(j=1; j<=score; j++)
cout<<\xCD;
cout<<\n;
}

Passing Variables as Arguments
Void bar(int inscore);
Void main(void)
{
int inscore=1;
cout<<\n;
while(inscore!=0)
{
Cout<<Score;
Cin>>inscore;
bar(inscore);
}
}
void bar(int score)
{
int j;
for(j=1; j<=score; j++)
cout<<\xCD;
cout<<\n;
}
28


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280


External Variable or Global Variable
It is sometimes desirable to use a variable known to (that is
visible to) all the functions in a programme, rather than just one.
In this case we have external variable sometimes called global
variable.
Void oddeven(void);
Void negative(void);
Int keynumb;
Void main(void)
{
Cout<<\nEnter Keynumb:;
Cin>>keynumb;
oddeven();
negative();
}
void oddeven(void)
{
if(keynumb%2)
cout<<Keynumb is odd.\n;
else
cout<<Keynumb is even.\n;
}
void negative(void)
{
if(keynumb<0)
cout<<Keynumb is Negative.\n;
else
cout<<Keynumb is Positive.;}

Main() and Prototyping.
Although prototypes are specified for all functions, we do not
use one for main(). You can do this if you want but because main()
is a special case, the prototype is understood to exist. Turbo c does
not generate error message if you neglect a prototype for main().
You can also leave out the void used to specify the arguments to
main() without eliciting any error message.

Preprocessor Directives.
We mentioned the directive # include earlier; here we shall
focus on another directive #define. Various other directives are
also existing in c.
To understand preprocessor directives, let us first review what a
compiler does when you write a line of programme code
29


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
Num=44;
You are asking the compiler to translate this code into
machine language instructions that can be executed by the
microprocessor chip in the computer. Thus most of your listing
consists of instructions to the microprocessor. Preprocessor
directives, on the other hand, are instructions to the compiler
itself. Rather than being translated into machine language, they
are operated on directly by the compiler before the compilation
process even begins; hence the name preprocessor.

The #define Directive.
The simplest use for the #define directive is to assign names
(Days,Pi, for example) to constants such 365 or 3.1415 etc.
#include <stdio.h>
#define PI 3.1415
void main(void)
{
int radius,area;
cout<<Enter Radius:;
cin>>radius;
area=PI*radius*radius;
cout<<The Area is =<<area;
}

Static Variable
There is another class of variables we should mention at this
point, static variables. Earlier we came to know that automatic
variables are created and destroyed automatically because as soon
as a function is called, its local variables called sometimes
automatic variables are created and with the end of the function,
they are destroyed.
However, sometimes you want a function to remember
something between calls to it. Thats if a local variable in the
function is left with a value when the function returns. You would
like to find the same value there when you call the function again.
Unfortunately, local variables cannot do it because they not only
lose their value but also cease to exist altogether when the function
returns.
An external variable can solve this problem because external
variables keep their values for the life of the programme not being
associated with any function.
This is where static variables come in. A static variable is defined
within a function lika a local variable and is visible within the
function. However, it keeps its value between calls to the function.

30


Ashfaq Ahmed Waraich
ashfaqmbd@gamil.com
0300 755 3280
Int func(void);
Void main(void)
{
int j;
for(j=0; j<4; j++)
cout<<\nyou have called me<<func()<<times;
}
int func(void)
{
static int k;
return(++k);
}

Das könnte Ihnen auch gefallen