SlideShare a Scribd company logo
/* Ranking  of 60 students in a class */ int main() { /*declaring 60 varialbes */ int  score0, score1,score2,……,score59;  /* Reading scores for sixty times */ printf(“Enter  the score : “);  scanf(“%d”, &score0); … .  ….  ….  …. printf(“Enter  the score : “); scanf(“%d”, &score59); /* comparing & swapping for 1770 times * to arrange in descending order  */ swap( score0, score1); swap( score1, score2); swap( score2, score3); … .  ….  ….  …. swap( score0,score1); swap( score1,score2); swap( score0,score1); /*printing 60 scores after sorting */ printf(“%4d”, score0); printf(“%4d”, score1); …  …  …  … }  void swap ( int  a, int b)  { int temp; if( a < b) { temp = a  ;  a = b  ;  b = temp; } } score0  score1 score2  score3 . . score59   scores[0] scores[1] scores[2]  scores[3] . . scores[59]   #include<stdio.h> int main()  { int scores[60]  , i , j, temp; for(i = 0; i < 60 ;i++)  { printf(&quot;Enter the score : &quot;); scanf(&quot;%d&quot;, &scores[i]); } for(i=0;i<(60-1);i++) for( j=0; j <(60 -(i+1)); j++) if(scores[ j ] < scores[ j +1]) { temp = scores[ j ];  scores[ j ] = scores[ j +1]; scores[ j + 1] = temp; } for( i = 0; i  < 60; i ++) printf(&quot;%4d&quot;, scores[i]); }  Sixty variables are replaced by one  Array Sixty input statements are called by one loop statement 1770 comparing statements are included in one loop statement Array & its Advantage
scores[0] scores[1] scores[2] scores[3] scores[4] scores Array . . .  start here 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 ( memory addresses) Mean can be calculated only after reading all scores. Each deviation is difference of individual score and mean. To calculate deviations of all scores, scores must be stored in an  ARRAY. Initialization of Array Declaration of Array Processing  on  Array Input to an element Accessing  an element
Scalar Variables :  A variable represents a data item and it can be used to store  a single atomic value at a  time. These are also called scalar variables.  Integer takes 2 bytes memory as a single unit to store its value. i.e.,the value of a scalar variable cannot be subdivided into a more simpler data items.  The address of first byte is the address of a variable . Vector Variables (arrays) : In contrast, an  array  is multivariable (an aggregate data type), which is also referred to a data structure. It represents a collection of related data items of same type.  An individual data item of an array is called as ‘element’. Every element is accessed by index or subscript enclosed in square brackets followed after the array name. All its elements are stored in consecutive memory locations, referred under a common array name.    Ex : int marks[10] ; /* declaration  of array */ ‘ 0’ is first number in computer environment. The first element of array marks is marks[0] and last element is marks[9]. (the address of first element is the address of the array) An array is a derived data type. It has additional operations for retrieve and update the individual values. The lowest address corresponds to the first element and the highest address to the last element.  Arrays can have from one to several dimensions. The most common array is the  string,  which is simply an array of characters terminated by a null. Scalar variable for single data item & Vector variable for multiple data items
Declaration of One Dimensional Arrays Syntax : arrayType  arrayName [ numberOfElements ]; Example : int scores [60]; float salaries [20]; Initialization of Array while Declaration : int numbers [ ] = { 9, 4, 2, 7, 3 }; char  name[ ] ={‘R’,’a’,‘v’,‘i’,‘ ‘,‘T’,‘e’,‘j’,’a’,’\0’ }; char  greeting[ ] =  “Good Morning”;  Declaration of Multi Dimensional Arrays Syntax : arrayType  arrayName [ Rows ][ Columns ]; arrayType  arrayName [ Planes][ Rows ][ Columns ]; Example : /* Each student for seven subjects */ int marks[60][7];  /* Matrix with 3 planes and 5 rows and 4 columns */ float matrix[3][5][4];  Initialization of Array while Declaration : int  matrix [ ][ ] = {  {  4, 2, 7, 3 } ,   {  6, 1, 9, 5 } ,   {  8, 5, 0, 1 }  }; Elements of  Array [3] by [4]  /*passing  an array  to function  */ #define SIZE 10 int main() { float list[SIZE] ,avg; … … … … … avg  = average(SIZE ,  list ); … … … … …  } float  average( int n , float  x[])  { float  sum=0,i; for( i = 0; i  < n ; i++) sum = sum + x[i]; return  ( sum / n ) ; } [0][0] [0][1] [0][2] [0][3] [1][0] [1][1] [1][2] [1][3] [2][0] [2][1] [2][2] [2][3]
char name[25] ; scanf(“%s”, name); /*reading a string until a white space is encountered ( & operator is not required )*/ printf(“%s”, name);  /*printing a string in input window */ gets(name) ; /* reading a string including white spaces until ‘\n’ is encountered. */ puts(name); /* printing a string and moves cursor to new line */ Strings  -  One Dimensional Character Arrays A String is sequence of characters.  In ‘C’ strings are implemented by an array of characters terminated with a null character ‘\0’(back slash followed by zero ). char name[] = “Ravi Kiran”; name ‘ name’ is an array of characters has size of eleven characters including a null character ‘\0’(ascii code is zero). String Manipulation Functions in <string.h> strlen(s1) - returns the length of string excluding the last ‘null’ character. strcpy(s1,s2) - copies characters in s2 into s1. strcat(s1,s2) - concatenates s2 to s1. strcmp(s1,s2) -compares  s1 with s2 lexicographically and returns ‘0’ if two strings are  same , returns -1 if s1 is before s2 and returns +1 if s1 is after s2. strcmpi(s1,s2) -compares s1 with s2 like strcmp() but case of characters is ignored. strchr(s1,ch) -returns pointer to first occurrence of the character ‘ch’ in s1. strstr(s1,s2) -returns pointer to first occurrence s2 in s1. strrev(s1) -returns pointer to the reversed string. R a v i K i r a n \0
Memory Address  : Bit is a smallest unit of memory to store either ‘0’ or ‘1’ in memory. Byte is unit of memory of 8 bits. Memory is  a sequence of a large number of memory locations , each of which has an address known as byte. Every byte in memory has a sequential address number to recognized by processor. RAM is temporary storage place to run programs. C-Language runtime also utilizes an allotted memory block in RAM to run its programs. Text Section  : Memory-area that contains the machine instructions(code).It is read  only and is shared by multiple instances of a running program. Data Section  : Memory image of a running program contains storage for initialized  global variables, which is separate for each running instance of a program. BSS (Below Stack Segment)  : Memory area contains storage for uninitialized global  variables. It is also separate for each running instance of a program. Stack  : Area of memory image of  a running program contains storage for automatic  variables of a function. It also stores memory address of the instruction  which is the function call, to return the value of called function.  Heap  :  This memory region is reserved for dynamically allocating memory for  variables at run time.  Dynamic Memory Allocation  calculate the required  memory size while program is being executed. Shared Libraries : This region contains the executable image of shared libraries  being used by a program. Memory Sections of C-Runtime
Two or more Permanent Manipulations using one Function /* program to swap two numbers */ #include<stdio.h> void swap(int x, int y) { int temp; temp = x; x = y; y = temp; printf(“\nIn swap()  :  %d  %d “,x,y); } int main() { int  a = 25,b = 37; printf(“Before swap() : %d %d”,a,b); swap (a,b); printf(“\nAfter swap() : %d %d“,a,b); } Passing Parameters By Value Passing Parameters By Reference Output :  Before swap()  25 37 In swap ()  37 25 After swap()  25 37 /* program to swap two numbers */ #include<stdio.h> void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; printf(“\nIn swap()  :  %d  %d “,*x,*y); } int main() { int  a = 25,b = 37; printf(“Before swap() : %d %d”,a,b); swap (&a , &b); printf(“\nAfter swap() : %d %d“,a,b); } Output :  Before swap()  25 37 In swap ()  37 25 After swap()  37 25
Pointer variable – A variable holds the address of another variable char option = ‘Y’; Allots some memory location  4042 (for example) with a name option and  stores value ‘Y’  in it   ‘ Y’ option 4042 Value in ‘option’  Memory Address of variable ‘option’  char *ptr = NULL; Creates a pointer variable with a name ‘ptr’ Which can hold a  Memory address ptr Memory address of  Variable ‘option’ Is copied to the  Pointer ‘ptr’ 4042 ptr ptr = &option; ‘ Y’ option 4042 *ptr = ‘N’; The value ‘N’ is stored in the variable which has the  memory address 4042 4042 ptr ‘ N’ option 4042
Program with Using Pointers  int main() { int  n1, n2 ; int  *p = NULL, *q = NULL; n1  =  6 ; p  =  & n1; printf (“%d  %d”, n1,*p  ); printf (“%ld  %ld”,&n1, p ); q  =  & n2; *q  =  3 ; printf (“ %d  %d “, *p , *q ) ; p  =  q ; printf (“ %d  %d “, *p , *q ) ; *p  = 7 ; printf (“ %d  %d “, *p , *q ) ; } NULL NULL n1 n2 p q 6 3 n1 n2 p q pointer variables are declared Prints  6  3  6 3 n1 n2 p q pointer ‘q’ assigned with  pointer ‘q’  Prints  3  3  6 7 n1 n2 p q Prints  7  7  When two pointers are referencing with one variable, both pointers contains address of the same variable, and  the value changed through with one pointer will reflect to both of them.  Prints  6  6  Prints address of  n1
Pointer and Arrays  Even though pointers and arrays work alike and strongly related, they are not synonymous. When an array is assigned with pointer, the address of first element of the array is copied into the pointer.  #include<stdio.h> int main() { int  a[3] = { 12, 5 ,7}, b[3]; int *p ,*q; p = a; printf(&quot;%d %d\n&quot;, *p, *a); q = p; printf(&quot;%d %d&quot;,*p,*q); b = a;  /*  error  */ }  Prints  12  12 Prints  12  12 Pointer is an address variable, having no initialized value by default. The address stored  in  the pointer can be changed time to time in the program. Array name is an address constant, initialized with the address of the first element (base address )in the array. The address stored in array name cannot be changed in the program.
Pointer Arithmetic and Arrays  #include <stdio.h> int main() { int arr [5]  = {  12, 31, 56, 19, 42 }; int *p; p = arr + 1; printf(&quot;%d \n&quot;, *p); printf(&quot;%d %d %d\n&quot;, *(p-1), *(p), *(p + 1)); --p; printf(&quot;%d&quot;, *p); Prints  31  Prints  12 31 56  Prints  12  Subscript operator [ ] used to access an element of array implements address arithmetic, like pointer. 12 31 56 19 42 arr[0]  or *( arr + 0 ) arr[1]  or *( arr + 1 ) arr[2]  or *( arr + 2 ) arr[3]  or *( arr + 3 ) arr[4]  or *( arr + 4 ) p  -  1  p  p  + 1 p  + 2  p  + 3
Array of Pointers  The advantage of pointer array is that the length of each row in the array may be different. The important application of pointer array is to store character strings of different length.  Example :  char  *day[ ] = { “Sunday”, “Monday”, ”Tuesday”, “Wednesday”, “Thursday”,  “Friday”, “Saturday” };  Pointer to Pointer ( Double indirection )  Example :  int  a = 25; int  *pa = &a; int  **ppa ; *ppa  =  &pa; printf(“%d”, *pa);    prints  25  printf(“%d”, **ppa);    prints 25 25 pa ppa 4078 4024 4056 4056 4024 a Two Dimensional Array -- Pointers  base_address Address of a[ i ] [ j ] = *( * ( base_address + i ) + j ) = * ( * ( a + i ) + j )  Array name contains base address  a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] a[3][0] a[3][1] a[3][2]
void Pointer  int main( )  { void*  p; int x = 7; float y = 23.5; p = &x; printf(“x contains : %d\n”, *( ( int *)p) ); p = &y; printf(“y contains : %f\n”, *( ( float *)p) ); }  ‘ void’ type pointer is a generic pointer, which can be assigned to any data type without cast during compilation or runtime. ‘void’ pointer cannot be dereferenced unless it is cast.  Output : x contains  7 y contains 23.500000 Function Pointers Function pointers are pointers, which point to the address of a function. Declaration : <return type> (* function_pointer) (type1  arg1, type2 arg2, ……. ); int add ( int a, int b ) { return (a + b) ; } int sub ( int a, int b ) { return (a – b) ; } int (*fp ) (int, int ) ; /* function pointer */ int main( )  { fp = add; printf(“Sum = %d\n”, fp( 4, 5 )  ) ; fp = sub; printf(“Difference = %d\n”, fp( 6 , 2 )  ) ; }  Output : Sum = 9 Difference = 4
Dynamic Memory Allocation (DMA) of pointers  Static memory allocation means allocating memory by compiler. When  using address operator, the address of a variable is assigned to a pointer.  Ex : int  a = 20 ;  int *p = &a ; Dynamic memory allocation means allocating memory using functions like malloc() and calloc(). The values returned by these functions are assigned to pointer variables only after execution of these functions. Memory is assigned at run time. int main() { int *p, *q ; p = (int  *) malloc ( sizeof( int ) ); if( p == NULL ) {  printf(“Out of memory\n”); exit(-1); } printf(“Address  in  p : %d“, p ); free ( p ); p = NULL;  }  Allocates memory in bytes and returns the address of first byte to the pointer variable  Releases previously allocated memory space.  calloc ( ) is used for allocating memory space during the program execution for derived data types such as arrays, structures etc., Example :  struct book { int no ;  char name[20] ; float price ; }; struct  book  b1 ; b1  *ptr ; ptr  = (book *) calloc ( 10, sizeof ( book ) );  ptr  = (book * ) realloc ( ptr , 35 * sizeof ( book ) );  Modifies the size of previously allocated memory to new size.
Standard Character Functions  Classification of Characters control iscntrl ( ) printable isprint ( ) space isspace ( ) graphical isgraph () alpha-numeric isalnum ( ) punctuation ispunct ( ) alphabetic isalpha( ) digit isdigit () upper isupper ( ) lower islower () Other character functions in <ctype.h> toupper( ) – converts to uppercase. tolower ( ) – converts to lowercase.  toascii ( ) – converts greater than 127 to  with in the range 0 – 127  int main( int  argc , char* argv [ ]) { int i ; printf(“Number of arguments : %d“, argc ); printf(“\nName of Program : %s“, argv [0] ); for ( i = 1; i  < argc ; i++ )  printf(“\nUser value %d : %s “,   i , argv [ i ] );  }  Command Line Arguments Compile the program : c:\>tcc cmdline.c c:\>cmdline welcome to c-programming c:\>Number of arguments : 4 Name of Program  : c:\cmdline.exe User value 1  : welcome User value 2  : to User value 3  : c-programming File Name : cmdline.c output
Standard C-Library Functions  <stdlib.h> int atoi(s) Converts string s to an integer long atol(s) Converts string s to a long integer. float atof(s) Converts string s to a double-precision quantity. void* calloc(u1,u2) Allocate memory to an array u1, each of length u2 bytes. void exit(u) Closes all files and buffers, and terminate the program. void free (p) Free block of memory.  void* malloc (u) Allocate u bytes of memory. int rand(void) Return a random positive integer. void* realloc(p,u) Allocate u bytes of new memory to the pointer variable p. void srand(u) Initialize the random number generator. void systerm(s) Pass command string to the operating system. <time.h> clock_t clock() Returns clock ticks since program starts. char *asctime(stuct tm) Converts date and time into ascii. int stime(time_t *tp) Sets time. time_t time(time_t *timer) Gets time of day. double difftime(t1,t2) Returns difference time between two times t1 and t2.
Ad

