Introduction to c



Download 0.91 Mb.
Page5/13
Date28.05.2018
Size0.91 Mb.
#51782
1   2   3   4   5   6   7   8   9   ...   13

e.g.:- x = max(num1, num2);

Arguments appearing in the function header are also called as formal arguments or formal parameters. Arguments appearing in the function reference in the calling statement are called the actual arguments, since the actual data is transferred to the function through them. Any formal argument, which is not declared, is taken to be of type int by default.

Actual arguments can be expressed as constants, variables, expressions or functions and the formal arguments must be variables. The actual arguments must be identical in number, order and type with the formal arguments.

When a function call is made, only a copy of the values of actual argument is passed in the called functions. What occurs inside the function will have no effect on the variables used in the actual argument list.

Identifiers used as formal arguments are considered local to the function and they are released from the memory when the function terminates. Therefore other variables of arguments appearing outside the function can have the same name as those of the formal arguments.

The Return statement causes the function to terminate and the control to be return to the point from where the function was called. A function can send back a value to the calling program using the Return statement. A called function can also return one value per call. Return can be used differently like,

return;

return <expr>;



return(<expr>);

The plain return; does not return any value, only terminates the function. Bur the second and third model returns a value to the calling program before terminating the function.



E.g.:-(1) e.g.:-(2)

int max(int m, int n) int xyz()



{ {

statements; statements;

return y; return;

} }

By default all 'C' function returns the type int , when no other type is specified. To enable a calling function to receive a non-integer value from a called function,



  • The data type, corresponding to the data required must be mentioned in the function header. The data type tells the compiler, the type of data the function is to return.

e.g.:-

float div(float num1, float num2)



{

return(num1/num2);



}

  • The called function must be declared at the start of the body in the calling function like any other variable. This is to tell the calling-function the type of the data that the function is actually returning. This is called Prototyping.

e.g.:-

float div(float num1, float num2);

A function that does not return any value can not be used in an expression. It can only used as an independent statement. If the function does not returns any value then it can be declared as a void type function. void means nothing. That is void tells the compiler that the function do not return any values.

e.g.:-

void sample(void);



FUNCTION WITH ARRAYS

'C' also allows passing the values of an array to a function. To pass an array to a called function mention only the name of the array with out any subscripts and size of the array, as arguments.



e.g.:-

main()


{

float ar[25];

check (ar);

}

In the function header , the formal argument should be an array name with empty brackets.



e.g.:-

float check( xy[ ] )



{

statements;



}

If a function changes the values of an array elements then these changes will be made to the original array that passed to the function. When the entire array is passed as an argument the contents of the array are not copied into the formal parameters array, instead, information about the addresses of array elements are passed into the function. Therefore any changes introduced to the array elements in the function are reflected in the original array in the calling function.



RECURSION

Recursion is a process where a function may invoke itself from within its body(direct method) or a function may be invoked by another which was itself invoked by the first function (indirect method).

main( ) main()

{ {

------- indirect ----------

fun( ); main();

------ direct ----------

} }

fun( )


{

-----


main( );

-----


}

e.g.:- main()



{

printf("This is an example of recursion \n");

main();

}

When executed, the above example will produce the output indefinitely. To stop execution press Ctrl+Break.

Each recursive function must specify an exit condition for it to terminate, otherwise it will go indefinitely. Recursive function can be effectively used to solve problems where the solution is expressed in terms of successively applying the same solution to subsets of the problem.

Q1. Write a program to generate a sequence of Fibonacci numbers.(Fibonacci numbers form a sequence, where end number is the sum of the previous two numbers, with the first two numbers being 1.) [ e.g.:- 1,1,2,3,5,8,13,21,………. ]

# include

long int fibo(int m);

main()

{

int n, x;

long i;

printf("%Enter no. of Fibonacci numbers : ");



scanf("%d", &n);

for(x=1; x<=n; x++)



{

printf("%ld", fibo(x) );



}

}

long int fibo(int m)



{

if(m<=2)


return 1;

else


return(fibo(m-1)+fibo(m-2));

}

If the user enters 4 to the variable n, then,

fibo(1) returns 1

fibo(2) returns 1

fibo(3) calls fibo(2) and fibo(1)

Then the result is calculated backward as, fibo(3) = 1 + 1 = 2

fibo(4) calls fibo(3) and fibo(2)

fibo(3) calls fibo(2) and fibo(1)

fibo(2) returns 1

fibo(1) returns 1

so the result is calculated backward as, fibo(3) = 1 + 1 = 2

fibo(4) = 2 + 1 = 3



Q2.Write a function factorial to find out the factorial of the given number.

factorial(int n)



{

int fact;

if(n==1)

return 1;

else

fact = n * factorial(n-1);



return fact;

}

Assume n=3. Since the value of n is not 1, the statement, fact =n * factorial(n-1); will be executed with n=3, i.e., fact=3 * factorial(2); factorial(2) will return 2*factorial(1). This time factorial() is called with n=1, and the function returns 1. Therefore the result is.

