Date post: | 05-Jul-2018 |
Category: |
Documents |
Upload: | akhilesh-chaudhry |
View: | 228 times |
Download: | 0 times |
of 41
8/15/2019 C Programming Language Notes for Second Test
1/41
C programming language provides following types of loop to handle looping requirements.
Loop Type Description
while loop
Repeats a statement or group of statements while a given
condition is true. It tests the condition before executing the
loop body.
for loopExecute a sequence of statements multiple times andabbreviates the code that manages the loop variable.
do...while loopLike a while statement except that it tests the condition at
the end of the loop body
nested loops!ou can use one or more loop inside any another while for
or do..while loop.
While Loop
" while loop statement in C programming language repeatedly executes a target statement as
long as a given condition is true.
#yntax$
%he syntax of a while loop in C programming language is$
while&condition'
( statement&s')
*
+ere statement(s) may be a single statement or a block of statements. %he condition may be any
expression and true is any non,ero value. %he loop iterates while the condition is true.
-hen the condition becomes false program control passes to the line immediately following the
loop.
+ere key point of the while loop is that the loop might not ever run. -hen the condition is testedand the result is false the loop body will be skipped and the first statement after the while loop
will be executed.
Example$
include /stdio.h0
include /conio.h0
int main &'
1
http://www.tutorialspoint.com/cprogramming/c_while_loop.htmhttp://www.tutorialspoint.com/cprogramming/c_for_loop.htmhttp://www.tutorialspoint.com/cprogramming/c_do_while_loop.htmhttp://www.tutorialspoint.com/cprogramming/c_nested_loops.htmhttp://www.tutorialspoint.com/cprogramming/c_for_loop.htmhttp://www.tutorialspoint.com/cprogramming/c_do_while_loop.htmhttp://www.tutorialspoint.com/cprogramming/c_nested_loops.htmhttp://www.tutorialspoint.com/cprogramming/c_while_loop.htm
8/15/2019 C Programming Language Notes for Second Test
2/41
(
12 local variable definition 21
int a 3 45)
12 while loop execution 21
while& a / 65 ' (
printf&7value of a$ 8d9n7 a')
a::) * getch&')*
-hen the above code is compiled and executed it produces following result$
value of a$ 45value of a$ 44value of a$ 46
value of a$ 4;
value of a$ 4<
value of a$ 4=value of a$ 4>
value of a$ 4?
value of a$ 4@value of a$ 4A
For Loop
" for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
#yntax$
%he syntax of a for loop in C programming language is$
for & init) condition) increment '
(
statement&s')
*
+ere is the flow of control in a for loop$
2
8/15/2019 C Programming Language Notes for Second Test
3/41
4. %he init step is executed first and only once. %his step allows you to declare and
initiali,e any loop control variables. !ou are not required to put a statement here as long as a
semicolon appears.6. Bext the condition is evaluated. If it is true the body of the loop is executed. If it is
false the body of the loop does not execute and flow of control umps to the next statement ust
after the for loop.;. "fter the body of the for loop executes the flow of control umps back up to
the incrementstatement. %his statement allows you to update any loop control variables. %his
statement can be left blank as long as a semicolon appears after the condition.
8/15/2019 C Programming Language Notes for Second Test
4/41
value of a$ 4?value of a$ 4@
value of a$ 4A
Do – While Loop
Dnlike for and while loops which test the loop condition at the top of the loop
the do...while loop in C programming language checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is garanteed to
execte at least one time.
#yntax$
%he syntax of a do...while loop in C programming language is$
do
(
statement&s')
*while& condition ')
Botice that the conditional expression appears at the end of the loop so the statement&s' in theloop execute once before the condition is tested.
If the condition is true the flow of control umps back up to do and the statement&s' in the loop
execute again. %his process repeats until the given condition becomes false.
Example$
include /stdio.h0
int main &'
(
12 local variable definition 21
int a 3 45)
12 do loop execution 21
do
4
8/15/2019 C Programming Language Notes for Second Test
5/41
(
printf&7value of a$ 8d9n7 a')
a 3 a : 4)
*while& a / 65 ')
return 5)
*
-hen the above code is compiled and executed it produces following result$
value of a$ 45value of a$ 44
value of a$ 46
value of a$ 4;value of a$ 4<
value of a$ 4=
value of a$ 4>value of a$ 4?
value of a$ 4@
value of a$ 4A
!ested Loops
C programming language allows to use one loop inside another loop. ollowing section shows
few examples to illustrate the concept.
Syntax:
%he syntax for a nested for loop statement in C is as follows$
for & init) condition) increment '(
for & init) condition) increment ' ( statement&s')
*
statement&s')
*
%he syntax for a nested while loop statement in C programming language is as follows$
5
8/15/2019 C Programming Language Notes for Second Test
6/41
while&condition'(
while&condition'
( statement&s')
* statement&s')*
%he syntax for a nested do...while loop statement in C programming language is as follows$
do
( statement&s')
do
( statement&s')
*while& condition ')
*while& condition ')
" final note on loop nesting is that you can put any type of loop inside of any other type of loop.
or example a for loop can be inside a while loop or vice versa.
6
8/15/2019 C Programming Language Notes for Second Test
7/41
Example:
%he following program uses a nested for loop to find the prime numbers from 6 to 455$
include /stdio.h0
int main &'
( 12 local variable definition 21
int i )
for&i36) i/455) i::' (
for&36) /3 &i1') ::' if&F&i8'' break) 11 if factor found not prime
if& 0 &i1'' printf&78d is prime9n7 i')
*
return 5)
*
-hen the above code is compiled and executed it produces following result$
6 is prime; is prime
= is prime
? is prime44 is prime
4; is prime
4? is prime4A is prime
6; is prime
6A is prime
;4 is prime;? is prime
8/15/2019 C Programming Language Notes for Second Test
8/41
@; is prime@A is prime
A? is prime
"rea# $tatement
%he %rea# statement in C programming language has following two usage$
4. -hen the %rea# statement is encountered inside a loop the loop is immediatelyterminated and program control resumes at the next statement following the loop.
6. It can be used to terminate a case in the switch statement &covered in the next chapter'.
If you are using nested loops & ie. one loop inside another loop' the break statement will stop theexecution of the innermost loop and start executing the next line of code after the block.
#yntax$
%he syntax for a %rea# statement in C is as follows$
break)
Example$
include /stdio.h0 int main &'
(
12 local variable definition 21
int a 3 45)
12 while loop execution 21 while& a / 65 '
(
printf&7value of a$ 8d9n7 a')
a::) if& a 0 4='
(
12 terminate the loop using break statement 21 break)
* *
return 5)*
-hen the above code is compiled and executed it produces following result$
8
8/15/2019 C Programming Language Notes for Second Test
9/41
value of a$ 45value of a$ 44
value of a$ 46
value of a$ 4;value of a$ 4<
value of a$ 4=
&ontine $tatement
%he contine statement in C programming language works somewhat like the %rea# statement.
Instead of forcing termination however continue forces the next iteration of the loop to take
place skipping any code in between.or the for loop contine statement causes the conditional test and increment portions of the
loop to execute. or the while and do...while loops contine statement causes the program
control passes to the conditional tests.
#yntax$
%he syntax for a contine statement in C is as follows$
continue)
Example$
include /stdio.h0 int main &'
(
12 local variable definition 21
int a 3 45)
12 do loop execution 21
do (
if& a 33 4='
( 12 skip the iteration 21
a 3 a : 4)
continue) *
printf&7value of a$ 8d9n7 a') a::)
*while& a / 65 ')
return 5)
*
9
8/15/2019 C Programming Language Notes for Second Test
10/41
-hen the above code is compiled and executed it produces following result$
value of a$ 45value of a$ 44
value of a$ 46
value of a$ 4;value of a$ 4<
value of a$ 4>
value of a$ 4?
value of a$ 4@value of a$ 4A
goto $tatement
" goto statement in C programming language provides an unconditional ump from the goto to a
labeled statement in the same function.!'T Dse of goto statement is highly discouraged in any programming language because it
makes difficult to trace the control flow of a program making the program hard to understandand hard to modify. "ny program that uses a goto can be rewritten so that it doesnGt need the
goto.
#yntax$
%he syntax for a goto statement in C is as follows$
goto label)
..
.
label$ statement)+ere la%el can be any plain text except C keyword and it can be set anywhere in the C program
above or below to goto statement.
Example$
include /stdio.h0
int main &'
( 12 local variable definition 21
int a 3 45)
12 do loop execution 21 LHH$do
(
if& a 33 4=' (
12 skip the iteration 21
a 3 a : 4)
10
8/15/2019 C Programming Language Notes for Second Test
11/41
goto LHH) *
printf&7value of a$ 8d9n7 a')
a::)
*while& a / 65 ')
return 5)*
-hen the above code is compiled and executed it produces following result$
value of a$ 45
value of a$ 44value of a$ 46
value of a$ 4;
value of a$ 4<value of a$ 4>
value of a$ 4?
value of a$ 4@
value of a$ 4A
Fnctions
" function is a group of statements that together perform a task. Every C program has at least
one function which is main() and all the most trivial programs can define additional functions.
!ou can divide up your code into separate functions. +ow you divide up your code among
different functions is up to you but logically the division usually is so each function performs aspecific task.
" function declaration tells the compiler about a functionGs name return type and parameters. "function definition provides the actual body of the function.
%he C standard library provides numerous builtJin functions that your program can call. or
example function strcat() to concatenate two strings function memcpy() to copy one memorylocation to another location and many more functions.
" function is known with various names like a method or a subJroutine or a procedure etc.
Kefining a unction$
%he general form of a function definition in C programming language is as follows$
returntype functionname& parameter list '(
11
8/15/2019 C Programming Language Notes for Second Test
12/41
body of the function*
" function definition in C programming language consists of a function header and a functionbody. +ere are all the parts of a function$
• *etrn Type$ " function may return a value. %he retrn+type is the data type of the
value the function returns. #ome functions perform the desired operations without returning avalue. In this case the returntype is the keyword oid.
• Fnction !ame %his is the actual name of the function. %he function name and the
parameter list together constitute the function signature.
• -arameters " parameter is like a placeholder. -hen a function is invoked you pass a
value to the parameter. %his value is referred to as actual parameter or argument. %he parameter
list refers to the type order and number of the parameters of a function. arameters are optional)
that is a function may contain no parameters.
• Fnction "ody %he function body contains a collection of statements that define what
the function does.
Example$
ollowing is the source code for a function called max(). %his function takes two parameters
num4 and num6 and returns the maximum between the two$
12 function returning the max between two numbers 21
int max&int num4 int num6'(
12 local variable declaration 21
int result)
if &num4 0 num6'
result 3 num4) else
result 3 num6)
return result)
*
unction Keclarations$
" function declaration tells the compiler about a function name and how to call the function.
%he actual body of the function can be defined separately.
" function declaration has the following parts$
returntype functionname& parameter list ')
or the above defined function max&' following is the function declaration$
int max&int num4 int num6')
12
8/15/2019 C Programming Language Notes for Second Test
13/41
arameter names are not important in function declaration only their type is required so
following is also valid declaration$
int max&int int')
unction declaration is required when you define a function in one source file and you call thatfunction in another file. In such case you should declare the function at the top of the file calling
the function.
Calling a unction$
-hile creating a C function you give a definition of what the function has to do. %o use a
function you will have to call that function to perform the defined task.
-hen a program calls a function program control is transferred to the called function. " called
function performs defined task and when its return statement is executed or when its functionJ
ending closing brace is reached it returns program control back to the main program.
%o call a function you simply need to pass the required parameters along with function name andif function returns a value then you can store returned value. or example$
include /stdio.h0
12 function declaration 21
int max&int num4 int num6')
int main &'(
12 local variable definition 21
int a 3 455) int b 3 655)
int ret)
12 calling a function to get max value 21
ret 3 max&a b')
printf& 7Max value is $ 8d9n7 ret ')
return 5)
*
12 function returning the max between two numbers 21int max&int num4 int num6'
(
12 local variable declaration 21 int result)
13
8/15/2019 C Programming Language Notes for Second Test
14/41
if &num4 0 num6' result 3 num4)
else
result 3 num6)
return result)*
I kept max&' function along with main&' function and complied the source code. -hile running
final executable it would produce following result$
Max value is $ 655
unction "rguments$
If a function is to use arguments it must declare variables that accept the values of the
arguments. %hese variables are called the formal parameters of the function.
%he formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
-hile calling a function there are two ways that arguments can be passed to a function$
&all Type Description
Call by value
%his method copies the actual value of an argument into the
formal parameter of the function. In this case changes madeto the parameter inside the function have no effect on the
argument.
Call by reference
%his method copies the address of an argument into the
formal parameter. Inside the function the address is used to
access the actual argument used in the call. %his means thatchanges made to the parameter affect the argument.
Ny default C uses call %y ale to pass arguments. In general this means that code within a
function cannot alter the arguments used to call the function and above mentioned example while
calling max&' function used the same method.
&all %y ale
%he call %y ale method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case changes made to the parameter
inside the function have no effect on the argument.
14
http://www.tutorialspoint.com/cprogramming/c_function_call_by_value.htmhttp://www.tutorialspoint.com/cprogramming/c_function_call_by_reference.htmhttp://www.tutorialspoint.com/cprogramming/c_function_call_by_value.htmhttp://www.tutorialspoint.com/cprogramming/c_function_call_by_reference.htm
8/15/2019 C Programming Language Notes for Second Test
15/41
Ny default C programming language uses call by value method to pass arguments. In general
this means that code within a function cannot alter the arguments used to call the function.
Consider the function swap() definition as follows.
Bow let us call the function swap() by passing actual values as in the following example$
include /stdio.h0
void swap&int x int y'
( int temp)
temp 3 x) 12 save the value of x 21
x 3 y) 12 put y into x 21 y 3 temp) 12 put temp into y 21
return)*
int main &'
( 12 local variable definition 21
int a 3 455)
int b 3 655)
printf&7Nefore swap value of a $ 8d9n7 a ') printf&7Nefore swap value of b $ 8d9n7 b ')
12 calling a function to swap the values 21
swap&a b')
printf&7"fter swap value of a $ 8d9n7 a ')
printf&7"fter swap value of b $ 8d9n7 b ')
return 5)
*
Let us put above code in a single C file compile and execute it it will produce following result$
Nefore swap value of a $455
Nefore swap value of b $655
"fter swap value of a $455
"fter swap value of b $655
15
8/15/2019 C Programming Language Notes for Second Test
16/41
&all %y reference
%he call %y reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function the address is used to access the actual
argument used in the call. %his means that changes made to the parameter affect the passed
argument.
%o pass the value by reference argument pointers are passed to the functions ust like any other
value. #o accordingly you need to declare the function parameters as pointer types as in the
following functionswap() which exchanges the values of the two integer variables pointed to by
its arguments.
12 function definition to swap the values 21
void swap&int 2x int 2y'(
int temp)
temp 3 2x) 12 save the value at address x 21 2x 3 2y) 12 put y into x 21
2y 3 temp) 12 put temp into y 21
return)
*
%o check the more detail about C J ointers you can check C J ointers chapter.
or now let us call the function swap() by passing values by reference as in the followingexample$
include /stdio.h0
12 function declaration 21
void swap&int 2x int 2y')
int main &'
(
12 local variable definition 21
int a 3 455) int b 3 655)
printf&7Nefore swap value of a $ 8d9n7 a ') printf&7Nefore swap value of b $ 8d9n7 b ')
12 calling a function to swap the values.
2 Oa indicates pointer to a ie. address of variable a and
16
http://www.tutorialspoint.com/cprogramming/c_pointers.htmhttp://www.tutorialspoint.com/cprogramming/c_pointers.htm
8/15/2019 C Programming Language Notes for Second Test
17/41
2 Ob indicates pointer to b ie. address of variable b. 21
swap&Oa Ob')
printf&7"fter swap value of a $ 8d9n7 a ')
printf&7"fter swap value of b $ 8d9n7 b ')
return 5)
*
Let us put above code in a single C file compile and execute it it will produce following result$
Nefore swap value of a $455
Nefore swap value of b $655
"fter swap value of a $655
"fter swap value of b $455
-hich shows that the change has reflected outside of the function as well unlike call by value
where changes does not reflect outside of the function.
*ecrsie fnction
%he C programming language supports recursion ie. a function to call itself. Nut while using
recursion programmers need to be careful to define an exit condition from the function
otherwise it will go in infinite loop.
Recursive function are very useful to solve many mathematical problems like to calculate
factorial of a number generating fibonacci series etc.
Bumber actorial
ollowing is an example which calculate factorial for a given number using a recursive function$
include /stdio.h0
int factorial&unsigned int i'
( if &i /3 4'
(
return 4)
* return i 2 factorial&i J 4')
*
int main&'
17
8/15/2019 C Programming Language Notes for Second Test
18/41
( int i 3 4=)
printf &7actorial of 8d is 8d9n7 i factorial&i'')
return 5)*
-hen the above code is compiled and executed it produces the following result$
actorial of 4= is 655
ibonacci #eries
ollowing is another example which generates fibonacci series for a given number using a
recursive function$
include /stdio.h0
int fibonaci&int i'
( if &i 33 5'
(
return 5) *
if &i 33 4'
( return 4)
*
return fibonaci&iJ4' : fibonaci&iJ6')*
int main&'
( int i)
for &i 3 5) i / 45) i::'
( printf &78d9t8n7 fibonaci&i'')
*
return 5)
*
-hen the above code is compiled and executed it produces the following result$
5 4 4 6 ; = @ 4; 64 ;<
Arrays
18
8/15/2019 C Programming Language Notes for Second Test
19/41
C programming language provides a data structure called the array which can store a fixedJsi,e
sequential collection of elements of the same type. "n array is used to store a collection of data but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables such as number5 number4 ... and numberAA youdeclare one array variable such as numbers and use numbersP5Q numbersP4Q and ...
numbersPAAQ to represent individual variables. " specific element in an array is accessed by an
index.
"ll arrays consist of contiguous memory locations. %he lowest address corresponds to the first
element and the highest address to the last element.
Keclaring "rrays
%o declare an array in C a programmer specifies the type of the elements and the number of
elements required by an array as follows$
type arrayBame P array#i,e Q)
%his is called a single-dimensional array. %he array$ie must be an integer constant greater than
,ero and type can be any valid C data type. or example to declare a 45Jelement arraycalled %alance of type double use this statement$
double balanceP45Q)
Bow balance is avariable array which is sufficient to hold upto 45 double numbers.
Initiali,ing "rrays
!ou can initiali,e array in C either one by one or using a single statement as follows$
double balanceP=Q 3 (4555.5 6.5 ;.
8/15/2019 C Programming Language Notes for Second Test
20/41
balanceP
8/15/2019 C Programming Language Notes for Second Test
21/41
ElementP5Q 3 455ElementP4Q 3 454
ElementP6Q 3 456
ElementP;Q 3 45;ElementPQ 3 45>ElementP?Q 3 45?
ElementP@Q 3 45@
ElementPAQ 3 45A
Two/Dimensional Arrays
%he simplest form of the multidimensional array is the twoJdimensional array. " twoJ
dimensional array is in essence a list of oneJdimensional arrays. %o declare a twoJdimensional
integer array of si,e xy you would write something as follows$
type arrayBame P x QP y Q)
-here type can be any valid C data type and array!ame will be a valid C identifier. " two
dimensional array can be think as a table which will have x number of rows and y number of
columns. " 6Jdimentional array a which contains three rows and four columns can be shown as
below$
%hus every element in array a is identified by an element name of the form a0 i 10 2 1 where a is
the name of the array and i and are the subscripts that uniquely identify each element in a.
Initiali,ing %woJKimensional "rrays$
Multidimensionalarrays may be initiali,ed by specifying bracketed values for each row.
ollowing is an array with ; rows and each row have < columns.
int aP;QP
8/15/2019 C Programming Language Notes for Second Test
22/41
int aP;QP
8/15/2019 C Programming Language Notes for Second Test
23/41
ointers in C are easy and fun to learn. #ome C programming tasks are performed more easily
with pointers and other tasks such as dynamic memory allocation cannot be performed without
using pointers. #o it becomes necessary to learn pointers to become a perfect C programmer.
LetGs start learning them in simple and easy steps.
"s you know every variable is a memory location and every memory location has its address
defined which can be accessed using ampersand &O' operator which denotes an address in
memory. Consider the following example which will print the address of the variables defined$
include /stdio.h0
int main &'(
int var4)
char var6P45Q)
printf&7"ddress of var4 variable$ 8x9n7 Ovar4 ')
printf&7"ddress of var6 variable$ 8x9n7 Ovar6 ')
return 5)
*
-hen the above code is compiled and executed it produces result something as follows$
"ddress of var4 variable$ bff=a
8/15/2019 C Programming Language Notes for Second Test
24/41
int 2ip) 12 pointer to an integer 21double 2dp) 12 pointer to a double 21
float 2fp) 12 pointer to a float 21
char 2ch 12 pointer to a character 21
%he actual data type of the value of all pointers whether integer float character or otherwise is
the same a long hexadecimal number that represents a memory address. %he only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.
!o" to #se Pointers
%here are few important operations which we will do with the help of pointers very
frequently. (a) we define a pointer variables (%) assign the address of a variable to a pointer
and (c) finally access the value at the address available in the pointer variable. %his is done by
using unary operator 3 that returns the value of the variable located at the address specified by its
operand. ollowing example makes use of these operations$
include /stdio.h0
int main &'
( int var 3 65) 12 actual variable declaration 21
int 2ip) 12 pointer variable declaration 21
ip 3 Ovar) 12 store address of var in pointer variable21
printf&7"ddress of var variable$ 8x9n7 Ovar ')
12 address stored in pointer variable 21
printf&7"ddress stored in ip variable$ 8x9n7 ip ')
12 access the value using the pointer 21
printf&7alue of 2ip variable$ 8d9n7 2ip ')
return 5)
*
-hen the above code is compiled and executed it produces result something as follows$
"ddress of var variable$ bffd@b;c
"ddress stored in ip variable$ bffd@b;c
alue of 2ip variable$ 65
24
8/15/2019 C Programming Language Notes for Second Test
25/41
!4LL -ointers in &
It is always a good practice to assign a BDLL value to a pointer variable in case you do not have
exact address to be assigned. %his is done at the time of variable declaration. " pointer that isassigned BDLL is called a nll pointer.
%he BDLL pointer is a constant with a value of ,ero defined in several standard libraries.
Consider the following program$
include /stdio.h0
int main &'
( int 2ptr 3 BDLL)
printf&7%he value of ptr is $ 8x9n7 ptr ')
return 5)*
-hen the above code is compiled and executed it produces following result$
%he value of ptr is 5
Hn most of the operating systems programs are not permitted to access memory at address 5
because that memory is reserved by the operating system. +owever the memory address 5 hasspecial significance) it signals that the pointer is not intended to point to an accessible memorylocation. Nut by convention if a pointer contains the null &,ero' value it is assumed to point to
nothing.
%o check for a null pointer you can use an if statement as follows$
if&ptr' 12 succeeds if p is not null 21if&Fptr' 12 succeeds if p is null 21
C ointers in Ketail$
ointers have many but easy concepts and they are very important to C programming. %here arefollowing few important pointer concepts which should be clear to a C programmer$
&oncept Description
C J ointer arithmetic%here are four arithmetic operators that can be
used on pointers$ :: JJ : J
25
http://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htmhttp://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htm
8/15/2019 C Programming Language Notes for Second Test
26/41
C J "rray of pointers!ou can define arrays to hold a number of
pointers.
assing pointers to functions in C
assing an argument by reference or by address
both enable the passed argument to be changed in
the calling function by the called function.
& / -ointer arithmetic
%o understand pointer arithmetic let us consider that ptr is an integer pointer which points to the
address 4555. "ssuming ;6Jbit integers let us perform the following arithmetic operation on the
pointer$
ptr::
Bow after the above operation the ptr will point to the location 455< because each time ptr isincremented it will point to the next integer location which is < bytes next to the current
location. %his operation will move the pointer to next memory location without impacting actual
value at the memory location. If ptr points to a character whose address is 4555 then above
operation will point to the location 4554 because next character will be available at 4554.
$n%rementin& a Pointer
-e prefer using a pointer in our program instead of an array because the variable pointer can be
incremented unlike the array name which cannot be incremented because it is a constant pointer.
%he following program increments the variable pointer to access each succeeding element of the
array$
include /stdio.h0
const int M"S 3 ;)
int main &'
( int varPQ 3 (45 455 655*)
int i 2ptr)
12 let us have array address in pointer 21
ptr 3 var)
for & i 3 5) i / M"S) i::'
(
printf&7"ddress of varP8dQ 3 8x9n7 i ptr ')
26
http://www.tutorialspoint.com/cprogramming/c_array_of_pointers.htmhttp://www.tutorialspoint.com/cprogramming/c_passing_pointers_to_functions.htmhttp://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htmhttp://www.tutorialspoint.com/cprogramming/c_array_of_pointers.htmhttp://www.tutorialspoint.com/cprogramming/c_passing_pointers_to_functions.htmhttp://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htm
8/15/2019 C Programming Language Notes for Second Test
27/41
printf&7alue of varP8dQ 3 8d9n7 i 2ptr ')
12 move to the next location 21
ptr::) *
return 5)*
-hen the above code is compiled and executed it produces result something as follows$
"ddress of varP5Q 3 bf@@6b;5
alue of varP5Q 3 45
"ddress of varP4Q 3 bf@@6b;<alue of varP4Q 3 455
"ddress of varP6Q 3 bf@@6b;@
alue of varP6Q 3 655
'e%rementin& a Pointer
%he same considerations apply to decrementing a pointer which decreases its value by the
number of bytes of its data type as shown below$
include /stdio.h0
const int M"S 3 ;)
int main &'
( int varPQ 3 (45 455 655*)
int i 2ptr)
12 let us have array address in pointer 21
ptr 3 OvarPM"SJ4Q)
for & i 3 M"S) i 0 5) iJJ'
(
printf&7"ddress of varP8dQ 3 8x9n7 i ptr ') printf&7alue of varP8dQ 3 8d9n7 i 2ptr ')
12 move to the previous location 21
ptrJJ) *
return 5)
*
27
8/15/2019 C Programming Language Notes for Second Test
28/41
-hen the above code is compiled and executed it produces result something as follows$
"ddress of varP;Q 3 bfedbcd@
alue of varP;Q 3 655
"ddress of varP6Q 3 bfedbcd<
alue of varP6Q 3 455"ddress of varP4Q 3 bfedbcd5
alue of varP4Q 3 45
Array of -ointers
Nefore we understand the concept of arrays of pointers let us consider the following example
which makes use of an array of ; integers$
include /stdio.h0
const int M"S 3 ;)
int main &'
(
int varPQ 3 (45 455 655*) int i)
for &i 3 5) i / M"S) i::'
(
printf&7alue of varP8dQ 3 8d9n7 i varPiQ ')
* return 5)
*
-hen the above code is compiled and executed it produces following result$
alue of varP5Q 3 45
alue of varP4Q 3 455alue of varP6Q 3 655
%here may be a situation when we want to maintain an array which can store pointers to an int or char or any other data type available. ollowing is the declaration of an array of pointers to an
integer$
int 2ptrPM"SQ)
28
8/15/2019 C Programming Language Notes for Second Test
29/41
%his declares ptr as an array of M"S integer pointers. %hus each element in ptr now holds a
pointer to an int value. ollowing example makes use of three integers which will be stored in an
array of pointers as follows$
include /stdio.h0 const int M"S 3 ;)
int main &'
(
int varPQ 3 (45 455 655*)
int i 2ptrPM"SQ)
for & i 3 5) i / M"S) i::'
(
ptrPiQ 3 OvarPiQ) 12 assign the address of integer. 21
* for & i 3 5) i / M"S) i::'
( printf&7alue of varP8dQ 3 8d9n7 i 2ptrPiQ ')
*
return 5)*
-hen the above code is compiled and executed it produces following result$
alue of varP5Q 3 45alue of varP4Q 3 455alue of varP6Q 3 655
!ou can also use an array of pointers to character to store a list of strings as follows$
include /stdio.h0
const int M"S 3
8/15/2019 C Programming Language Notes for Second Test
30/41
int i 3 5)
for & i 3 5) i / M"S) i::'
( printf&7alue of namesP8dQ 3 8s9n7 i namesPiQ ')
* return 5)*
-hen the above code is compiled and executed it produces following result$
alue of namesP5Q 3 Tara "li
alue of namesP4Q 3 +ina "lialue of namesP6Q 3 Buha "li
alue of namesP;Q 3 #ara "li
C programming language allows you to pass a pointer to a function. %o do so simply declare the
function parameter as a pointer type.
ollowing a simple example where we pass an unsigned long pointer to a function and change
the value inside the function which reflects back in the calling function$
include /stdio.h0include /time.h0
void get#econds&unsigned long 2par')
int main &'(
unsigned long sec)
get#econds& Osec ')
12 print the actual value 21
printf&7Bumber of seconds$ 8ld9n7 sec ')
return 5)*
void get#econds&unsigned long 2par'(
12 get the current number of seconds 21
30
8/15/2019 C Programming Language Notes for Second Test
31/41
2par 3 time& BDLL ') return)
*
-hen the above code is compiled and executed it produces following result$
Bumber of seconds $46A
8/15/2019 C Programming Language Notes for Second Test
32/41
-hen the above code is compiled together and executed it produces following result$
"verage value is$ 64
8/15/2019 C Programming Language Notes for Second Test
33/41
Number Reverse:
#include
#include
void main()
{
int num,rem,rev=0;
clrscr();
printf("nEnter an no to !e reversed ");
scanf("d",$num);
while(n>=%)
{
rem = num %0;
rev = rev & %0 ' rem;
num = num %0;
printf("n*eversed +um!er d",rev);
etch();
Program to convert temperature from degree centigrade to
Fahrenheit#include
#include
void main()
{
float celsius,fahrenheit;
clrscr();
printf("nEnter temp in -elsius ");
scanf("f",$celsius);
fahrenheit = (%. & celsius) ' /;
printf("n1emperature in 2ahrenheit f ",fahrenheit);
etch();
33
8/15/2019 C Programming Language Notes for Second Test
34/41
Program : To obtain solution of second order quadratic equation
#include
#include
#include
void main()
{
float a,!,c;
float desc,root%,root;
clrscr();
printf("nEnter the 3alues of a ");
scanf("f",$a);
printf("nEnter the 3alues of ! ");
scanf("f",$!);
printf("nEnter the 3alues of c ");
scanf("f",$c);
desc = s4rt(!&!56&a&c);
root% = (5! ' desc)(.0&a);
root = (5! 5 desc)(.0&a);
printf("n2irst *oot f",root%);
printf("n7econd *oot f",root);
etch();
Fibonacci Series
#include
#include
int main()
{
int first,second,sum,num,counter=0;
clrscr();
printf("Enter the term ");
scanf("d",$num);
printf("nEnter 2irst +um!er ");
scanf("d",$first);
34
8/15/2019 C Programming Language Notes for Second Test
35/41
8/15/2019 C Programming Language Notes for Second Test
36/41
num = num %0;
if(temp == sum)
printf("nd is mstron +um!er",temp);
else
printf("nd is mstron +um!er",temp);
return(0);
Program : Find Smallest Element in Array in Programming
555555555555555555555555555555555555555555555555555555
1itle 2ind out smallest +um!er 2rom rra
smallest 5 t 7tores the smallest num!er 555555555555555555555555555555555555555555555555555555
#include
#include
void main()
{
int a?/0@,i,n,smallest;
printf("n Enter no of elements ");
scanf("d",$n);
& read n elements in an arra &
for(i=0 ; i
8/15/2019 C Programming Language Notes for Second Test
37/41
37
8/15/2019 C Programming Language Notes for Second Test
38/41
Transpose of a matrix
#include
#include
void main()
{
int a?%0@?%0@,m,i,B,temp;
& actual siCe of matriD is m&n
i,B 5 for scannin of arra
temp 5 for interchanin of a?i@?B@ and a?B@?i@ &
printf("n Enter the siCe of matriD ");
scanf("d",$m);
& *eadin elements of matriD &
printf("n Enter the values a");
for(i=0;i
8/15/2019 C Programming Language Notes for Second Test
39/41
for(i=0;i 〈 m;i'')
{
printf("n");
for(B=0;B
8/15/2019 C Programming Language Notes for Second Test
40/41
& Hefore acceptin the Elements -hec if no of
roFs and columns of !oth matrices is e4ual &
if ( m% = m II n% = n )
{
printf("nJrder of tFo matrices is not same "); eDit(0);
555555 1erminate Aroram if Jrders are une4ual
555555 eDit(0) 0 for normal 1ermination
& ccept the Elements in m D n GatriD &
for(i=0;i
8/15/2019 C Programming Language Notes for Second Test
41/41
Output
Enter the num!er of *oFs of Gat% /
Enter the num!er of -olumns of Gat% /
Enter the Element a?0@?0@ %
Enter the Element a?0@?%@
Enter the Element a?0@?@ /
Enter the Element a?%@?0@
Enter the Element a?%@?%@ %
Enter the Element a?%@?@ %
Enter the Element a?@?0@ %
Enter the Element a?@?%@
Enter the Element a?@?@ %
Enter the num!er of *oFs of Gat /
Enter the num!er of -olumns of Gat /
Enter the Element !?0@?0@ %
Enter the Element !?0@?%@
Enter the Element !?0@?@ /
Enter the Element !?%@?0@
Enter the Element !?%@?%@ %
Enter the Element !?%@?@ %
Enter the Element !?@?0@ %
Enter the Element !?@?%@
Enter the Element !?@?@ %
1he ddition of tFo Gatrices is
6 K
6
6