More Related Content

What's hot (20)

strings
stringsstrings
strings
teach4uin
 
Unit 2
Unit 2Unit 2
Unit 2
TPLatchoumi
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
Praveen M Jigajinni
 
Arrays
ArraysArrays
Arrays
Chukka Nikhil Chakravarthy
 
Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2
Ali Aminian
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and strings
Rai University
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
GC University Faisalabad
 
Chapter 13.1.7
Chapter 13.1.7Chapter 13.1.7
Chapter 13.1.7
patcha535
 
Link list
Link listLink list
Link list
Malainine Zaid
 
Very interesting C programming Technical Questions
Very interesting C programming Technical Questions Very interesting C programming Technical Questions
Very interesting C programming Technical Questions
Vanathi24
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
Praveen M Jigajinni
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
Ilio Catallo
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
application developer
 
Arrays
ArraysArrays
Arrays
Saranya saran
 
Computer Programming- Lecture 5
Computer Programming- Lecture 5 Computer Programming- Lecture 5
Computer Programming- Lecture 5
Dr. Md. Shohel Sayeed
 
handling input output and control statements
 handling input output and control statements handling input output and control statements
handling input output and control statements
Rai University
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
Sowri Rajan
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
Appili Vamsi Krishna
 
CHAPTER 5
CHAPTER 5CHAPTER 5
CHAPTER 5
mohd_mizan
 
