SlideShare a Scribd company logo
1 of 41
Download to read offline
Computing Fundamentals
Dr. Muhammad Yousaf Hamza
Deputy Chief Engineer, PIEAS
Arrays and Pointers
Dr. Yousaf, PIEAS
• A variable declared as an array represents a contiguous
region of memory in which the array elements are stored.
int x[5]; // an array of 5 4-byte ints.
• All arrays begin with an index of 0
• An array identifier is equivalent to a pointer that references
the first element of the array
– int x[5], *ptr;
ptr = &x[0] is equivalent to ptr = x;
• Pointer arithmetic and arrays:
– int x[5];
x[2] is the same as *(x + 2), the compiler
will assume you mean 2 objects beyond
element x.
Arrays and Pointers
0
1
2
3
4
10 2 3
little endian byte ordering
memory layout for array x
Dr. Yousaf, PIEAS
The Relationship b/w Pointers and Arrays
• Pointers have close relationship with arrays and strings
– Array name is itself a pointer. It means the name of the
array is the address of the first element of the array.
– Pointers can do array subscripting operations
• Declare an array b[ 5 ] and a pointer Ptrb
• b[5] = {4, 7, 9, 10, 56};
• int *ptrb
• Array name b is also the address of this
array.
• Ptrb = b; // Most important to note that we
have not used & with b. WHY?
• Because actually b itself is the address of
first element of the array b[5].
i.e. Ptrb = &b[ 0 ]
Explicitly assigns bPtr to address of first element of b
Dr. Yousaf, PIEAS
• int b[5] = {4, 7, 9, 10, 56};
• int *ptrb, *ptr2
• ptrb = b;
• ptr2 = &b[ 0 ]
// Are ptrb and ptr2 equal? Yes.
printf(“ptrb = %d”, ptrb);
printf(“ptr2 = %d”, ptr2);
They will have the same addresses
Dr. Yousaf, PIEAS
The Relationship b/w Pointers and Arrays
– Element b[ 3 ]
• Can be accessed by *( ptrb + 3 )
–Where 3 is the offset, called pointer/offset
notation
• Can be accessed by ptrb[ 3 ]
–Called pointer/subscript notation
–ptrb[ 3 ] same as b[ 3 ]
• Can be accessed by performing pointer
arithmetic on the array itself
*( b + 3 )
Dr. Yousaf, PIEAS
The Relationship b/w Pointers and Arrays
Array as a Pointer
• Array: sequence of identical objects in memory
• int a[10]; means space for ten integers
 By itself, a is the address of the first integer
 *a and a[0] mean the same thing
 The address of a is not stored in memory: the compiler