fact = 3*factorial(2)

= 3*2*facorial(1)

= 3*2*1

= 6



Q3. To print numbers up to the user given number from 1.

# include

display(int i);

main() display(int i)

{ {

int i; if(i = = 0)

clrscr(); return;

printf("Enter Number : ") ; else

scanf("%d", &i); display(i - 1);

display(i); printf("%d \n", i);

return; }

}

STORAGE CLASSES

A variable name identifies some physical location within computer, where the string of bits representing the variable’s value is stored. There are basically two kinds of locations in a computer where a value can be kept, memory (RAM) or one of the CPU registers. It is a variable storage class, which determines whether it is to be stored in memory or in a register. The storage class also determines the scope and longevity (lifetime or permanence) of each class of variables. The scope of variables determines over what parts of the program a variable is available for use (active). Longevity refers to the period during which a variable retains a given value during execution of a program (alive). Thus storage class determines the location of variable in the computer, the scope and longevity of the variables in the program. There are four storage classes in ‘C’ there are automatic, external, static, register.



AUTOMATIC VARIABLES

Automatic variables are declared within a function and can be accessed only from within the function where they are declared i.e., from the point of its definition to the end of the function. i.e., it is local or private to the function because automatic variables are created when function is called and destroyed automatically when the function is exited. These classes of variables are also called internal variables.

When a variable is declared inside a function it is automatically assigned a class auto and the compiler sets aside the computers memory area for the variable. Automatic variables defined in different functions are independent of one another, though they may have the same name.

Formal arguments of a function are automatic, unless a different storage is enclosed within the function declaration. It is not necessary to use the keyword auto at the beginning of each variables determines the automatic storage class.

An automatic variable does not retain its value once the function terminates. Therefore it is necessary to reassign values every time a function is entered. The scope of the automatic variables can be smaller than the entire function, if it is declared in from within single compound statement. The scope then will be restricted to that compound statement.

e.g.: -

main( ) func1( )



{ {

int x=10; int y=20;

printf(“%d”,x); printf(“%d”,y);

func1(); prinrf(“%d”,x);

printf(“%d”,y); return;

} }

In the above example errors will occurs at two lines. First the printf(%d”, y); statement in the main() error will be undefined variable the second the printf(“%d”, x); statement in the func1() error will be the same, undefined symbol. This is because the automatic variables declared in one function is local to that function.



e.g.: -

main()


{

int x=5;


printf(“%d”, x);

{

int y=2;


printf(“%d”, x);

printf(“%d”, y);



}

printf(“%d”, y);



}

Here also an undefined variable error will occur at the last printf(“%d”, y) statement. Here all the variables declared in the same function but the variable y is declared in the inner most compound statement, therefore the scope of y is only within that compound statement.



e.g.: -

main()


{

int m=100;

function2 ();

printf(“%d”, m);



}

function1()



{

int m=10;

printf(“%d”, m);

}

function2()



{

int m=100;

function1();

printf(“%d”, m);



}

Output will be



10

100

1000

Because m in the function does not affect its value in other functions, and the value of m is defined when it leaves the function.



EXTERNAL VARIABLES

Variables that are both alive and active throughout the entire program are known as external variables, also called global variables. External variable definition must be defined outside the functions. That access the external variables and usually before the function definition. The keyword extern is not required as the class is determined by the position of the definition. External variables are automatically initialized by the compiler to 0. They can be initialized with other values. The initialization must be done with constants and not with expressions. The external variable definition reserves storage space in memory. The scope of an external variable is from the point of their definition to the remainder of the program. They are normally written at the beginning of a program so that their scope extends to all the functions in a program values can be assigned to external variables by any functions within their scope and the values are also available to all functions within the scope. The values are lost only when the program terminates.

External variables provides an easy way of transferring data between functions as data is shared by all functions but there is a possibility of making unwanted changes by the functions. And the external variables are not released from the memory until the program ends. This makes debugging difficult, as one must keep track of all global variables in all functions.

When a local variable (automatic class) and a global variable (extern class) have the same name, the local variable will have precedence over the global one in the function it is declared.



e.g.:-

# include

int num; will return,

main() 100



{ 10

num=100; 100

printf("%d \n", num);

function(); When the function references the variable num, it will be

printf("%d", num); referencing only its local variable, not the global one. The

} value of num in main will not be affected.

function()



{

int num=10;

printf("%d \n", num);

num+=1000;



}

EXTERANAL VARIABLE DECLARATION

An external variable definition must be defined outside the functions, that access the external variables and usually before the function definitions. An external variable definition automatically allots space for the external variables in memory. The system initialises the external variables to zero. All the functions can access the external variables from the point of its definition.



e.g.:-

int num;


main()

{

fun1();


printf("%d \n", num);

func2();


}