Strings
StringsStrings
Strings
Mitali Chugh
 

Similar to Unit3 C (20)

C Language Unit-3
C Language Unit-3C Language Unit-3
C Language Unit-3
kasaragadda srinivasrao
 
Unit3 jwfiles
Unit3 jwfilesUnit3 jwfiles
Unit3 jwfiles
mrecedu
 
Array, string and pointer
Array, string and pointerArray, string and pointer
Array, string and pointer
Nishant Munjal
 
Arrays
ArraysArrays
Arrays
AnaraAlam
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
YOGESH SINGH
 
Algoritmos e Estruturas de Dados - Pointers
Algoritmos e Estruturas de Dados - PointersAlgoritmos e Estruturas de Dados - Pointers
Algoritmos e Estruturas de Dados - Pointers
martijnkuipersandebo
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
AntareepMajumder
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
rajatryadav22
 
unit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentationunit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentation
MukeshTheLioner
 
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
aroraopticals15
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
string function with example...................
string function with example...................string function with example...................
string function with example...................
NishantsrivastavaV
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
JamesChristianGadian
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
Thesis Scientist Private Limited
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
Rabin BK
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
ShivamChaturvedi67
 
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
 
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdfPPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
YashShekhar6
 
Pointers definition syntax structure use
Pointers definition syntax structure usePointers definition syntax structure use
Pointers definition syntax structure use
dheeraj658032
 