inserts code to compute it when it appears
Dr. Yousaf, PIEAS
Pointer Arithmetic
If we define an array we can use pointers to access it
int i[7]; /* An array of 7 ints */
int *j; /* A pointer to an int*/
j= i; /* j points at the start of i*/
*j= 3; /* Same as i[0]= 3 */
j= &i[0]; /* Same as j= i */
j= j+1; /* Move j to point at i[1]*/
Dr. Yousaf, PIEAS
Pointer Expressions and Pointer
Arithmetic
• Arithmetic operations can be performed on pointers
– Increment/decrement pointer (++ or --)
– Add an integer to a pointer( + or += , - or -=)
– Pointers may be subtracted from each other
– Operations meaningless unless performed on an
array
Dr. Yousaf, PIEAS
Pointer Expressions and Pointer Arithmetic
5 element int array on machine with 4 byte ints
– int v[5];
– int *vptr;
– vptr = v;
– vPtr points to first element v[ 0 ]
• at location 3000 (vPtr = 3000)
– vPtr += 2; sets vPtr to 3008
• vPtr points to v[ 2 ] (incremented by 2), but the
machine has 4 bytes ints, so it points to address
3008
pointer variable vPtr
v[0] v[1] v[2] v[4]v[3]
3000 3004 3008 3012 3016
location
Dr. Yousaf, PIEAS
Pointer Expressions and Pointer Arithmetic
• Subtracting pointers
– Returns number of elements from one to the other.
5 element int array on machine with 4 byte ints
int v[5];
int *vptr1, *vptr2;
vptr1 = v; // actually vptr1 = v[0];
vptr2 = &v[2];
vPtr2 – vPtr1; //would produce 2, i.e if two pointers are
pointing to the same variable, the difference between their
values will be equal to the number elements between them.
• Pointer comparison ( <, == , > )
– See which pointer points to the higher numbered array
element
– e.g if (vptr2 > vptr 1)
rest of the code here
Dr. Yousaf, PIEAS
#include<stdio.h>
int main()
{
int x[5] = {11, 21, 31, 41, 51};
int *p1, *p2;
p1 = x;
p2= &x[2];
printf("n p1 = %d", p1);
printf("n p2 = %d", p2);
printf("n diff = %d", p2-p1);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
// Printing the elements of an array without using pointer
#include<stdio.h>
int main()
{
int i, x[5] ={10, 20, 30, 40, 50};
for (i = 0; i<5;i++)
printf("n x = %d", x[i]);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
// Printing the elements of an array using pointer
#include<stdio.h>
int main()
{
int i, x[5] ={10, 20, 30, 40, 50}, *ptrx;
ptrx = x; // important to observe that there is no & sign with x.
// x itself is an address of the first element stored in array x
for (i = 0; i<5;i++)
{
printf("n x = %d",*ptrx);
ptrx++; // see the increment in ptrx and its use
}
getchar();
return 0;
} Dr. Yousaf, PIEAS
/* C program to determine and print the largest number in an
array (no use of pointers) */
#include<stdio.h>
int main()
{
int i, max, x[5] ={23, 78, 99, 2, 37};
max = x[0];
for (i = 0; i<5;i++)
{
if (x[i] > max)
max = x[i];
}
printf("n max = %d",max);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
/* C program to determine the largest number in an array, and
then print it using a pointer */
#include<stdio.h>
int main()
{
int i, max, x[5] ={23, 78, 99, 2, 37}, *ptrmax;
max = x[0];
for (i = 0; i<5;i++)
{
if (x[i] > max)
max = x[i];
}
ptrmax = &max;
printf("n max = %d", *ptrmax);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
Solve a problem
Dr. Yousaf, PIEAS
Try to write a program that calculates average of
three numbers, you have done this program before,
here try to do it using pointers, i.e. use pointers only.
Solve a problem
Dr. Yousaf, PIEAS
Try to write a program that swaps the values of two
integer variables, you have to do it using pointers
i.e. any modifications in the values of integer
variables should be done using pointers.
Pass By Reference
Dr. Yousaf, PIEAS
Pass by Value/ Pass by Reference
• Normally when we send a variable to a function we
make a COPY of the variable.
• This is called pass by value. A value is passed and
this copy of the variable arrives at the function. The
original doesn’t change.
• The value of a variable can also be pass by reference
• In this case, any change in the value of this variable
made within a function changes the original value.
Dr. Yousaf, PIEAS
What's the point of pointers?
• When we use & to pass a pointer to a variable
into a function we CAN change the value of the
variable within the function.
• This is called pass by reference.
Dr. Yousaf, PIEAS
Calling Functions by Reference
Call by reference with pointer arguments
–Pass address of argument using & operator
–Allows you to change actual location in
memory
Dr. Yousaf, PIEAS
// Passing arguments by reference
#include <stdio.h>
void myfunc(int *a, int *b, int *c);
int main()
{
int x = 2, y = 4, z = 6;
printf("n Before calling
by_reference(), x=%d, y=%d,z= %d.",
x, y, z); //x = 2, y = 4, z = 6.
my_func(&x, &y, &z);
printf("nn After calling
by_reference(), x=%d, y=%d, z=%d.",
x, y, z); //x = 0, y = 0, z = 0.
getchar(); return(0);
}
void myfunc(int *a, int *b,
int *c)
{
*a = 0;
*b = 0;
*c = 0;
printf("nn Within function
by_ref(), x= %d, y = %d, z =
%d.", *a, *b, *c);
//x = 0, y = 0, z = 0.
}
Dr. Yousaf, PIEAS
Calling Functions by Reference
Use of * operator
// Passing arguments by reference
#include <stdio.h>
void my_double(int *number )
int main()
{
int number;
pintf(“Enter an integer number);
scanf(“%d”, &number);
my_double(&number) ;
printf(“%d”, number);
getchar();
}
void my_double( int *number )
{
*number = 2 * ( *number );
}
//*number used as alias/nickname for variable inside function
Dr. Yousaf, PIEAS
Changing an argument within a function
void square_num (int *);
int main()
{
int p= 5;
square_num (&p);
printf ("P is now %dn",p);
return 0;
}
void square_num (int *num)
{
(*num)= (*num) * (*num);
}
Prototype a function
taking a POINTER
Pass the address of p to square function
Now the function has changed p to 25
Remember * gives
the value the pointer
points at
Dr. Yousaf, PIEAS
Passing Arrays to Functions
Dr. Yousaf, PIEAS
Calling Functions by Reference
Arrays are not passed with & because
the array name is already a pointer
(we have already studied)
Dr. Yousaf, PIEAS
/*Pass by reference (Page 365)
//Pass by reference Example Page
366
If names of variables in main and
the calling function are similar */
#include<stdio.h>
void add_num_inArray(int x[]);
int main()
{
int i, x[5] ={23, 78, 99, 2, 37};
add_num_inArray(x);
for (i = 0; i<5;i++)
{
printf("n %d",x[i]);
}
getchar(); return 0;
}
void add_num_inArray(int
x[])
{
int i;
for (i = 0; i<5; i++)
{
x[i] = x[i] + 5;
}
}
Pass by Reference
Dr. Yousaf, PIEAS
/* Pass by reference
If names of variables in main and the
calling function are different */
#include<stdio.h>
void add_num_inArray(int k[]);
int main()
{
int i, x[5] ={23, 78, 99, 2, 37};
add_num_inArray(x);
for (i = 0; i<5;i++)
{
printf("n %d",x[i]);
}
getchar(); return 0;
}
void add_num_inArray(int k[])
{
int i;
for (i = 0; i<5; i++)
{
k[i] = k[i] + 5;
}
}
Pass by Reference
Dr. Yousaf, PIEAS
/* Define an array in main. Pass that
array to a function that should
determine the maximum number.
// Return the maximum number
from that function to main and then
print it in main.
No use of pointers */
#include<stdio.h>
int find_max(int k[]);
int main()
{
int max, x[5] ={23, 78, 99, 2, 37};
max = find_max(x);
printf("n max = %d",max);
getchar();
return 0; }
int find_max(int k[])
{
int i, max = k[0];
for (i = 0; i<5;i++)
{
if (k[i] > max)
max = k[i];
}
return max;
}
Dr. Yousaf, PIEAS
/* Define an array in main. Pass that
array to a function that should
determine the maximum number
// Return the address of that max
number (using pointer) from the
function to main and then print it in
main. */
#include<stdio.h>
int* find_max(int k[]);
int main()
{
int *ptrmax, x[5] ={23, 78, 99, 2, 37};
ptrmax = find_max(x);
printf("n max = %d",*ptrmax);
getchar();
return 0; }
int* find_max(int k[])
{
int *ptrmax;
int i;
int max = k[0];
for (i = 0; i<5;i++)
{
if (k[i] > max)
max = k[i];
}
ptrmax = &max;
return ptrmax;
}
Dr. Yousaf, PIEAS
/* Define an array in main. Pass that array
to a function that should add an integer to
each element of that array. Return the
address of the new array (using pointer)
from the function to main and then print it
in main. */
#include<stdio.h>
int* add_num_inArray(int k[]);
int main()
{
int i, *ptr_added_array, x[5] ={23, 78, 99, 2,
37};
ptr_added_array = add_num_inArray(x);
for (i = 0; i<5;i++)
{
printf("n %d",*ptr_added_array);
ptr_added_array++;
}
getchar();
return 0; }
int* add_num_inArray(int
k[])
{
int i;
int new_array[5];
for (i = 0; i<5; i++)
{
new_array[i] = k[i] + 5;
}
return new_array;
}
Dr. Yousaf, PIEAS
/* Define an array in main. Pass that array to a
function that should add an integer number to
each of the element of that array.
Also correspond the added_array of main
function and new_array of main function in the
calling statement of the main function.
// In fact, here array names are being used as
pointers. */
#include<stdio.h>
void add_num_inArray(int k[], int new_array[]);
int main()
{
int i, x[5] ={23, 78, 99, 2, 37};
int added_array[5];
add_num_inArray(x, added_array);
for (i = 0; i<5;i++)
{
printf("n %d", added_array[i]);
}
getchar();
return 0; }
void add_num_inArray(int k[],
int new_array[])
{
int i;
for (i = 0; i<5; i++)
{
new_array[i] = k[i] + 5;
}
}
Dr. Yousaf, PIEAS
We can pass 2D arrays to and from
functions
• Example prototype for function:
void process_array (int X[3][6]);
void process_array (int array[3][6])
{
/* Do stuff to the array */
}
int thearray[3][6];
process_array(thearray);
Call the array with this (in main or other function)
And write the function with
Dr. Yousaf, PIEAS
// Add two matrices in main and print them
// No use of pointers
#include<stdio.h>
int main()
{
int mat1[2][2]={ {1,2},{3,4} }, mat2[2][2] = { {5,6},{7,8} }, result_mat[2][2];
int i,j;
for (i = 0; i<2;i++)
for (j = 0; j<2; j++)
result_mat[i][j] = mat1[i][j] + mat2[i][j];
for (i = 0; i<2;i++)
{
printf("n");
for (j = 0; j<2; j++)
printf("%d t", result_mat[i][j]);
}
getchar();
return 0; }
Dr. Yousaf, PIEAS
/*Declare two matrices in main. Pass them
to a function. Add these in a function.
Print the results in main
Use array name as pointers */
#include<stdio.h>
void add_mat(int x[2][2], int y[2][2], int
z[2][2]);
int main()
{
int mat1[2][2]={ {1,2},{3,4} }, mat2[2][2] = {
{5,6},{7,8} }, res_mat[2][2];
int i,j;
add_mat(mat1, mat2, res_mat);
for (i = 0; i<2;i++)
{
printf("n");
for (j = 0; j<2; j++)
printf("%d t", res_mat[i][j]);
}
getchar(); return 0; }
void add_mat(int x[2][2],
int y[2][2],int z[2][2])
{
int i, j;
for (i = 0; i<2;i++)
for (j = 0; j<2; j++)
z[i][j] = x[i][j] + y[i][j];
}
Dr. Yousaf, PIEAS
• We can also have pointer to pointer:
• We can even have pointers to functions:
• If you want to use them then feel free.
Pointer to Pointer
int number= 5;
int *ptrtonumber;
int **ptrtoptrtonumber;
ptrtonumber= &number;
ptrtoptrtonumber= &ptrtonumber;
*(*ptrtoptrtonumber)= 6;
5
ptrtonumber
ptrtoptrtonumber
number
Dr. Yousaf, PIEAS
Some Jargons
Dr. Yousaf, PIEAS
• Loop
– Group of instructions computer executes repeatedly
while some condition remains true
• Counter-controlled repetition
– Definite repetition: know how many times loop will
execute for (i = 0; i < 12; i++)
– Control variable (e.g i)used to count repetitions
• Sentinel-controlled repetition
– Indefinite repetition
– Used when number of repetitions not known
– Sentinel value indicates "end of data"
Dr. Yousaf, PIEAS
Essentials of Counter-Controlled
Repetition
• Counter-controlled repetition requires
– The name of a control variable (or loop counter)
– The initial value of the control variable
– A condition that tests for the final value of the
control variable (i.e., whether looping should
continue)
– An increment (or decrement) by which the control
variable is modified each time through the loop
Dr. Yousaf, PIEAS
Essentials of Counter-Controlled
Repetition• Example:
int counter = 1; // initialization
while ( counter <= 10 ) { // repetition
condition
printf( "%dn", counter );
++counter; // increment
}
– The statement
int counter = 1;
• Names counter
• Declares it to be an integer
• Reserves space for it in memory
• Sets it to an initial value of 1
Dr. Yousaf, PIEAS

More Related Content

What's hot

Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm KristinaBorooah
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersKimikazu Kato
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Appili Vamsi Krishna
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to ArraysTareq Hasan
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
 
Arrays in python
Arrays in pythonArrays in python
Arrays in pythonmoazamali28
 
Arrays searching-sorting
Arrays searching-sortingArrays searching-sorting
Arrays searching-sortingAjharul Abedeen
 

What's hot (20)

Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPy
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
 
Composing method
Composing methodComposing method
Composing method
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning ProgrammersIntroduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning Programmers
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
 
Session 4
Session 4Session 4
Session 4
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
arrays of structures
arrays of structuresarrays of structures
arrays of structures
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Numpy
NumpyNumpy
Numpy
 
Arrays searching-sorting
Arrays searching-sortingArrays searching-sorting
Arrays searching-sorting
 

Similar to C Language Lecture 20

Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxRamakrishna Reddy Bijjam
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersANUSUYA S
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
 
Engineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptxEngineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptxhappycocoman
 
Week06
Week06Week06
Week06hccit
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxarjurakibulhasanrrr7
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxajajkhan16
 

Similar to C Language Lecture 20 (20)

C Language Lecture 19
C Language Lecture 19C Language Lecture 19
C Language Lecture 19
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
 
Pointers [compatibility mode]
Pointers [compatibility mode]Pointers [compatibility mode]
Pointers [compatibility mode]
 
C Language Lecture 10
C Language Lecture 10C Language Lecture 10
C Language Lecture 10
 
SlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdfSlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdf
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
Pointers
PointersPointers
Pointers
 
C Language Lecture 11
C Language Lecture  11C Language Lecture  11
C Language Lecture 11
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Engineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptxEngineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptx
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
C Language Lecture 15
C Language Lecture 15C Language Lecture 15
C Language Lecture 15
 
Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
 
Arrays
ArraysArrays
Arrays
 
Week06
Week06Week06
Week06
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptx
 
Cs341
Cs341Cs341
Cs341
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 

More from Shahzaib Ajmal

More from Shahzaib Ajmal (17)

C Language Lecture 22
C Language Lecture 22C Language Lecture 22
C Language Lecture 22
 
C Language Lecture 21
C Language Lecture 21C Language Lecture 21
C Language Lecture 21
 
C Language Lecture 18
C Language Lecture 18C Language Lecture 18
C Language Lecture 18
 
C Language Lecture 17
C Language Lecture 17C Language Lecture 17
C Language Lecture 17
 
C Language Lecture 16
C Language Lecture 16C Language Lecture 16
C Language Lecture 16
 
C Language Lecture 14
C Language Lecture 14C Language Lecture 14
C Language Lecture 14
 
C Language Lecture 13
C Language Lecture 13C Language Lecture 13
C Language Lecture 13
 
C Language Lecture 12
C Language Lecture 12C Language Lecture 12
C Language Lecture 12
 
C Language Lecture 9
C Language Lecture 9C Language Lecture 9
C Language Lecture 9
 
C Language Lecture 8
C Language Lecture 8C Language Lecture 8
C Language Lecture 8
 
C Language Lecture 7
C Language Lecture 7C Language Lecture 7
C Language Lecture 7
 
C Language Lecture 6
C Language Lecture 6C Language Lecture 6
C Language Lecture 6
 
C Language Lecture 5
C Language Lecture  5C Language Lecture  5
C Language Lecture 5
 
C Language Lecture 4
C Language Lecture  4C Language Lecture  4
C Language Lecture 4
 
C Language Lecture 3
C Language Lecture  3C Language Lecture  3
C Language Lecture 3
 
C Language Lecture 2
C Language Lecture  2C Language Lecture  2
C Language Lecture 2
 
C Language Lecture 1
C Language Lecture  1C Language Lecture  1
C Language Lecture 1
 

Recently uploaded

Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 

Recently uploaded (20)

Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 

C Language Lecture 20

  • 1. Computing Fundamentals Dr. Muhammad Yousaf Hamza Deputy Chief Engineer, PIEAS
  • 2. Arrays and Pointers Dr. Yousaf, PIEAS
  • 3. • A variable declared as an array represents a contiguous region of memory in which the array elements are stored. int x[5]; // an array of 5 4-byte ints. • All arrays begin with an index of 0 • An array identifier is equivalent to a pointer that references the first element of the array – int x[5], *ptr; ptr = &x[0] is equivalent to ptr = x; • Pointer arithmetic and arrays: – int x[5]; x[2] is the same as *(x + 2), the compiler will assume you mean 2 objects beyond element x. Arrays and Pointers 0 1 2 3 4 10 2 3 little endian byte ordering memory layout for array x Dr. Yousaf, PIEAS
  • 4. The Relationship b/w Pointers and Arrays • Pointers have close relationship with arrays and strings – Array name is itself a pointer. It means the name of the array is the address of the first element of the array. – Pointers can do array subscripting operations • Declare an array b[ 5 ] and a pointer Ptrb • b[5] = {4, 7, 9, 10, 56}; • int *ptrb • Array name b is also the address of this array. • Ptrb = b; // Most important to note that we have not used & with b. WHY? • Because actually b itself is the address of first element of the array b[5]. i.e. Ptrb = &b[ 0 ] Explicitly assigns bPtr to address of first element of b Dr. Yousaf, PIEAS
  • 5. • int b[5] = {4, 7, 9, 10, 56}; • int *ptrb, *ptr2 • ptrb = b; • ptr2 = &b[ 0 ] // Are ptrb and ptr2 equal? Yes. printf(“ptrb = %d”, ptrb); printf(“ptr2 = %d”, ptr2); They will have the same addresses Dr. Yousaf, PIEAS The Relationship b/w Pointers and Arrays
  • 6. – Element b[ 3 ] • Can be accessed by *( ptrb + 3 ) –Where 3 is the offset, called pointer/offset notation • Can be accessed by ptrb[ 3 ] –Called pointer/subscript notation –ptrb[ 3 ] same as b[ 3 ] • Can be accessed by performing pointer arithmetic on the array itself *( b + 3 ) Dr. Yousaf, PIEAS The Relationship b/w Pointers and Arrays
  • 7. Array as a Pointer • Array: sequence of identical objects in memory • int a[10]; means space for ten integers  By itself, a is the address of the first integer  *a and a[0] mean the same thing  The address of a is not stored in memory: the compiler inserts code to compute it when it appears Dr. Yousaf, PIEAS
  • 8. Pointer Arithmetic If we define an array we can use pointers to access it int i[7]; /* An array of 7 ints */ int *j; /* A pointer to an int*/ j= i; /* j points at the start of i*/ *j= 3; /* Same as i[0]= 3 */ j= &i[0]; /* Same as j= i */ j= j+1; /* Move j to point at i[1]*/ Dr. Yousaf, PIEAS
  • 9. Pointer Expressions and Pointer Arithmetic • Arithmetic operations can be performed on pointers – Increment/decrement pointer (++ or --) – Add an integer to a pointer( + or += , - or -=) – Pointers may be subtracted from each other – Operations meaningless unless performed on an array Dr. Yousaf, PIEAS
  • 10. Pointer Expressions and Pointer Arithmetic 5 element int array on machine with 4 byte ints – int v[5]; – int *vptr; – vptr = v; – vPtr points to first element v[ 0 ] • at location 3000 (vPtr = 3000) – vPtr += 2; sets vPtr to 3008 • vPtr points to v[ 2 ] (incremented by 2), but the machine has 4 bytes ints, so it points to address 3008 pointer variable vPtr v[0] v[1] v[2] v[4]v[3] 3000 3004 3008 3012 3016 location Dr. Yousaf, PIEAS
  • 11. Pointer Expressions and Pointer Arithmetic • Subtracting pointers – Returns number of elements from one to the other. 5 element int array on machine with 4 byte ints int v[5]; int *vptr1, *vptr2; vptr1 = v; // actually vptr1 = v[0]; vptr2 = &v[2]; vPtr2 – vPtr1; //would produce 2, i.e if two pointers are pointing to the same variable, the difference between their values will be equal to the number elements between them. • Pointer comparison ( <, == , > ) – See which pointer points to the higher numbered array element – e.g if (vptr2 > vptr 1) rest of the code here Dr. Yousaf, PIEAS
  • 12. #include<stdio.h> int main() { int x[5] = {11, 21, 31, 41, 51}; int *p1, *p2; p1 = x; p2= &x[2]; printf("n p1 = %d", p1); printf("n p2 = %d", p2); printf("n diff = %d", p2-p1); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 13. // Printing the elements of an array without using pointer #include<stdio.h> int main() { int i, x[5] ={10, 20, 30, 40, 50}; for (i = 0; i<5;i++) printf("n x = %d", x[i]); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 14. // Printing the elements of an array using pointer #include<stdio.h> int main() { int i, x[5] ={10, 20, 30, 40, 50}, *ptrx; ptrx = x; // important to observe that there is no & sign with x. // x itself is an address of the first element stored in array x for (i = 0; i<5;i++) { printf("n x = %d",*ptrx); ptrx++; // see the increment in ptrx and its use } getchar(); return 0; } Dr. Yousaf, PIEAS
  • 15. /* C program to determine and print the largest number in an array (no use of pointers) */ #include<stdio.h> int main() { int i, max, x[5] ={23, 78, 99, 2, 37}; max = x[0]; for (i = 0; i<5;i++) { if (x[i] > max) max = x[i]; } printf("n max = %d",max); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 16. /* C program to determine the largest number in an array, and then print it using a pointer */ #include<stdio.h> int main() { int i, max, x[5] ={23, 78, 99, 2, 37}, *ptrmax; max = x[0]; for (i = 0; i<5;i++) { if (x[i] > max) max = x[i]; } ptrmax = &max; printf("n max = %d", *ptrmax); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 17. Solve a problem Dr. Yousaf, PIEAS Try to write a program that calculates average of three numbers, you have done this program before, here try to do it using pointers, i.e. use pointers only.
  • 18. Solve a problem Dr. Yousaf, PIEAS Try to write a program that swaps the values of two integer variables, you have to do it using pointers i.e. any modifications in the values of integer variables should be done using pointers.
  • 19. Pass By Reference Dr. Yousaf, PIEAS
  • 20. Pass by Value/ Pass by Reference • Normally when we send a variable to a function we make a COPY of the variable. • This is called pass by value. A value is passed and this copy of the variable arrives at the function. The original doesn’t change. • The value of a variable can also be pass by reference • In this case, any change in the value of this variable made within a function changes the original value. Dr. Yousaf, PIEAS
  • 21. What's the point of pointers? • When we use & to pass a pointer to a variable into a function we CAN change the value of the variable within the function. • This is called pass by reference. Dr. Yousaf, PIEAS
  • 22. Calling Functions by Reference Call by reference with pointer arguments –Pass address of argument using & operator –Allows you to change actual location in memory Dr. Yousaf, PIEAS
  • 23. // Passing arguments by reference #include <stdio.h> void myfunc(int *a, int *b, int *c); int main() { int x = 2, y = 4, z = 6; printf("n Before calling by_reference(), x=%d, y=%d,z= %d.", x, y, z); //x = 2, y = 4, z = 6. my_func(&x, &y, &z); printf("nn After calling by_reference(), x=%d, y=%d, z=%d.", x, y, z); //x = 0, y = 0, z = 0. getchar(); return(0); } void myfunc(int *a, int *b, int *c) { *a = 0; *b = 0; *c = 0; printf("nn Within function by_ref(), x= %d, y = %d, z = %d.", *a, *b, *c); //x = 0, y = 0, z = 0. } Dr. Yousaf, PIEAS
  • 24. Calling Functions by Reference Use of * operator // Passing arguments by reference #include <stdio.h> void my_double(int *number ) int main() { int number; pintf(“Enter an integer number); scanf(“%d”, &number); my_double(&number) ; printf(“%d”, number); getchar(); } void my_double( int *number ) { *number = 2 * ( *number ); } //*number used as alias/nickname for variable inside function Dr. Yousaf, PIEAS
  • 25. Changing an argument within a function void square_num (int *); int main() { int p= 5; square_num (&p); printf ("P is now %dn",p); return 0; } void square_num (int *num) { (*num)= (*num) * (*num); } Prototype a function taking a POINTER Pass the address of p to square function Now the function has changed p to 25 Remember * gives the value the pointer points at Dr. Yousaf, PIEAS
  • 26. Passing Arrays to Functions Dr. Yousaf, PIEAS
  • 27. Calling Functions by Reference Arrays are not passed with & because the array name is already a pointer (we have already studied) Dr. Yousaf, PIEAS
  • 28. /*Pass by reference (Page 365) //Pass by reference Example Page 366 If names of variables in main and the calling function are similar */ #include<stdio.h> void add_num_inArray(int x[]); int main() { int i, x[5] ={23, 78, 99, 2, 37}; add_num_inArray(x); for (i = 0; i<5;i++) { printf("n %d",x[i]); } getchar(); return 0; } void add_num_inArray(int x[]) { int i; for (i = 0; i<5; i++) { x[i] = x[i] + 5; } } Pass by Reference Dr. Yousaf, PIEAS
  • 29. /* Pass by reference If names of variables in main and the calling function are different */ #include<stdio.h> void add_num_inArray(int k[]); int main() { int i, x[5] ={23, 78, 99, 2, 37}; add_num_inArray(x); for (i = 0; i<5;i++) { printf("n %d",x[i]); } getchar(); return 0; } void add_num_inArray(int k[]) { int i; for (i = 0; i<5; i++) { k[i] = k[i] + 5; } } Pass by Reference Dr. Yousaf, PIEAS
  • 30. /* Define an array in main. Pass that array to a function that should determine the maximum number. // Return the maximum number from that function to main and then print it in main. No use of pointers */ #include<stdio.h> int find_max(int k[]); int main() { int max, x[5] ={23, 78, 99, 2, 37}; max = find_max(x); printf("n max = %d",max); getchar(); return 0; } int find_max(int k[]) { int i, max = k[0]; for (i = 0; i<5;i++) { if (k[i] > max) max = k[i]; } return max; } Dr. Yousaf, PIEAS
  • 31. /* Define an array in main. Pass that array to a function that should determine the maximum number // Return the address of that max number (using pointer) from the function to main and then print it in main. */ #include<stdio.h> int* find_max(int k[]); int main() { int *ptrmax, x[5] ={23, 78, 99, 2, 37}; ptrmax = find_max(x); printf("n max = %d",*ptrmax); getchar(); return 0; } int* find_max(int k[]) { int *ptrmax; int i; int max = k[0]; for (i = 0; i<5;i++) { if (k[i] > max) max = k[i]; } ptrmax = &max; return ptrmax; } Dr. Yousaf, PIEAS
  • 32. /* Define an array in main. Pass that array to a function that should add an integer to each element of that array. Return the address of the new array (using pointer) from the function to main and then print it in main. */ #include<stdio.h> int* add_num_inArray(int k[]); int main() { int i, *ptr_added_array, x[5] ={23, 78, 99, 2, 37}; ptr_added_array = add_num_inArray(x); for (i = 0; i<5;i++) { printf("n %d",*ptr_added_array); ptr_added_array++; } getchar(); return 0; } int* add_num_inArray(int k[]) { int i; int new_array[5]; for (i = 0; i<5; i++) { new_array[i] = k[i] + 5; } return new_array; } Dr. Yousaf, PIEAS
  • 33. /* Define an array in main. Pass that array to a function that should add an integer number to each of the element of that array. Also correspond the added_array of main function and new_array of main function in the calling statement of the main function. // In fact, here array names are being used as pointers. */ #include<stdio.h> void add_num_inArray(int k[], int new_array[]); int main() { int i, x[5] ={23, 78, 99, 2, 37}; int added_array[5]; add_num_inArray(x, added_array); for (i = 0; i<5;i++) { printf("n %d", added_array[i]); } getchar(); return 0; } void add_num_inArray(int k[], int new_array[]) { int i; for (i = 0; i<5; i++) { new_array[i] = k[i] + 5; } } Dr. Yousaf, PIEAS
  • 34. We can pass 2D arrays to and from functions • Example prototype for function: void process_array (int X[3][6]); void process_array (int array[3][6]) { /* Do stuff to the array */ } int thearray[3][6]; process_array(thearray); Call the array with this (in main or other function) And write the function with Dr. Yousaf, PIEAS
  • 35. // Add two matrices in main and print them // No use of pointers #include<stdio.h> int main() { int mat1[2][2]={ {1,2},{3,4} }, mat2[2][2] = { {5,6},{7,8} }, result_mat[2][2]; int i,j; for (i = 0; i<2;i++) for (j = 0; j<2; j++) result_mat[i][j] = mat1[i][j] + mat2[i][j]; for (i = 0; i<2;i++) { printf("n"); for (j = 0; j<2; j++) printf("%d t", result_mat[i][j]); } getchar(); return 0; } Dr. Yousaf, PIEAS
  • 36. /*Declare two matrices in main. Pass them to a function. Add these in a function. Print the results in main Use array name as pointers */ #include<stdio.h> void add_mat(int x[2][2], int y[2][2], int z[2][2]); int main() { int mat1[2][2]={ {1,2},{3,4} }, mat2[2][2] = { {5,6},{7,8} }, res_mat[2][2]; int i,j; add_mat(mat1, mat2, res_mat); for (i = 0; i<2;i++) { printf("n"); for (j = 0; j<2; j++) printf("%d t", res_mat[i][j]); } getchar(); return 0; } void add_mat(int x[2][2], int y[2][2],int z[2][2]) { int i, j; for (i = 0; i<2;i++) for (j = 0; j<2; j++) z[i][j] = x[i][j] + y[i][j]; } Dr. Yousaf, PIEAS
  • 37. • We can also have pointer to pointer: • We can even have pointers to functions: • If you want to use them then feel free. Pointer to Pointer int number= 5; int *ptrtonumber; int **ptrtoptrtonumber; ptrtonumber= &number; ptrtoptrtonumber= &ptrtonumber; *(*ptrtoptrtonumber)= 6; 5 ptrtonumber ptrtoptrtonumber number Dr. Yousaf, PIEAS
  • 39. • Loop – Group of instructions computer executes repeatedly while some condition remains true • Counter-controlled repetition – Definite repetition: know how many times loop will execute for (i = 0; i < 12; i++) – Control variable (e.g i)used to count repetitions • Sentinel-controlled repetition – Indefinite repetition – Used when number of repetitions not known – Sentinel value indicates "end of data" Dr. Yousaf, PIEAS
  • 40. Essentials of Counter-Controlled Repetition • Counter-controlled repetition requires – The name of a control variable (or loop counter) – The initial value of the control variable – A condition that tests for the final value of the control variable (i.e., whether looping should continue) – An increment (or decrement) by which the control variable is modified each time through the loop Dr. Yousaf, PIEAS
  • 41. Essentials of Counter-Controlled Repetition• Example: int counter = 1; // initialization while ( counter <= 10 ) { // repetition condition printf( "%dn", counter ); ++counter; // increment } – The statement int counter = 1; • Names counter • Declares it to be an integer • Reserves space for it in memory • Sets it to an initial value of 1 Dr. Yousaf, PIEAS