Post on 06-Jan-2017
transcript
CONTROL STATEMENTS, ARRAY, POINTER, STRUCTURES
UNIT- II
Fundamental of Computer programming -206
By- Er. Indrajeet Sinha , +919509010997
UNIT-II
2.1- Control Statements2.2- Switch statement2.3- Loop Control Statement2.4- Array in C2.5- Strings 2.6- Pointers, Address Arithmetic2.7- Pointers to represent array2.8- Command line arguments2.9- Structures, typedef
2
2.1 - CONTROL STATEMENTS IN C
Lecture no.- 13, UNIT- II
By- Er. Indrajeet Sinha , +919509010997
2.1.1- INTRODUCTION
A control statement is a statement that determines whether other statements will be executed.
An if statement decides whether to execute another statement, or decides which of two statements to execute.
A loop decides how many times to execute another statement.
4
By- Er. Indrajeet Sinha , +919509010997
C KEYWORDS
auto double int structbreak else long switchcase enum register typedefchar extern return unionconst float short unsignedcontinue for signed voiddefault goto sizeof volatiledo if static while
The words in bold print are used in control statements. They change the sequential execution of the assignment statements in a function block
By- Er. Indrajeet Sinha , +919509010997
C CONTROL STATEMENT
If Statement If / else statement For loop Do loop Do While Loop
Definition:-
Control statements enable us to specify the flow of program control; ie, the order in which the instructions in a program must be executed. They make it possible to make decisions, to perform tasks repeatedly or to jump from one section of code to another.
By- Er. Indrajeet Sinha , +919509010997
2.1.2 - IF SELECTION STRUCTURE
Selection structure Choose among alternative courses of action Pseudocode example:
If student’s grade is greater than or equal to 60Print “Passed”
If the condition is true Print statement executed, program continues to next
statement If the condition is false
Print statement ignored, program continues Indenting makes programs easier to read
By- Er. Indrajeet Sinha , +919509010997
IF SELECTION STRUCTURE Flowchart of pseudocode statement
A decision can be made on any expression.
zero - false
nonzero - true
Example:
3 - 4 is true
true
false
grade >= 60
print “Passed”
By- Er. Indrajeet Sinha , +919509010997
2.1.2- “IF” – “ELSE” WITH A BLOCK OF STATEMENTS
if (aValue <= 10) { printf("Answer is %8.2f\n", aValue); countB++; } // End ifelse { printf("Error occurred\n"); countC++; } // End else
By- Er. Indrajeet Sinha , +919509010997
2.1.3 IMPORTANCE OF BRACES ( { } )
Curly braces (also referred to as just "braces" or as "curly brackets") are a major part of the C programming language.
The main uses of curly braces in: Functions
void myfunction(datatype argument) {
statements(s)}
Loops Conditional statements
By- Er. Indrajeet Sinha , +919509010997
2.1.4 - NESTED “IF” STATEMENT
if (aValue == 1) countA++;else if (aValue == 10) countB++;else if (aValue == 100) countC++;else countD++;
By- Er. Indrajeet Sinha , +919509010997
EXAMPLE IF- ELSE
12
// Program to display a number if user enters negative number// If user enters positive number, that number won't be displayed#include <stdio.h>int main(){ int number; printf("Enter an integer: "); scanf("%d", &number); // Test expression is true if number is less than 0 if (number < 0) { printf("You entered %d.\n", number); } printf("The if statement is easy."); return 0;}Output 1Enter an integer: -2You entered -2.
SWITCH STATEMENT
Lecture no.- 14, UNIT- II
By- Er. Indrajeet Sinha , +919509010997
2.1.5- SWITCH STATEMENT
14
Definition:- A switch statement is a type of selection
control mechanism used to allow the value of a variable or expression to change the control flow of program execution via a multiway branch.
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
Switch case statements mostly used when we have number of options (or choices) and we may need to perform a different task for each choice.
By- Er. Indrajeet Sinha , +919509010997
SYNTAX OF SWITCH...CASE
15
switch (n) { case constant1:
// code to be executed if n is equal to constant1; break; case constant2:
// code to be executed if n is equal to constant2; break; . . . default:
// code to be executed if n doesn't match any Constant }
By- Er. Indrajeet Sinha , +919509010997
“SWITCH” STATEMENT
switch (aNumber) { case 1 : countA++; break; case 10 : countB++; break; case 100 : case 500 : countC++; break; default : countD++; } // End switch
By- Er. Indrajeet Sinha , +919509010997
FLOW CHART OF SWITCH STATEMENT
17
By- Er. Indrajeet Sinha , +919509010997
2.1.6 PROBLEMS ON CONDITIONAL STATEMENTS
18
# include <stdio.h>int main() { char operator; double firstNumber,secondNumber; printf("Enter an operator (+, -, *, /): "); scanf("%c", &operator); printf("Enter two operands: "); scanf("%lf %lf",&firstNumber, &secondNumber); switch(operator) { case '+': printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber+secondNumber); break; case '-': printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-
secondNumber); break;
PROGRAM TO CREATE A SIMPLE CALCULATOR// PERFORMS ADDITION, SUBTRACTION, MULTIPLICATION OR DIVISION DEPENDING THE INPUT FROM USER
By- Er. Indrajeet Sinha , +919509010997
CONT…
19
case '*': printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber*secondNumber); break; case '/': printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber/firstNumber); break; // operator is doesn't match any case constant (+, -, *, /) default: printf("Error! operator is not correct"); } return 0;}
Output- Enter an operator (+, -, *,): -Enter two operands: 32.512.432.5 - 12.4 = 20.1
LOOP CONTROL STATEMENT
Lecture no.- 15, UNIT- II
By- Er. Indrajeet Sinha , +919509010997
2.2.1 INTRODUCTION OF LOOPS Definition
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
loop. Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Loops are used in programming to repeat a specific block of code. After reading this tutorial, you will learn to create a for loop in C programming.
for loopwhile loopdo...while loop 21
By- Er. Indrajeet Sinha , +919509010997
2.2.2 INITIALIZATION, TEST CONDITION, INCREMENT AND DECREMENT OF LOOPS
Note:- A sequence of statements are executed until a specified condition is true. This sequence of statements to be executed is kept inside the curly braces { } known as the Loop body. After every execution of loop body, condition is verified, and if it is found to be true the loop body is executed again. When the condition check returns false, the loop body is not executed. 22
By- Er. Indrajeet Sinha , +919509010997
2.2.3- FOR LOOP A for loop is a repetition control structure that
allows us to efficiently write a loop that needs to execute a specific number of times. Syntax
for ( init; condition; increment ) { statement(s); }
Here is the flow of control in a 'for' loop − The init step is executed first, and only once.
This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. 23
By- Er. Indrajeet Sinha , +919509010997
Next, 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 the flow of control jumps to the next statement just after the 'for' loop.
After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates. 24
By- Er. Indrajeet Sinha , +919509010997
Flow Diagram
25
By- Er. Indrajeet Sinha , +919509010997
EXAMPLE FOR LOOP
#include <stdio.h> int main () {
int a; /* for loop execution */ for( a = 10; a < 20; a = a +
1 ) { printf("value of a: %d\n", a); }
return 0; }
26
Out Put:value of a: 10 value of a: 11value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
By- Er. Indrajeet Sinha , +919509010997
for” with a single statement
for” with a block of statements
27
for (i = 1; i <= MAX_LENGTH; i++) printf("#");
for (i = 0; i < MAX_SIZE; i++) { printf("Symbol is %c\n", aBuffer[i]); aResult = aResult / i; } // End for
WHILE LOOP
Lecture no.- 17, UNIT- II
By- Er. Indrajeet Sinha , +919509010997
2.2.5- WHILE LOOP A while loop in C programming repeatedly
executes a target statement as long as a given condition is true. Syntax
while(condition) { statement(s); }
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following the loop.
29
By- Er. Indrajeet Sinha , +919509010997
Flow Diagram
30
Here, the key point to note is that a while loop might not execute at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
By- Er. Indrajeet Sinha , +919509010997
Example While Loop
#include <stdio.h> int main () { /* local variable definition */ int a = 10; /* while loop execution */ while( a < 20 ) { printf("value of a: %d\n", a); a+
+; } return 0; } 31
Out Put:value of a: 10 value of a: 11value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
By- Er. Indrajeet Sinha , +919509010997
2.2.6- DO-WHILE LOOP Unlike for and while loops, which test the loop condition
at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time. Syntax
do {
statement(s); } while
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false. 32
By- Er. Indrajeet Sinha , +919509010997
Flow Diagram
33
By- Er. Indrajeet Sinha , +919509010997
Example#include <stdio.h> int main () { /* local variable definition */ int a = 10; /* do loop execution */ do { printf("value of a: %d\n",
a); a = a + 1; }while( a < 20 ); return 0; } 34
Out Put:value of a: 10 value of a: 11value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
NESTED LOOPS (FOR,WHILE,DO-WHILE)
Lecture no.- 18, UNIT- II
By- Er. Indrajeet Sinha , +919509010997
2.2.8 - NESTED LOOPS (FOR,WHILE,DO-WHILE)
C programming allows to use one loop inside another loop. On loop nesting is that we can put any type of loop inside
any other type of loop. For example, a 'for' loop can be inside a 'while' loop or vice versa. Syntax
The syntax for a nested for loop statement in C is as follows −for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); }
36
By- Er. Indrajeet Sinha , +919509010997
The syntax for a nested while loop statement in C programming language is as follows −
while(condition) { while(condition) { statement(s); } statement(s); }
37
By- Er. Indrajeet Sinha , +919509010997
The 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 ); 38
By- Er. Indrajeet Sinha , +919509010997
Example The following program uses a nested for loop to find the prime
numbers from 2 to 100 −#include <stdio.h> int main () { /* local variable definition */ int i, j; for(i = 2; i<100; i++) { for(j = 2; j <= (i/j); j++) if(!(i%j)) break; // if factor found, not prime if(j > (i/j)) printf("%d is prime\n", i); } return 0; }
39
OutPut:2 is prime3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime... 89 is prime 97 is prime
ARRAY IN C
Lecture no.- 19, UNIT- II
By- Er. Indrajeet Sinha , +919509010997
INTRODUCTION OF LECTURE
What is Array? Arrays a kind of data structure that can store a
fixed-size sequential collection of elements of the same type.
An 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.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
41
By- Er. Indrajeet Sinha , +919509010997
Array – In the C programming language an array is a fixed sequenced collection of elements of the same data type. It is simply a grouping of like type data. In the simplest form, an array can be used to represent a list of numbers, or a list of names. Some examples where the concept of an array can be used:
List of temperatures recorded every hour in a day , or a month, or a year.
List of employees in an organization List of products and their cost sold by a store 42
By- Er. Indrajeet Sinha , +919509010997
Since an array provides a convenient structure for representing data, it is classified as one of the data structures in C language.
There are following types of arrays in the C programming language –One – dimensional arraysTwo – dimensional arraysMultidimensional arrays
43
By- Er. Indrajeet Sinha , +919509010997
2.3.1 ONE-DIMENSIONAL ARRAY
Definition A list of items can be given one variable name using only
one subscript and such a variable is called single sub-scripted variable or one dimensional array.
2.3.2 Declaration of 1D Arrays – Like any other variable, arrays must be declared
before they are used so that the compiler can allocate space for them in the memory. The syntax form of array declaration is – Syntax
Datatype arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type.
44
By- Er. Indrajeet Sinha , +919509010997
Example – float height[50]; int groupt[10]; char name[10]
Now as we declare a array int number[5];
Then the computer reserves five storage locations as the size of the array is 5 as shown below –
45
By- Er. Indrajeet Sinha , +919509010997
Initialization of 1D Array After an array is declared, it’s elements must be
initialized. In C programming an array can be initialized at either of the following stages:
At compile time At run time
Compile Time initialization We can initialize the elements of arrays in the same
was as the ordinary variables when they are declared. The general form of initialization of array is:
type array-name[size] = { list of values };The values in the list are separated by commas. For ex, the statement
int number[3] = { 0,5,4 }; 46
By- Er. Indrajeet Sinha , +919509010997
Run time Initialization An array can also be explicitly initialized at run time.
For ex – consider the following segment of a C program.
for(i=0;i<10;i++) { scanf(" %d ", &x[i] ); }
Above example will initialize array elements with the values entered through the keyboard. In the run time initialization of the arrays looping statements are almost compulsory. Looping statements are used to initialize the values of the arrays one by one by using assignment operator or through the keyboard by the user. 47
By- Er. Indrajeet Sinha , +919509010997
Simple C program to store the elements in the array and to print them from the array.
#include<stdio.h> void main() { int array[5],i; printf("Enter 5 numbers to store them in array \n");
for(i=0;i<5;i++) { scanf("%d",&array[i]); } printf("Element in the array are - \n \n"); for(i=0;i<5;i++) { printf("Element stored at a[%d] = %d \n",i,array[i]); } getch(); }
48
Input – Enter 5 elements in the array – 23 45 32 25 45Output – Elements in the array are –Element stored at a[0]-23Element stored at a[0]-45Element stored at a[0]-32Element stored at a[0]-25Element stored at a[0]-45
By- Er. Indrajeet Sinha , +919509010997
2.3.4 TWO-DIMENSIONAL ARRAY Definition
2D Arrays- There could be situations where a table of values will have to be stored. In such cases 1D arrays are of no use. So we use 2D arrays to represent the items in tables.
Declaration syntax – type array_name [row_size][column_size];
Initializing 2D Array Like the one dimensional array, 2D arrays can be initialized in
both the two ways; the compile time initialization and the run time initialization.
Compile Time initialization – We can initialize the elements of the 2D array in the same way as the ordinary variables are declared. The best form to initialize 2D array is by using the matrix form. Syntax is as below –
int table-[2][3] = { { 0, 2, 5} { 1, 3, 0} }; 49
By- Er. Indrajeet Sinha , +919509010997
Run Time initialization – As in the initialization of 1D array we used the looping statements to set the values of the array one by one.
In the similar way 2D array are initialized by using the looping structure.
Initialization method –for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&ar1[i][j]); } }
50
By- Er. Indrajeet Sinha , +919509010997
Sample 2D array Program #include<stdio.h> #include<conio.h> void main() { int array[3][3],i,j,count=0; /* Run time Initialization */
for(i=1;i<=3;i++) { for(j=1;j<=3;j++) { count++; array[i][j]=count; printf("%d \t",array[i][j]); } printf("\n"); } getch(); }
51
Output –1 2 34 5 67 8 9
STRING IN C
Lecture no.- 23, UNIT- II
By- Er. Indrajeet Sinha , +919509010997
2.11- INTRODUCTION OF LECTURE
Definition Strings are actually one-dimensional array of
characters terminated by a null character '\0'. In C programming, array of character are
called strings.
53
By- Er. Indrajeet Sinha , +919509010997
2.3.7 STRINGS – DECLARATION, INITIALIZATION, READING, PRINTING
Declaration and initialization of String The following declaration and initialization create a
string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello.“
Syntax char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
OR char greeting[] = "Hello";
54
By- Er. Indrajeet Sinha , +919509010997
Following is the memory presentation of the above defined string in C
Note: The C compiler automatically places the '\0' at the end of the string when it initializes the array. 55
By- Er. Indrajeet Sinha , +919509010997
Programming. Ex-#include <stdio.h> int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting message: %s\n", greeting ); return 0; }
Output:Greeting message: Hello
56
By- Er. Indrajeet Sinha , +919509010997
2.3.8- STANDARD LIBRARY FUNCTION OF STRING
57Note:Where S1 and S2 are two different string.
S.N. Function Purpose
1 strcpy(s1, s2); Copies string s2 into string s1.
2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.
3 strlen(s1); Returns the length of string s1.
4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
By- Er. Indrajeet Sinha , +919509010997
Programming Example#include <stdio.h> #include <string.h> int main () { char str1[12] = "Hello"; char str2[12] = "World"; char str3[12]; int len ; /* copy str1 into str3 */ strcpy(str3, str1); printf("strcpy( str3, str1) : %s\n", str3 ); /* concatenates str1 and
str2 */ strcat( str1, str2); printf("strcat( str1, str2): %s\n", str1 ); /* total lenghth of str1 after
concatenation */ len = strlen(str1); printf("strlen(str1) : %d\n", len ); return 0; }
58
Output:strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10
POINTERS, ADDRESS ARITHMETIC
Lecture no.- 24, UNIT- II
By- Er. Indrajeet Sinha , +919509010997
INTRODUCTION TO POINTERS
Definition: Pointers are variables that hold address of another
variable of same data type.
Benefit of using pointers Pointers are more efficient in handling Array and
Structure. Pointer allows references to function and thereby helps in
passing of function as arguments to other function. It reduces length and the program execution time. It allows C to support dynamic memory management.
60
By- Er. Indrajeet Sinha , +919509010997
2.4.1 CONCEPT OF POINTERS
Whenever a variable is declared, system will allocate a location to that variable in the memory, to hold value. This location will have its own address number.Let us assume that system has allocated memory location 80F for a variable a.
int a = 10 ;
61
By- Er. Indrajeet Sinha , +919509010997
We can access the value 10 by either using the variable name a or the address 80F. Since the memory addresses are simply numbers they can be assigned to some other variable. The variable that holds memory address are called pointer variables. A pointer variable is therefore nothing but a variable that contains an address, which is a location of another variable. Value of pointer variable will be stored in another memory location.
62
By- Er. Indrajeet Sinha , +919509010997
Declaring a pointer variable Syntax
data-type *pointer_name; Note:- Data type of pointer must be same as the variable,
which the pointer is pointing. void type pointer works with all data types, but isn't used often.
Initialization of Pointer variable
int a = 10 ; int *ptr ; //pointer declaration ptr = &a ; //pointer initialization or, int *ptr = &a ; //initialization and declaration together
63
By- Er. Indrajeet Sinha , +919509010997
2.4.3 THE DEREFERENCING OPERATOR
Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is dereferenced, using the indirection operator.
int a,*p; a = 10; p = &a; printf("%d",*p); //this will print the value of a. printf("%d",*&a); //this will also print the value of a. printf("%u",&a); //this will print the address of a. printf("%u",p); //this will also print the address of a. printf("%u",&p); //this will also print the address of p.
64
By- Er. Indrajeet Sinha , +919509010997
2.4.4 ADDRESS ARITHMETIC A pointer in c is an address, which is a numeric value.
Therefore, we can perform arithmetic operations on a pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and – To understand pointer arithmetic, let us consider
that ptr is an integer pointer which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer −ptr++ After the above operation, the ptr will point to the
location 1004 because each time ptr is incremented, it will point to the next integer location which is 4 bytes next to the current location. This operation will move the pointer to the next memory location without impacting the actual value at the memory location. 65
By- Er. Indrajeet Sinha , +919509010997
Incrementing a Pointer#include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = var; for ( i = 0; i < MAX; i++) { printf("Address of var[%d] = %x\n", i, ptr ); printf("Value of var[%d] = %d\n", i, *ptr ); /* move to the next location */ ptr++; } return 0; }
66
Output:-Address of var[0] = bf882b30 Value of var[0] = 10 Address of var[1] = bf882b34 Value of var[1] = 100 Address of var[2] = bf882b38 Value of var[2] = 200
By- Er. Indrajeet Sinha , +919509010997
Decrementing a Pointer#include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr; /* let us have array address in pointer */ ptr = &var[MAX-1]; for ( i = MAX; i > 0; i--) { printf("Address of var[%d] = %x\n", i-1, ptr ); printf("Value of var[%d] = %d\n", i-1, *ptr ); /* move to the
previous location */ ptr--; } return 0; }
67
Output:-Address of var[2] = bfedbcd8Value of var[2] = 200 Address of var[1] = bfedbcd4 Value of var[1] = 100 Address of var[0] = bfedbcd0 Value of var[0] = 10
POINTERS TO REPRESENT ARRAY
Lecture no.- 25, UNIT- II
By- Er. Indrajeet Sinha , +919509010997
2.5.1 POINTERS TO REPRESENT ARRAYS
we can use a pointer to point to an Array, and then we can use that pointer to access the array.
#include <stdio.h> const int MAX = 3; int main () { int var[] = {10, 100, 200}; int i, *ptr[MAX]; for ( i = 0; i < MAX; i++) { ptr[i] = &var[i]; /* assign the address of integer. */ } for ( i = 0; i < MAX; i++) { printf("Value of var[%d] = %d\n", i, *ptr[i] ); } return 0; } 69
Output:-Value of var[0] = 10 Value of var[1] = 100 Value of var[2] = 200
By- Er. Indrajeet Sinha , +919509010997
2.5.2- POINTERS AND STRINGS Pointer can also be used to create strings. Pointer variables
of char type are treated as string.Consider
The above creates a string and stores its address in the pointer variable str. The pointer str now points to the first character of the string "Hello". Another important thing to note that string created using char pointer can be assigned a value at runtime.
char *str; str = "hello"; //this is Legal The content of the string can be printed
using printf() and puts(). printf("%s", str); puts(str); Notice: That str is pointer to the string, it is also name of the
string. Therefore we do not need to use indirection operator *.
70
char *str = "Hello";
By- Er. Indrajeet Sinha , +919509010997
We can also have array of pointers. Pointers are very helpful in handling character array with rows of varying length.
char *name[3]={"Adam“,"chris“,"Deniel”};//Now see same array without using
pointer char name[3][20]= { "Adam", "chris", "Deniel" };
71
By- Er. Indrajeet Sinha , +919509010997
2.5.3 POINTERS TO POINTERS A pointer to a pointer is a form of multiple indirection, or a
chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name.
For example,
int **var; 72
Pointer-1 Address
Pointer-2 Address
VariableValue
By- Er. Indrajeet Sinha , +919509010997
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example −
#include <stdio.h> int main () {
int var; int *ptr; int **pptr; var = 3000; /* take the address of var */ ptr = &var; /* take the address of ptr using address of operator & */ pptr = &ptr; /* take the value using pptr */ printf("Value of var = %d\n", var ); printf("Value available at *ptr = %d\n", *ptr ); printf("Value available at **pptr = %d\n", **pptr); return 0;
} 73
Output:Value of var = 3000 Value available at *ptr = 3000 Value available at **pptr = 3000
By- Er. Indrajeet Sinha , +919509010997
2.5.4 VOID POINTERS Definition: The void pointer, also known as the generic pointer, is a
special type of pointer that can be pointed at objects of any data type. A void pointer is declared like a normal pointer, using the void keyword as the pointer's type:
void *ptr; // ptr is a void pointer Void Pointer Basics :
In C General Purpose Pointer is called as void Pointer. It does not have any data type associated with it It can store address of any type of variable A void pointer is a C convention for a raw address. The compiler has no idea what type of object a void Pointer really points
to ?74
By- Er. Indrajeet Sinha , +919509010997
Declaration of Void Pointer :void * pointer_name;
Void Pointer Example :void *ptr; // ptr is declared as Void pointer char Cnum; int inum; float fnum; ptr = &Cnum; // ptr has address of character data ptr = &inum; // ptr has address of integer data ptr = &fnum; // ptr has address of float data
75
By- Er. Indrajeet Sinha , +919509010997
Explanation :void *ptr;
1. Void pointer declaration is shown above.
2. We have declared 3 variables of integer,character and float type.
3. When we assign address of integer to the void pointer, pointer will become Integer Pointer.
4. When we assign address of Character Data type to void pointer it will become Character Pointer.
5. Similarly we can assign address of any data type to the void pointer.
6. It is capable of storing address of any data type 76
By- Er. Indrajeet Sinha , +919509010997
Summary : Void Pointer
77
Scenario Behavior
When We assign address of integer variable to void pointer
Void Pointer Becomes Integer Pointer
When We assign address of character variable to void pointer
Void Pointer Becomes Character Pointer
When We assign address of floating variable to void pointer
Void Pointer Becomes Floating Pointer
By- Er. Indrajeet Sinha , +919509010997
2.6.1 COMMAND LINE ARGUMENTS Definition: It is possible to pass some values from the command
line to our C programs when they are executed. These values are called command line arguments.
The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program.
78
By- Er. Indrajeet Sinha , +919509010997
79
By- Er. Indrajeet Sinha , +919509010997
Following is a simple example #include <stdio.h> int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } }
80
By- Er. Indrajeet Sinha , +919509010997
When the above code is compiled and executed with single argument, it produces the following result.
$./a.out testing The argument supplied is testing When the above code is compiled and executed with a two
arguments, it produces the following result.$./a.out testing1 testing2 Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces the following result.
$./a.out One argument expected NOTE: It should be noted that argv[0] holds the name of the program
itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if you pass one argument then argc is set at 2. 81
STRUCTURES, TYPEDEF
Lecture no.- 26, UNIT- II
By- Er. Indrajeet Sinha , +919509010997
2.7.1 DECLARATION OF STRUCTURE Definition:- Structure is composition of the different variables of
different data types , grouped under same name. It is user defined data types in C.
The format of the structure statement is as follows −struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables];
Note:-1. Each member declared in Structure is called member. 2. Name given to structure is called as tag 3.Structure member may be of different data type including user
defined data- type also83
By- Er. Indrajeet Sinha , +919509010997
2.7.3 ACCESSING & INITIALIZATION Accessing Structure Members: To access any member of a structure, we use the member
access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use the keyword struct to define variables of structure type. The following example shows how to use a structure in a program −
#include <stdio.h> #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; 84
By- Er. Indrajeet Sinha , +919509010997
CONT…int main( ) { struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 */ /* book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407; /* book 2 specification */ strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700;
85
By- Er. Indrajeet Sinha , +919509010997
CONT…/* print Book1 info */ printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author); printf( "Book 1 subject : %s\n", Book1.subject); printf( "Book 1 book_id : %d\n", Book1.book_id);
/*Book2infoprintf( "Book 2 title : %s\n", Book2.title); printf( "Book 2 author : %s\n", Book2.author); printf( "Book 2 subject : %s\n", Book2.subject); printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0; }
86
By- Er. Indrajeet Sinha , +919509010997
CONT…
87
Output:Book 1 title : C Programming Book 1 author : Nuha Ali Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407 Book 2 title : Telecom Billing Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700
By- Er. Indrajeet Sinha , +919509010997
2.7.4 STRUCTURE AND UNION Definition: A union is a special data type available in C that allows
to store different data types in the same memory location. We can define a union with many members, but only one
member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.
o Defining a Union union [union tag]
{ member definition; member definition; ... member definition; } [one or more Union variables]; 88
By- Er. Indrajeet Sinha , +919509010997
#include <stdio.h> #include <string.h> union Data
{ int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10;
data.f = 220.5; strcpy( data.str, "C Programming"); printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f); printf( "data.str : %s\n", data.str); return 0; }
89
Output:data.i : 1917853763 data.f :4122360580327794860452759994368.000000 data.str : C Programming
By- Er. Indrajeet Sinha , +919509010997
2.7.5 TYPE DEFINITION Definition The C programming language provides a keyword
called typedef, which we can use to give a type, a new name. Following is an example to define a term BYTE for one-byte numbers −
typedef unsigned char BYTE; After this type definition, the identifier BYTE can be used as
an abbreviation for the type unsigned char, for example.BYTE b1, b2;
By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but we can use lowercase, as follows −
typedef unsigned char byte; we can use typedef to give a name to our user defined data
types as well. 90
By- Er. Indrajeet Sinha , +919509010997
CONT… For example, we can use typedef with structure to
define a new data type and then use that data type to define structure variables directly as follows −
#include <stdio.h> #include <string.h>
typedef struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } Book; 91
By- Er. Indrajeet Sinha , +919509010997
CONT… int main( ) {
Book book; strcpy( book.title, "C Programming"); strcpy( book.author, “Indrajeet"); strcpy( book.subject, "C Programming Tutorial");book.book_id = 6495407; printf( "Book title : %s\n", book.title); printf( "Book author : %s\n", book.author); printf( "Book subject : %s\n", book.subject); printf( "Book book_id : %d\n", book.book_id); return 0;
} 92
By- Er. Indrajeet Sinha , +919509010997
93
Output:Book title : C Programming Book author : Indrajeetsubject : C Programming Tutorial Book book_id : 6495407