Unit3 jwfiles
Unit3 jwfilesUnit3 jwfiles
Unit3 jwfiles
mrecedu
 
Array, string and pointer
Array, string and pointerArray, string and pointer
Array, string and pointer
Nishant Munjal
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
YOGESH SINGH
 
Algoritmos e Estruturas de Dados - Pointers
Algoritmos e Estruturas de Dados - PointersAlgoritmos e Estruturas de Dados - Pointers
Algoritmos e Estruturas de Dados - Pointers
martijnkuipersandebo
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
AntareepMajumder
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
rajatryadav22
 
unit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentationunit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentation
MukeshTheLioner
 
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
aroraopticals15
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
string function with example...................
string function with example...................string function with example...................
string function with example...................
NishantsrivastavaV
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
JamesChristianGadian
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
Rabin BK
 
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
 
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdfPPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
YashShekhar6
 
Pointers definition syntax structure use
Pointers definition syntax structure usePointers definition syntax structure use
Pointers definition syntax structure use
dheeraj658032
 
Ad

More from arnold 7490 (20)

Les14
Les14Les14
Les14
arnold 7490
 
Les13
Les13Les13
Les13
arnold 7490
 
Les11
Les11Les11
Les11
arnold 7490
 
Les10
Les10Les10
Les10
arnold 7490
 