func1()


{

printf("%d \n", num);

num+=20;

}

fun2();


{

printf("%d \n", num);



}

But, if the external variable is defined after the accessing functions, the functions cannot access those variables.

main()

{

printf("%d \n", num);

fun1();

}

fun1()


{

printf("%d \n", num);



}

int num; /* external variable definition */

Declaring the variables within the functions as external can solve this problem. External variable declarations are needed if the function definition in which the variable is used comes before the external variable definition. An external variable declaration must begin with the storage class specifier extern. An external variable declaration will not allocate the storage space in memory, also initial values cannot be assigned to external variable declarations.

e.g.:-


main()

{

extern int num; /* external variable declaration */

printf("%d \n", num);

fun1();


}

fun1()


{

extern int num; /* external variable declaration */

printf("%d \n", num);

}

int num; /* external variable definition */



STATIC VARIABLES

Static variables are defined within a function and therefore their scope is local to the function in which they are defined from the point of their definition and not outside it. i.e. not outside the function. Unlike automatic variables, static variables retain their values even after the function terminates, till the end of the program. As a result, if a function terminates and then is re-entered later, the static variables defined within that function would still retain their former values. The variable declaration must begin with the static storage class designation.

e.g.:- static int num;

Initial values can be assigned to variables within static variable declarations and the initial values must be expressed as constants and not expressions. The compiler automatically assigns the default value of zero to any static variable, which is not initialised. The values are not re-initialised when a function is re-entered. The variables retain their previous values. Initialisation takes place only once, when the program is compiled.

It is possible to define static variables having the same names as external variables. The local variables (static as well as automatic) take precedence over the external variables and the values of the external variables will be unaffected by any manipulation of the local variables. External variables of the same name as local variables in a function can not be accessed in that function.

e.g.:- 1

main()


{ fun()

int i; {

for(i=0;i<3;i++) int num=65;



{ printf("%d - - %c \n", num, num);

fun(); num++;



} }

}

Will return, 65 - - A This is because each time fun() is called, the variable num

65 - - A which has a storage class auto is re-initialised to 65 (ASCII - A).

65 - - A When the function, terminates the new value of num is lost

( ASCII - 66).


e.g.:- 2

main()


{ fun()

int i; {

for(i=0;i<3;i++) static int num=65;

{ printf("%d - - %c \n", num, num);

fun(); num++;



} }

}

Will return, 65 - - A When the storage class is static, num is initialised to 65

66 - - B only once when the program is compiled. At end of the first

67 - - C function call, num has a value of 66 (ASCII - B) and in the next call num has a value of 67 (ASCII - C). At the end of last function call num has a value of 68 (ASCII - D). This value is lost when the program terminates.



REGISTER VARIABLES

Computers have internal registers in their ALU which are used to store data temporarily that needs to accessed repeatedly. Intermediate results of calculations are also stored in registers. Operations can be performed upon the data stored in registers more quickly than upon the data stored in memory (RAM). The keyword register must be used to define the register variables.



e.g.:- register int i;

If the compiler finds a free register, and if the machine's registers are big enough to hold the variable, the compiler may place that variable's value in that register. Otherwise, the compiler treats register variables as any automatic variables.

i.e., it stores them in the memory (RAM).

The scope and initialisation of the register variables is the same as for the automatic variables, except for the location of storage. i.e., the register variables are local to a function and they are created only when the function is invoked and the value will be lost once the function is exited from. The system does not initialise these variables.

The number of registers available is limited. Therefore you should determine which variables in the program are used most often, then declare them as register variables.

e.g.:-

main()


{

register int i;

for(i=0; i<100; i++)

{

printf("%d", i);



}

}

POINTERS in C

A pointer is a variable, which contains the address of a memory location or variable, rather than its stored value. A pointer provides an indirect way of accessing the value of a data item (variable). For each type of data, it is possible to declare a corresponding type of pointer. The type associated with pointers is pointer, but pointers point to variables of other data types.

The reference (&) and Indirection (*) operators

Pointers can be manipulated in C by using two unary operators. The reference or address of operator, denoted by & and the indirection operator denoted by *. The computers memory is divided into uniquely addressable units called words or bytes. The addresses start from 0 and these are unsigned numbers.

Consider an integer variable, i with value 500.

i.e., int i = 500;

This declaration tells the compiler to,


  1. Reserve space in memory to hold the integer value,

  2. Associate the name i with this memory location,

  3. Store the value 500 at this location

Suppose the address of the memory location is 65496,

i



Location name

500



Value at location

65496



Location no.(address)

The address of a variable can be obtained by prefixing the variable with the reference operator. (e.g.:- &i) i.e., The address operator is used to return the address of the variable.

e.g.:-

main()



Download 0.91 Mb.

Share with your friends:
1   2   3   4   5   6   7   8   9   ...   13




The database is protected by copyright ©ininet.org 2024
send message

    Main page