Les09
Les09Les09
Les09
arnold 7490
 
Les03
Les03Les03
Les03
arnold 7490
 
Les02
Les02Les02
Les02
arnold 7490
 
Les01
Les01Les01
Les01
arnold 7490
 
Les12
Les12Les12
Les12
arnold 7490
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
arnold 7490
 
Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
arnold 7490
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
arnold 7490
 
Unit 4 Java
Unit 4 JavaUnit 4 Java
Unit 4 Java
arnold 7490
 
Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
arnold 7490
 
Unit 2 Java
Unit 2 JavaUnit 2 Java
Unit 2 Java
arnold 7490
 
Unit 1 Java
Unit 1 JavaUnit 1 Java
Unit 1 Java
arnold 7490
 
Ad

Recently uploaded (20)

tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 

Unit3 C

  • 1. /* Ranking of 60 students in a class */ int main() { /*declaring 60 varialbes */ int score0, score1,score2,……,score59; /* Reading scores for sixty times */ printf(“Enter the score : “); scanf(“%d”, &score0); … . …. …. …. printf(“Enter the score : “); scanf(“%d”, &score59); /* comparing & swapping for 1770 times * to arrange in descending order */ swap( score0, score1); swap( score1, score2); swap( score2, score3); … . …. …. …. swap( score0,score1); swap( score1,score2); swap( score0,score1); /*printing 60 scores after sorting */ printf(“%4d”, score0); printf(“%4d”, score1); … … … … } void swap ( int a, int b) { int temp; if( a < b) { temp = a ; a = b ; b = temp; } } score0 score1 score2 score3 . . score59 scores[0] scores[1] scores[2] scores[3] . . scores[59] #include<stdio.h> int main() { int scores[60] , i , j, temp; for(i = 0; i < 60 ;i++) { printf(&quot;Enter the score : &quot;); scanf(&quot;%d&quot;, &scores[i]); } for(i=0;i<(60-1);i++) for( j=0; j <(60 -(i+1)); j++) if(scores[ j ] < scores[ j +1]) { temp = scores[ j ]; scores[ j ] = scores[ j +1]; scores[ j + 1] = temp; } for( i = 0; i < 60; i ++) printf(&quot;%4d&quot;, scores[i]); } Sixty variables are replaced by one Array Sixty input statements are called by one loop statement 1770 comparing statements are included in one loop statement Array & its Advantage
  • 2. scores[0] scores[1] scores[2] scores[3] scores[4] scores Array . . . start here 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 ( memory addresses) Mean can be calculated only after reading all scores. Each deviation is difference of individual score and mean. To calculate deviations of all scores, scores must be stored in an ARRAY. Initialization of Array Declaration of Array Processing on Array Input to an element Accessing an element
  • 3. Scalar Variables : A variable represents a data item and it can be used to store a single atomic value at a time. These are also called scalar variables. Integer takes 2 bytes memory as a single unit to store its value. i.e.,the value of a scalar variable cannot be subdivided into a more simpler data items. The address of first byte is the address of a variable . Vector Variables (arrays) : In contrast, an array is multivariable (an aggregate data type), which is also referred to a data structure. It represents a collection of related data items of same type. An individual data item of an array is called as ‘element’. Every element is accessed by index or subscript enclosed in square brackets followed after the array name. All its elements are stored in consecutive memory locations, referred under a common array name. Ex : int marks[10] ; /* declaration of array */ ‘ 0’ is first number in computer environment. The first element of array marks is marks[0] and last element is marks[9]. (the address of first element is the address of the array) An array is a derived data type. It has additional operations for retrieve and update the individual values. The lowest address corresponds to the first element and the highest address to the last element. Arrays can have from one to several dimensions. The most common array is the string, which is simply an array of characters terminated by a null. Scalar variable for single data item & Vector variable for multiple data items
  • 4. Declaration of One Dimensional Arrays Syntax : arrayType arrayName [ numberOfElements ]; Example : int scores [60]; float salaries [20]; Initialization of Array while Declaration : int numbers [ ] = { 9, 4, 2, 7, 3 }; char name[ ] ={‘R’,’a’,‘v’,‘i’,‘ ‘,‘T’,‘e’,‘j’,’a’,’\0’ }; char greeting[ ] = “Good Morning”; Declaration of Multi Dimensional Arrays Syntax : arrayType arrayName [ Rows ][ Columns ]; arrayType arrayName [ Planes][ Rows ][ Columns ]; Example : /* Each student for seven subjects */ int marks[60][7]; /* Matrix with 3 planes and 5 rows and 4 columns */ float matrix[3][5][4]; Initialization of Array while Declaration : int matrix [ ][ ] = { { 4, 2, 7, 3 } , { 6, 1, 9, 5 } , { 8, 5, 0, 1 } }; Elements of Array [3] by [4] /*passing an array to function */ #define SIZE 10 int main() { float list[SIZE] ,avg; … … … … … avg = average(SIZE , list ); … … … … … } float average( int n , float x[]) { float sum=0,i; for( i = 0; i < n ; i++) sum = sum + x[i]; return ( sum / n ) ; } [0][0] [0][1] [0][2] [0][3] [1][0] [1][1] [1][2] [1][3] [2][0] [2][1] [2][2] [2][3]
  • 5. char name[25] ; scanf(“%s”, name); /*reading a string until a white space is encountered ( & operator is not required )*/ printf(“%s”, name); /*printing a string in input window */ gets(name) ; /* reading a string including white spaces until ‘\n’ is encountered. */ puts(name); /* printing a string and moves cursor to new line */ Strings - One Dimensional Character Arrays A String is sequence of characters. In ‘C’ strings are implemented by an array of characters terminated with a null character ‘\0’(back slash followed by zero ). char name[] = “Ravi Kiran”; name ‘ name’ is an array of characters has size of eleven characters including a null character ‘\0’(ascii code is zero). String Manipulation Functions in <string.h> strlen(s1) - returns the length of string excluding the last ‘null’ character. strcpy(s1,s2) - copies characters in s2 into s1. strcat(s1,s2) - concatenates s2 to s1. strcmp(s1,s2) -compares s1 with s2 lexicographically and returns ‘0’ if two strings are same , returns -1 if s1 is before s2 and returns +1 if s1 is after s2. strcmpi(s1,s2) -compares s1 with s2 like strcmp() but case of characters is ignored. strchr(s1,ch) -returns pointer to first occurrence of the character ‘ch’ in s1. strstr(s1,s2) -returns pointer to first occurrence s2 in s1. strrev(s1) -returns pointer to the reversed string. R a v i K i r a n \0
  • 6. Memory Address : Bit is a smallest unit of memory to store either ‘0’ or ‘1’ in memory. Byte is unit of memory of 8 bits. Memory is a sequence of a large number of memory locations , each of which has an address known as byte. Every byte in memory has a sequential address number to recognized by processor. RAM is temporary storage place to run programs. C-Language runtime also utilizes an allotted memory block in RAM to run its programs. Text Section : Memory-area that contains the machine instructions(code).It is read only and is shared by multiple instances of a running program. Data Section : Memory image of a running program contains storage for initialized global variables, which is separate for each running instance of a program. BSS (Below Stack Segment) : Memory area contains storage for uninitialized global variables. It is also separate for each running instance of a program. Stack : Area of memory image of a running program contains storage for automatic variables of a function. It also stores memory address of the instruction which is the function call, to return the value of called function. Heap : This memory region is reserved for dynamically allocating memory for variables at run time. Dynamic Memory Allocation calculate the required memory size while program is being executed. Shared Libraries : This region contains the executable image of shared libraries being used by a program. Memory Sections of C-Runtime
  • 7. Two or more Permanent Manipulations using one Function /* program to swap two numbers */ #include<stdio.h> void swap(int x, int y) { int temp; temp = x; x = y; y = temp; printf(“\nIn swap() : %d %d “,x,y); } int main() { int a = 25,b = 37; printf(“Before swap() : %d %d”,a,b); swap (a,b); printf(“\nAfter swap() : %d %d“,a,b); } Passing Parameters By Value Passing Parameters By Reference Output : Before swap() 25 37 In swap () 37 25 After swap() 25 37 /* program to swap two numbers */ #include<stdio.h> void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; printf(“\nIn swap() : %d %d “,*x,*y); } int main() { int a = 25,b = 37; printf(“Before swap() : %d %d”,a,b); swap (&a , &b); printf(“\nAfter swap() : %d %d“,a,b); } Output : Before swap() 25 37 In swap () 37 25 After swap() 37 25
  • 8. Pointer variable – A variable holds the address of another variable char option = ‘Y’; Allots some memory location 4042 (for example) with a name option and stores value ‘Y’ in it ‘ Y’ option 4042 Value in ‘option’ Memory Address of variable ‘option’ char *ptr = NULL; Creates a pointer variable with a name ‘ptr’ Which can hold a Memory address ptr Memory address of Variable ‘option’ Is copied to the Pointer ‘ptr’ 4042 ptr ptr = &option; ‘ Y’ option 4042 *ptr = ‘N’; The value ‘N’ is stored in the variable which has the memory address 4042 4042 ptr ‘ N’ option 4042
  • 9. Program with Using Pointers int main() { int n1, n2 ; int *p = NULL, *q = NULL; n1 = 6 ; p = & n1; printf (“%d %d”, n1,*p ); printf (“%ld %ld”,&n1, p ); q = & n2; *q = 3 ; printf (“ %d %d “, *p , *q ) ; p = q ; printf (“ %d %d “, *p , *q ) ; *p = 7 ; printf (“ %d %d “, *p , *q ) ; } NULL NULL n1 n2 p q 6 3 n1 n2 p q pointer variables are declared Prints 6 3 6 3 n1 n2 p q pointer ‘q’ assigned with pointer ‘q’ Prints 3 3 6 7 n1 n2 p q Prints 7 7 When two pointers are referencing with one variable, both pointers contains address of the same variable, and the value changed through with one pointer will reflect to both of them. Prints 6 6 Prints address of n1
  • 10. Pointer and Arrays Even though pointers and arrays work alike and strongly related, they are not synonymous. When an array is assigned with pointer, the address of first element of the array is copied into the pointer. #include<stdio.h> int main() { int a[3] = { 12, 5 ,7}, b[3]; int *p ,*q; p = a; printf(&quot;%d %d\n&quot;, *p, *a); q = p; printf(&quot;%d %d&quot;,*p,*q); b = a; /* error */ } Prints 12 12 Prints 12 12 Pointer is an address variable, having no initialized value by default. The address stored in the pointer can be changed time to time in the program. Array name is an address constant, initialized with the address of the first element (base address )in the array. The address stored in array name cannot be changed in the program.
  • 11. Pointer Arithmetic and Arrays #include <stdio.h> int main() { int arr [5] = { 12, 31, 56, 19, 42 }; int *p; p = arr + 1; printf(&quot;%d \n&quot;, *p); printf(&quot;%d %d %d\n&quot;, *(p-1), *(p), *(p + 1)); --p; printf(&quot;%d&quot;, *p); Prints 31 Prints 12 31 56 Prints 12 Subscript operator [ ] used to access an element of array implements address arithmetic, like pointer. 12 31 56 19 42 arr[0] or *( arr + 0 ) arr[1] or *( arr + 1 ) arr[2] or *( arr + 2 ) arr[3] or *( arr + 3 ) arr[4] or *( arr + 4 ) p - 1 p p + 1 p + 2 p + 3
  • 12. Array of Pointers The advantage of pointer array is that the length of each row in the array may be different. The important application of pointer array is to store character strings of different length. Example : char *day[ ] = { “Sunday”, “Monday”, ”Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” }; Pointer to Pointer ( Double indirection ) Example : int a = 25; int *pa = &a; int **ppa ; *ppa = &pa; printf(“%d”, *pa);  prints 25 printf(“%d”, **ppa);  prints 25 25 pa ppa 4078 4024 4056 4056 4024 a Two Dimensional Array -- Pointers base_address Address of a[ i ] [ j ] = *( * ( base_address + i ) + j ) = * ( * ( a + i ) + j ) Array name contains base address a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] a[3][0] a[3][1] a[3][2]
  • 13. void Pointer int main( ) { void* p; int x = 7; float y = 23.5; p = &x; printf(“x contains : %d\n”, *( ( int *)p) ); p = &y; printf(“y contains : %f\n”, *( ( float *)p) ); } ‘ void’ type pointer is a generic pointer, which can be assigned to any data type without cast during compilation or runtime. ‘void’ pointer cannot be dereferenced unless it is cast. Output : x contains 7 y contains 23.500000 Function Pointers Function pointers are pointers, which point to the address of a function. Declaration : <return type> (* function_pointer) (type1 arg1, type2 arg2, ……. ); int add ( int a, int b ) { return (a + b) ; } int sub ( int a, int b ) { return (a – b) ; } int (*fp ) (int, int ) ; /* function pointer */ int main( ) { fp = add; printf(“Sum = %d\n”, fp( 4, 5 ) ) ; fp = sub; printf(“Difference = %d\n”, fp( 6 , 2 ) ) ; } Output : Sum = 9 Difference = 4
  • 14. Dynamic Memory Allocation (DMA) of pointers Static memory allocation means allocating memory by compiler. When using address operator, the address of a variable is assigned to a pointer. Ex : int a = 20 ; int *p = &a ; Dynamic memory allocation means allocating memory using functions like malloc() and calloc(). The values returned by these functions are assigned to pointer variables only after execution of these functions. Memory is assigned at run time. int main() { int *p, *q ; p = (int *) malloc ( sizeof( int ) ); if( p == NULL ) { printf(“Out of memory\n”); exit(-1); } printf(“Address in p : %d“, p ); free ( p ); p = NULL; } Allocates memory in bytes and returns the address of first byte to the pointer variable Releases previously allocated memory space. calloc ( ) is used for allocating memory space during the program execution for derived data types such as arrays, structures etc., Example : struct book { int no ; char name[20] ; float price ; }; struct book b1 ; b1 *ptr ; ptr = (book *) calloc ( 10, sizeof ( book ) ); ptr = (book * ) realloc ( ptr , 35 * sizeof ( book ) ); Modifies the size of previously allocated memory to new size.
  • 15. Standard Character Functions Classification of Characters control iscntrl ( ) printable isprint ( ) space isspace ( ) graphical isgraph () alpha-numeric isalnum ( ) punctuation ispunct ( ) alphabetic isalpha( ) digit isdigit () upper isupper ( ) lower islower () Other character functions in <ctype.h> toupper( ) – converts to uppercase. tolower ( ) – converts to lowercase. toascii ( ) – converts greater than 127 to with in the range 0 – 127 int main( int argc , char* argv [ ]) { int i ; printf(“Number of arguments : %d“, argc ); printf(“\nName of Program : %s“, argv [0] ); for ( i = 1; i < argc ; i++ ) printf(“\nUser value %d : %s “, i , argv [ i ] ); } Command Line Arguments Compile the program : c:\>tcc cmdline.c c:\>cmdline welcome to c-programming c:\>Number of arguments : 4 Name of Program : c:\cmdline.exe User value 1 : welcome User value 2 : to User value 3 : c-programming File Name : cmdline.c output
  • 16. Standard C-Library Functions <stdlib.h> int atoi(s) Converts string s to an integer long atol(s) Converts string s to a long integer. float atof(s) Converts string s to a double-precision quantity. void* calloc(u1,u2) Allocate memory to an array u1, each of length u2 bytes. void exit(u) Closes all files and buffers, and terminate the program. void free (p) Free block of memory. void* malloc (u) Allocate u bytes of memory. int rand(void) Return a random positive integer. void* realloc(p,u) Allocate u bytes of new memory to the pointer variable p. void srand(u) Initialize the random number generator. void systerm(s) Pass command string to the operating system. <time.h> clock_t clock() Returns clock ticks since program starts. char *asctime(stuct tm) Converts date and time into ascii. int stime(time_t *tp) Sets time. time_t time(time_t *timer) Gets time of day. double difftime(t1,t2) Returns difference time between two times t1 and t2.