Movatterモバイル変換


[0]ホーム

URL:


123 views

Programming in C: UNIT-IV Pointers and User Defined Functions

Unit-4Pointers in C - Definition, Declaring and initialising pointers, accessing address and valueof variables using pointers,Pointer Arithmetic, Advantages and disadvantages of usingpointers.User Defined Functions - Need , structure of C user defined functions.Categories of userdefined functions - With and without parameters and return type. function call - call byvalue, call by reference.

Embed presentation

Download to read offline
Programming in C Unit-IV BCA Semester I1Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaUnit-IV: Pointers and User Defined FunctionsPointers in CDefinition:• A pointer is a special variable that stores the memory address of another variable insteadof storing a direct value.• Pointers are very powerful in C because they allow:o Direct access to memoryo Efficient handling of arrayso Dynamic memory allocationo Function calls by reference (to modify actual values)Syntax:datatype *pointer_name;• datatype → Specifies the type of value the pointer will point to (e.g., int, float, char).• The symbol * → Indicates that the variable being declared is a pointer.Declaring PointersTo declare a pointer, we must specify the data type it will point to and use the symbol * beforethe pointer name.Examples:int *p; // pointer to an integerfloat *q; // pointer to a floatchar *ch; // pointer to a characterInitializing Pointers:Pointers must be assigned a valid memory address. This is done using the address-of operator(&).
Programming in C Unit-IV BCA Semester I2Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaExample:int var = 10;int *ptr1 = &var; // ptr1 now holds the address of variable 'var'Accessing Address and Value Using Pointers:1. Getting the Address of a Variableint var = 10;printf("Address of var: %pn", &var);2. Accessing Value via Pointer (Dereferencing)int var = 10;int *ptr1 = &var;printf("Value of var: %dn", *ptr1); // Output: 103. Accessing Address via Pointerprintf("Address stored in pointer ptr1: %pn", ptr1);
Programming in C Unit-IV BCA Semester I3Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaDemonstration of Pointers in C: Accessing and Modifying Variable Using PointerOUTPUT:
Programming in C Unit-IV BCA Semester I4Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaPointer Arithmetic in CPointer arithmetic refers to performing operations on pointers to move across memory locations.It is mainly used when working with arrays, dynamic memory, and structures.Basic Pointer Arithmetic OperationsOperation Name OperationSymbolDescription Example Code Output /ResultPointerIncrementptr++ Moves the pointer tothe next elementint arr[3]={10,20,30};int *ptr=arr;ptr++;ptr → arr[1](value = 20)PointerDecrementptr-- Moves the pointer tothe previous elementint arr[3]={10,20,30};int *ptr=&arr[1];ptr--;ptr → arr[0](value = 10)Addition ofIntegerptr + n Moves pointerforward by nelementsint *ptr=arr;ptr = ptr + 2;ptr → arr[2](value = 30)Subtraction ofIntegerptr - n Moves pointerbackward by nelementsint *ptr=&arr[2];ptr = ptr - 1;ptr → arr[1](value = 20)PointerSubtractionptr1 - ptr2 Gives number ofelements between twopointers (same arrayonly)int *p1=&arr[2];int *p2=&arr[0];int diff = p1 - p2;diff = 2Pointer Addition(Invalid)ptr1 + ptr2 Adding two pointers isnot allowed— CompilationErrorPointerMultiplication(Invalid)ptr1 * ptr2 Multiplying pointers isnot allowed— CompilationErrorNotes:1. Pointer arithmetic works based on data type size, not bytes.Example:int *p; // int = 4 bytesp++; // moves 4 bytes ahead
Programming in C Unit-IV BCA Semester I5Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca2. Adding an integer to a pointer is allowed; adding/multiplying two pointers is notallowed.Example:p = p + 2; // validp = p + p; // invalidp = p * p; // invalid3. Subtracting two pointers gives distance in elements.Example:int arr[5];int *p1 = &arr[3];int *p2 = &arr[1];int d = p1 - p2; // d = 24. Pointer multiplication is not allowed; multiply the integer before adding.Example:p = p + (3); // move 3 positions
Programming in C Unit-IV BCA Semester I6Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaExample 1: Increment and DecrementExample 2: Using ptr + n• Adding an integer to a pointer• We cannot add two pointers, but we can add an integer to a pointer.ptr1 + ptr2; // ❌ Error• When we do ptr + n, the pointer moves n elements forward, not n bytes.
Programming in C Unit-IV BCA Semester I7Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaExample 3: Pointer DifferenceExample 4: Pointer Scaling• Direct multiplication of pointers is not allowed.We cannot do ptr * n or ptr1 * ptr2 in C. // ❌ Error• If we want to scale memory movement, we multiply an integer before adding to thepointer:ptr = base + (3 * n); // valid: moves 3*n elements ahead
Programming in C Unit-IV BCA Semester I8Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaAdvantages of Pointers1. Pointers save memory and time by passing addresses instead of copying data.2. They are required for dynamic memory allocation using malloc(), calloc(), etc.3. Pointers make array and string handling easier and faster.4. They allow functions to modify values directly using pass-by-reference.5. Pointers help in creating dynamic data structures like linked lists and trees.6. They allow direct access to memory and hardware-level operations.Disadvantages of Pointers1. Pointer-based programs are harder to understand and debug.2. Dangling pointers can cause crashes and unpredictable behavior.3. Forgetting to free memory leads to memory leaks.4. Incorrect pointer arithmetic may cause errors or segmentation faults.5. Misuse of pointers can cause security issues like buffer overflows.Applications of Pointers1. Pointers are used for dynamic memory allocation using malloc(), calloc(), and free().2. They are used to access and manipulate arrays and strings efficiently.3. Pointers help in passing arguments by reference to functions.4. They are essential for creating linked lists, stacks, queues, trees, and graphs.5. Pointers are used in system programming to access hardware and memory locationsdirectly.6. They are used for buffer management in files, networks, and I/O operations.7. Function pointers are used to implement callbacks and event-driven programming.8. Pointers support dynamic structures where size can grow or shrink at runtime.
Programming in C Unit-IV BCA Semester I9Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaFunction in CA function in C is a block of code that performs a specific task and can be called wheneverneeded in a program.• A function may take inputs (called parameters or arguments) and may return a value tothe calling function.• Functions make a program modular, reusable, and easy to debug.Types of Functions in C:1. Predefined (Library) Functions:o These functions are already provided by C.o Examples: printf(), scanf(), sqrt(), strlen()2. User-Defined Functions:o These functions are created by the programmer to perform specific tasks.o Example: A function to add two numbers(add(5, 10)), find factorial(fact()), displaya message(greet()), etc.Syntax of a Functionreturn_type function_name(parameter_list){// statementsreturn value; // used only if return_type is not void}• return_type → type of value returned(Example: int, float, char, void — e.g., int add() returns an integer)• function_name → name of the function(Example: add(), display(), calculateSum())• parameter_list → variables passed to the function (optional)(Example: (int a, int b) in int add(int a, int b))
Programming in C Unit-IV BCA Semester I10Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaUser-Defined FunctionsA user-defined function is a function written by the programmer to perform a custom task that isnot available in library functions.Example: add(5, 10); →A function to calculate the sum of two numbers.Need for User-Defined Functions1. They break the program into small, manageable modules (modularity).2. They allow the same code to be used many times without rewriting (reusability).3. They make debugging and maintenance easier.4. They improve the readability and clarity of the program.5. They reduce repetition by replacing repeated code with function calls.Structure of a User-Defined Function in CA user-defined function typically consists of three parts:
Programming in C Unit-IV BCA Semester I11Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca1.Function Declaration (Prototype)Tells the compiler about the function name, return type, and parameters before its actualdefinition.Syntax:return_type function_name(datatype arg1, datatype arg2, ...);Example:int add(int a, int b); // Function prototype2.Function DefinitionContains the actual body of the function where the actual code that performs the task.Syntax:return_type function_name(datatype arg1, datatype arg2, ...){// body of the functionreturn value;}Example:int add(int a, int b){int sum = a + b; // calculate sumreturn sum; // return sum to the calling function}3. Function CallIt is used to invoke the function from main() or another function.Syntax:variable = function_name(value1, value2,…);Example:int result;result = add(num1, num2); // calling the add() function
Programming in C Unit-IV BCA Semester I12Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaCategories of User-Defined FunctionsUser-defined functions in C can be classified into 4 types based on parameters and return type:1. Function with Arguments and Return Value(Takes parameters and returns a value) [int result = add (5, 10);]2.Function with No Arguments but Return Value(Takes parameters but does not return a value) [int result = add ();]3. Function with Arguments but No Return Value (Void Function)(Does not take parameters but returns a value) [ add (5, 10);]4. Function with No Arguments and No Return Value (Void Function)(Does not take parameters and does not return a value) [ add ();]1. Function with Arguments and Return Value• This type of user-defined function accepts arguments (inputs) from the calling functionand returns a value (output) back to the caller.• It is the most commonly used function type in C because it allows data to be passed intothe function and the result to be reused in different parts of the program.Example Program
Programming in C Unit-IV BCA Semester I13Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca2. Function with No Arguments but Return ValueThis type of function does not take any arguments from the calling function, but it returns avalue to the caller.• The input values (operands) are usually taken inside the function itself.• The computed result is then sent back to the main() function using the return statement.• Useful when you don’t want to pass arguments every time, but still need the result forfurther use.Example Program3. Function with Arguments but No Return Value (Void Function)This type of function takes arguments (inputs) from the calling function but does not returnany value.• Since it does not return a value, its return type is always void.• Useful when the function only performs an action (like displaying, printing, or updating)instead of sending results back.
Programming in C Unit-IV BCA Semester I14Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaExample Program4. Function with No Arguments and No Return Value (Void Function)This type of function does not take any input (arguments) and does not return any value.• Its return type is void.• It is generally used when the function performs a task internally, such as reading input,performing calculations, and displaying the output, without needing to return a result.Example Program
Programming in C Unit-IV BCA Semester I15Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaFunction CallFunction calling is the process of invoking a function by its name, passing required argumentsif any, so that the function executes its defined operations and returns control to the caller.Example of Function Callingint main(){// Function callsum = add(num1, num2);return 0;}Function Call MethodsIn C programming, functions can be called in two main ways depending on how the argumentsare passed to the function:1. Call by Value2. Call by ReferenceBoth methods determine whether the changes made to function parameters affect the originalvariables in the calling function.
Programming in C Unit-IV BCA Semester I16Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca1. Call by Value/NameDefinition:Call by Value is a function calling method in which a copy of the actual argument is passed tothe function. Changes made inside the function do not affect the original variable.• In Call by Value, the function works with a duplicate of the original data.• Used when you do not want the original value to change.• Safer because the original data remains unaltered.• Slower for large data because copies are made.Example 1: Swapping Two Numbers Using Call by ValueSample Output:
Programming in C Unit-IV BCA Semester I17Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaExample 2: Adding Two Numbers Using Call by ValueSample Output:Observation:• num1 and num2 remain unchanged because only copies were passed.Advantages of Call by Value:1. Original data is safe from accidental modification.2. Easy to implement and understand.3. Useful for small data types (int, float, char).
Programming in C Unit-IV BCA Semester I18Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaDisadvantages of Call by Value:1. Slower for large data types (arrays, structures) due to copying.2. Cannot modify the original variable inside the function.3. Extra memory may be used for copies of large data.2. Call by ReferenceDefinition:Call by Reference is a function calling method in which the address of the actual argument ispassed. Changes made inside the function directly affect the original variables.• In Call by Reference, the function works with the original data using its address.• Efficient for large data because no copying is required.• Useful when the function needs to modify the original variable.Example 1: Swapping Two Numbers Using Call by Reference
Programming in C Unit-IV BCA Semester I19Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaSample Output:Observation:• Values of num1 and num2 are swapped because their addresses were passed to thefunction.Example 2: Adding Two Numbers Using Call by ReferenceSample Output:
Programming in C Unit-IV BCA Semester I20Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaAdvantages of Call by Reference1. Modifies original data: Changes made inside the function affect the actual variable.2. Efficient for large data: No need to copy large data structures, saving memory and time.3. Useful for multiple outputs: A function can return multiple results using references.4. Memory efficient: Only addresses are passed, not entire data.Disadvantages of Call by Reference1. Changes original data: Accidental changes to the original variable can occur.2. Harder to debug: Errors may be difficult to trace because the function modifies originalvariables.3. Security risk: Passing sensitive data by reference can be risky if the function alters itunintentionally.4. Pointers required: Implementation uses pointers, which may be confusing for beginners.Comparison of Call by Value and Call by ReferenceCall by Value Call by Reference1. Passes a copy of the variable to the function.void swap(int num1, int num2)1. Passes the address of the variable to the function.void swap(int *num1, int *num2)2. Changes inside the function do not affect theoriginal variable.2. Changes inside the function affect the originalvariable.3. Uses extra memory because a copy of thevariable is created.3. More memory-efficient, no copying required.4. Safer; original data cannot be accidentallychanged.4. Slightly risky; pointers must be used carefully.5. Simple to implement and understand. 5. Slightly more complex due to pointer usage.6.Example: Swappingnum1=5, num2=7 → After function:num1=5, num2=76. Example: Swappingnum1=5, num2=7 → After function:num1=7, num2=57. Use when original data should not change. 7. Use when function needs to modify original data.*** *** ***

Recommended

PPTX
Programming in C sesion 2
PPT
Advanced pointers
PPTX
C Programming : Pointers and Arrays, Pointers and Strings
PPTX
Pointers and single &multi dimentionalarrays.pptx
PPTX
Algoritmos e Estruturas de Dados - Pointers
PPT
ch08.ppt
PPTX
UNIT 4 POINTERS.pptx pointers pptx for basic c language
PPT
presentation_pointers_1444076066_140676 (1).ppt
PPT
c program.ppt
PDF
Pointers.pdf
PDF
C Recursion, Pointers, Dynamic memory management
PDF
4th unit full
PPT
Pointers C programming
PPTX
C Programming : Pointers and Strings
PDF
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
PPT
pointers
PDF
Module 02 Pointers in C
PPT
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
PPT
l7-pointers.ppt
PPT
C Programming for Problem Solving programming Unit- 3
PPT
pointers CP Lecture.ppt
PPT
Pointers
PDF
PSPC--UNIT-5.pdf
PDF
CSEG1001 Unit 4 Functions and Pointers
PPTX
C Programming Unit-4
PDF
C programming session8
PDF
C programming session8
PPTX
Structured programming Unit-6-Strings-Unit-8-Pointer.pptx
PDF
First Semester BCA Fundamentals of Computers – Solved Question Paper (Kuvempu...
PDF
Data structure using C :UNIT-I Introduction to Data structures and Stacks BCA...

More Related Content

PPTX
Programming in C sesion 2
PPT
Advanced pointers
PPTX
C Programming : Pointers and Arrays, Pointers and Strings
PPTX
Pointers and single &multi dimentionalarrays.pptx
PPTX
Algoritmos e Estruturas de Dados - Pointers
PPT
ch08.ppt
PPTX
UNIT 4 POINTERS.pptx pointers pptx for basic c language
PPT
presentation_pointers_1444076066_140676 (1).ppt
Programming in C sesion 2
Advanced pointers
C Programming : Pointers and Arrays, Pointers and Strings
Pointers and single &multi dimentionalarrays.pptx
Algoritmos e Estruturas de Dados - Pointers
ch08.ppt
UNIT 4 POINTERS.pptx pointers pptx for basic c language
presentation_pointers_1444076066_140676 (1).ppt

Similar to Programming in C: UNIT-IV Pointers and User Defined Functions

PPT
c program.ppt
PDF
Pointers.pdf
PDF
C Recursion, Pointers, Dynamic memory management
PDF
4th unit full
PPT
Pointers C programming
PPTX
C Programming : Pointers and Strings
PDF
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
PPT
pointers
PDF
Module 02 Pointers in C
PPT
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
PPT
l7-pointers.ppt
PPT
C Programming for Problem Solving programming Unit- 3
PPT
pointers CP Lecture.ppt
PPT
Pointers
PDF
PSPC--UNIT-5.pdf
PDF
CSEG1001 Unit 4 Functions and Pointers
PPTX
C Programming Unit-4
PDF
C programming session8
PDF
C programming session8
PPTX
Structured programming Unit-6-Strings-Unit-8-Pointer.pptx
c program.ppt
Pointers.pdf
C Recursion, Pointers, Dynamic memory management
4th unit full
Pointers C programming
C Programming : Pointers and Strings
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
pointers
Module 02 Pointers in C
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
l7-pointers.ppt
C Programming for Problem Solving programming Unit- 3
pointers CP Lecture.ppt
Pointers
PSPC--UNIT-5.pdf
CSEG1001 Unit 4 Functions and Pointers
C Programming Unit-4
C programming session8
C programming session8
Structured programming Unit-6-Strings-Unit-8-Pointer.pptx

More from Kuvempu University

PDF
First Semester BCA Fundamentals of Computers – Solved Question Paper (Kuvempu...
PDF
Data structure using C :UNIT-I Introduction to Data structures and Stacks BCA...
PDF
Operating System (OS) :UNIT-I Introduction to Operating System BCA SEP SEM-II...
PDF
Database Management Systems(DBMS):UNIT-II Relational Data Model BCA SEP SEM ...
PDF
Design and Analysis of Algorithms(DAA): Unit-II Asymptotic Notations and Basi...
PDF
Database Management Systems(DBMS):UNIT-I Introduction to Database(DBMS) BCA S...
PDF
Solved First Semester B.C.A. C Programming Question Paper – Jan/Feb 2025
PDF
Programming in C: Unit-III: Arrays, Structures and Unions
PDF
Programming in C: Unit-II Input and Output, Operators, Control Structures/Sta...
PDF
Programming in C: Unit-I Problem solving with a Computer
PDF
Fundamentals of Computers(FOC): Unit-IV Word Processing, Presentation and Spr...
PDF
Fundamentals of Computers(FOC): Unit-III Operating Systems , Computer network...
PDF
Fundamentals of Computers(FOC): Unit-II Number Systems, Computer Codes and Lo...
PDF
BCA 1st Semester Fundamentals Solved Question Paper 44121
PDF
Fundamentals of Computers(FOC): UNIT-I Introduction to Computers
PDF
Unit – 4 Transducers and sensors:Definition and types of transducers
PDF
Unit – 3:Data Conversion and display
PDF
Unit – 2: Wave form generators and Filters
PDF
Artificial Neural Networks and Bayesian Learning
PDF
ELH -4.2: MACHINE LEARNING :supervised, unsupervised or reinforcement learning
First Semester BCA Fundamentals of Computers – Solved Question Paper (Kuvempu...
Data structure using C :UNIT-I Introduction to Data structures and Stacks BCA...
Operating System (OS) :UNIT-I Introduction to Operating System BCA SEP SEM-II...
Database Management Systems(DBMS):UNIT-II Relational Data Model BCA SEP SEM ...
Design and Analysis of Algorithms(DAA): Unit-II Asymptotic Notations and Basi...
Database Management Systems(DBMS):UNIT-I Introduction to Database(DBMS) BCA S...
Solved First Semester B.C.A. C Programming Question Paper – Jan/Feb 2025
Programming in C: Unit-III: Arrays, Structures and Unions
Programming in C: Unit-II Input and Output, Operators, Control Structures/Sta...
Programming in C: Unit-I Problem solving with a Computer
Fundamentals of Computers(FOC): Unit-IV Word Processing, Presentation and Spr...
Fundamentals of Computers(FOC): Unit-III Operating Systems , Computer network...
Fundamentals of Computers(FOC): Unit-II Number Systems, Computer Codes and Lo...
BCA 1st Semester Fundamentals Solved Question Paper 44121
Fundamentals of Computers(FOC): UNIT-I Introduction to Computers
Unit – 4 Transducers and sensors:Definition and types of transducers
Unit – 3:Data Conversion and display
Unit – 2: Wave form generators and Filters
Artificial Neural Networks and Bayesian Learning
ELH -4.2: MACHINE LEARNING :supervised, unsupervised or reinforcement learning

Recently uploaded

PDF
Lecture 7 Extra oral examination power point.pdf
PDF
Vertebrate Animals, reptiles, birds, mammals, amphibian, fish
PPT
DLC911_Feedback.ppt for grade 10 students
PPTX
UNIT -5 PPT PP-1.pptx buffer second year
PPT
Volcano and eruption ppt. for grade 8 students
PPTX
Physical Science SHS 24.2 Expanding Universe.pptx
PDF
Ch3-phys701-Maram optics for 1234566.pdf
PDF
The Bioland Tool for National Clearing-House Mechanism Portals: Introduction ...
PPTX
Copy of quiz bee questions for ISKOWIZARD-2019.pptx
PDF
Cognitive Architectures: Information Compression, Meaning-Making, and Drift i...
PPTX
Physical Science SHS 24.1 Special and General Theory of Relativity.pptx
PDF
Cosmic-Ray Bath in a Past Supernova Gives Birth to Earth-Like Planets
PDF
BP504T PHARMACOGNOSY UNIT 02 SUMMARY PART 01
PPTX
Surgical Affecation of Horn by Dr H M barot .pptx
PPTX
Advances in Monoclonal Antibody.pptxaaaaa
PDF
Amino acid cost and supply chain analysis for cultivated meat
PDF
glyoproteins and its types n o gpi linked pdf.pdf
PDF
Consequences of Undecidability in Physics on the Theory of Everything
PPTX
Epigenetics (Protein translation, Genetic Code, Steps involved in Translation...
PDF
CosmologywithVoidsfromtheNancyGraceRomanSpaceTelescope
Lecture 7 Extra oral examination power point.pdf
Vertebrate Animals, reptiles, birds, mammals, amphibian, fish
DLC911_Feedback.ppt for grade 10 students
UNIT -5 PPT PP-1.pptx buffer second year
Volcano and eruption ppt. for grade 8 students
Physical Science SHS 24.2 Expanding Universe.pptx
Ch3-phys701-Maram optics for 1234566.pdf
The Bioland Tool for National Clearing-House Mechanism Portals: Introduction ...
Copy of quiz bee questions for ISKOWIZARD-2019.pptx
Cognitive Architectures: Information Compression, Meaning-Making, and Drift i...
Physical Science SHS 24.1 Special and General Theory of Relativity.pptx
Cosmic-Ray Bath in a Past Supernova Gives Birth to Earth-Like Planets
BP504T PHARMACOGNOSY UNIT 02 SUMMARY PART 01
Surgical Affecation of Horn by Dr H M barot .pptx
Advances in Monoclonal Antibody.pptxaaaaa
Amino acid cost and supply chain analysis for cultivated meat
glyoproteins and its types n o gpi linked pdf.pdf
Consequences of Undecidability in Physics on the Theory of Everything
Epigenetics (Protein translation, Genetic Code, Steps involved in Translation...
CosmologywithVoidsfromtheNancyGraceRomanSpaceTelescope

Programming in C: UNIT-IV Pointers and User Defined Functions

  • 1.
    Programming in CUnit-IV BCA Semester I1Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaUnit-IV: Pointers and User Defined FunctionsPointers in CDefinition:• A pointer is a special variable that stores the memory address of another variable insteadof storing a direct value.• Pointers are very powerful in C because they allow:o Direct access to memoryo Efficient handling of arrayso Dynamic memory allocationo Function calls by reference (to modify actual values)Syntax:datatype *pointer_name;• datatype → Specifies the type of value the pointer will point to (e.g., int, float, char).• The symbol * → Indicates that the variable being declared is a pointer.Declaring PointersTo declare a pointer, we must specify the data type it will point to and use the symbol * beforethe pointer name.Examples:int *p; // pointer to an integerfloat *q; // pointer to a floatchar *ch; // pointer to a characterInitializing Pointers:Pointers must be assigned a valid memory address. This is done using the address-of operator(&).
  • 2.
    Programming in CUnit-IV BCA Semester I2Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaExample:int var = 10;int *ptr1 = &var; // ptr1 now holds the address of variable 'var'Accessing Address and Value Using Pointers:1. Getting the Address of a Variableint var = 10;printf("Address of var: %pn", &var);2. Accessing Value via Pointer (Dereferencing)int var = 10;int *ptr1 = &var;printf("Value of var: %dn", *ptr1); // Output: 103. Accessing Address via Pointerprintf("Address stored in pointer ptr1: %pn", ptr1);
  • 3.
    Programming in CUnit-IV BCA Semester I3Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaDemonstration of Pointers in C: Accessing and Modifying Variable Using PointerOUTPUT:
  • 4.
    Programming in CUnit-IV BCA Semester I4Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaPointer Arithmetic in CPointer arithmetic refers to performing operations on pointers to move across memory locations.It is mainly used when working with arrays, dynamic memory, and structures.Basic Pointer Arithmetic OperationsOperation Name OperationSymbolDescription Example Code Output /ResultPointerIncrementptr++ Moves the pointer tothe next elementint arr[3]={10,20,30};int *ptr=arr;ptr++;ptr → arr[1](value = 20)PointerDecrementptr-- Moves the pointer tothe previous elementint arr[3]={10,20,30};int *ptr=&arr[1];ptr--;ptr → arr[0](value = 10)Addition ofIntegerptr + n Moves pointerforward by nelementsint *ptr=arr;ptr = ptr + 2;ptr → arr[2](value = 30)Subtraction ofIntegerptr - n Moves pointerbackward by nelementsint *ptr=&arr[2];ptr = ptr - 1;ptr → arr[1](value = 20)PointerSubtractionptr1 - ptr2 Gives number ofelements between twopointers (same arrayonly)int *p1=&arr[2];int *p2=&arr[0];int diff = p1 - p2;diff = 2Pointer Addition(Invalid)ptr1 + ptr2 Adding two pointers isnot allowed— CompilationErrorPointerMultiplication(Invalid)ptr1 * ptr2 Multiplying pointers isnot allowed— CompilationErrorNotes:1. Pointer arithmetic works based on data type size, not bytes.Example:int *p; // int = 4 bytesp++; // moves 4 bytes ahead
  • 5.
    Programming in CUnit-IV BCA Semester I5Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca2. Adding an integer to a pointer is allowed; adding/multiplying two pointers is notallowed.Example:p = p + 2; // validp = p + p; // invalidp = p * p; // invalid3. Subtracting two pointers gives distance in elements.Example:int arr[5];int *p1 = &arr[3];int *p2 = &arr[1];int d = p1 - p2; // d = 24. Pointer multiplication is not allowed; multiply the integer before adding.Example:p = p + (3); // move 3 positions
  • 6.
    Programming in CUnit-IV BCA Semester I6Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaExample 1: Increment and DecrementExample 2: Using ptr + n• Adding an integer to a pointer• We cannot add two pointers, but we can add an integer to a pointer.ptr1 + ptr2; // ❌ Error• When we do ptr + n, the pointer moves n elements forward, not n bytes.
  • 7.
    Programming in CUnit-IV BCA Semester I7Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaExample 3: Pointer DifferenceExample 4: Pointer Scaling• Direct multiplication of pointers is not allowed.We cannot do ptr * n or ptr1 * ptr2 in C. // ❌ Error• If we want to scale memory movement, we multiply an integer before adding to thepointer:ptr = base + (3 * n); // valid: moves 3*n elements ahead
  • 8.
    Programming in CUnit-IV BCA Semester I8Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaAdvantages of Pointers1. Pointers save memory and time by passing addresses instead of copying data.2. They are required for dynamic memory allocation using malloc(), calloc(), etc.3. Pointers make array and string handling easier and faster.4. They allow functions to modify values directly using pass-by-reference.5. Pointers help in creating dynamic data structures like linked lists and trees.6. They allow direct access to memory and hardware-level operations.Disadvantages of Pointers1. Pointer-based programs are harder to understand and debug.2. Dangling pointers can cause crashes and unpredictable behavior.3. Forgetting to free memory leads to memory leaks.4. Incorrect pointer arithmetic may cause errors or segmentation faults.5. Misuse of pointers can cause security issues like buffer overflows.Applications of Pointers1. Pointers are used for dynamic memory allocation using malloc(), calloc(), and free().2. They are used to access and manipulate arrays and strings efficiently.3. Pointers help in passing arguments by reference to functions.4. They are essential for creating linked lists, stacks, queues, trees, and graphs.5. Pointers are used in system programming to access hardware and memory locationsdirectly.6. They are used for buffer management in files, networks, and I/O operations.7. Function pointers are used to implement callbacks and event-driven programming.8. Pointers support dynamic structures where size can grow or shrink at runtime.
  • 9.
    Programming in CUnit-IV BCA Semester I9Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaFunction in CA function in C is a block of code that performs a specific task and can be called wheneverneeded in a program.• A function may take inputs (called parameters or arguments) and may return a value tothe calling function.• Functions make a program modular, reusable, and easy to debug.Types of Functions in C:1. Predefined (Library) Functions:o These functions are already provided by C.o Examples: printf(), scanf(), sqrt(), strlen()2. User-Defined Functions:o These functions are created by the programmer to perform specific tasks.o Example: A function to add two numbers(add(5, 10)), find factorial(fact()), displaya message(greet()), etc.Syntax of a Functionreturn_type function_name(parameter_list){// statementsreturn value; // used only if return_type is not void}• return_type → type of value returned(Example: int, float, char, void — e.g., int add() returns an integer)• function_name → name of the function(Example: add(), display(), calculateSum())• parameter_list → variables passed to the function (optional)(Example: (int a, int b) in int add(int a, int b))
  • 10.
    Programming in CUnit-IV BCA Semester I10Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaUser-Defined FunctionsA user-defined function is a function written by the programmer to perform a custom task that isnot available in library functions.Example: add(5, 10); →A function to calculate the sum of two numbers.Need for User-Defined Functions1. They break the program into small, manageable modules (modularity).2. They allow the same code to be used many times without rewriting (reusability).3. They make debugging and maintenance easier.4. They improve the readability and clarity of the program.5. They reduce repetition by replacing repeated code with function calls.Structure of a User-Defined Function in CA user-defined function typically consists of three parts:
  • 11.
    Programming in CUnit-IV BCA Semester I11Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca1.Function Declaration (Prototype)Tells the compiler about the function name, return type, and parameters before its actualdefinition.Syntax:return_type function_name(datatype arg1, datatype arg2, ...);Example:int add(int a, int b); // Function prototype2.Function DefinitionContains the actual body of the function where the actual code that performs the task.Syntax:return_type function_name(datatype arg1, datatype arg2, ...){// body of the functionreturn value;}Example:int add(int a, int b){int sum = a + b; // calculate sumreturn sum; // return sum to the calling function}3. Function CallIt is used to invoke the function from main() or another function.Syntax:variable = function_name(value1, value2,…);Example:int result;result = add(num1, num2); // calling the add() function
  • 12.
    Programming in CUnit-IV BCA Semester I12Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaCategories of User-Defined FunctionsUser-defined functions in C can be classified into 4 types based on parameters and return type:1. Function with Arguments and Return Value(Takes parameters and returns a value) [int result = add (5, 10);]2.Function with No Arguments but Return Value(Takes parameters but does not return a value) [int result = add ();]3. Function with Arguments but No Return Value (Void Function)(Does not take parameters but returns a value) [ add (5, 10);]4. Function with No Arguments and No Return Value (Void Function)(Does not take parameters and does not return a value) [ add ();]1. Function with Arguments and Return Value• This type of user-defined function accepts arguments (inputs) from the calling functionand returns a value (output) back to the caller.• It is the most commonly used function type in C because it allows data to be passed intothe function and the result to be reused in different parts of the program.Example Program
  • 13.
    Programming in CUnit-IV BCA Semester I13Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca2. Function with No Arguments but Return ValueThis type of function does not take any arguments from the calling function, but it returns avalue to the caller.• The input values (operands) are usually taken inside the function itself.• The computed result is then sent back to the main() function using the return statement.• Useful when you don’t want to pass arguments every time, but still need the result forfurther use.Example Program3. Function with Arguments but No Return Value (Void Function)This type of function takes arguments (inputs) from the calling function but does not returnany value.• Since it does not return a value, its return type is always void.• Useful when the function only performs an action (like displaying, printing, or updating)instead of sending results back.
  • 14.
    Programming in CUnit-IV BCA Semester I14Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaExample Program4. Function with No Arguments and No Return Value (Void Function)This type of function does not take any input (arguments) and does not return any value.• Its return type is void.• It is generally used when the function performs a task internally, such as reading input,performing calculations, and displaying the output, without needing to return a result.Example Program
  • 15.
    Programming in CUnit-IV BCA Semester I15Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaFunction CallFunction calling is the process of invoking a function by its name, passing required argumentsif any, so that the function executes its defined operations and returns control to the caller.Example of Function Callingint main(){// Function callsum = add(num1, num2);return 0;}Function Call MethodsIn C programming, functions can be called in two main ways depending on how the argumentsare passed to the function:1. Call by Value2. Call by ReferenceBoth methods determine whether the changes made to function parameters affect the originalvariables in the calling function.
  • 16.
    Programming in CUnit-IV BCA Semester I16Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca1. Call by Value/NameDefinition:Call by Value is a function calling method in which a copy of the actual argument is passed tothe function. Changes made inside the function do not affect the original variable.• In Call by Value, the function works with a duplicate of the original data.• Used when you do not want the original value to change.• Safer because the original data remains unaltered.• Slower for large data because copies are made.Example 1: Swapping Two Numbers Using Call by ValueSample Output:
  • 17.
    Programming in CUnit-IV BCA Semester I17Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaExample 2: Adding Two Numbers Using Call by ValueSample Output:Observation:• num1 and num2 remain unchanged because only copies were passed.Advantages of Call by Value:1. Original data is safe from accidental modification.2. Easy to implement and understand.3. Useful for small data types (int, float, char).
  • 18.
    Programming in CUnit-IV BCA Semester I18Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaDisadvantages of Call by Value:1. Slower for large data types (arrays, structures) due to copying.2. Cannot modify the original variable inside the function.3. Extra memory may be used for copies of large data.2. Call by ReferenceDefinition:Call by Reference is a function calling method in which the address of the actual argument ispassed. Changes made inside the function directly affect the original variables.• In Call by Reference, the function works with the original data using its address.• Efficient for large data because no copying is required.• Useful when the function needs to modify the original variable.Example 1: Swapping Two Numbers Using Call by Reference
  • 19.
    Programming in CUnit-IV BCA Semester I19Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaSample Output:Observation:• Values of num1 and num2 are swapped because their addresses were passed to thefunction.Example 2: Adding Two Numbers Using Call by ReferenceSample Output:
  • 20.
    Programming in CUnit-IV BCA Semester I20Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bcaAdvantages of Call by Reference1. Modifies original data: Changes made inside the function affect the actual variable.2. Efficient for large data: No need to copy large data structures, saving memory and time.3. Useful for multiple outputs: A function can return multiple results using references.4. Memory efficient: Only addresses are passed, not entire data.Disadvantages of Call by Reference1. Changes original data: Accidental changes to the original variable can occur.2. Harder to debug: Errors may be difficult to trace because the function modifies originalvariables.3. Security risk: Passing sensitive data by reference can be risky if the function alters itunintentionally.4. Pointers required: Implementation uses pointers, which may be confusing for beginners.Comparison of Call by Value and Call by ReferenceCall by Value Call by Reference1. Passes a copy of the variable to the function.void swap(int num1, int num2)1. Passes the address of the variable to the function.void swap(int *num1, int *num2)2. Changes inside the function do not affect theoriginal variable.2. Changes inside the function affect the originalvariable.3. Uses extra memory because a copy of thevariable is created.3. More memory-efficient, no copying required.4. Safer; original data cannot be accidentallychanged.4. Slightly risky; pointers must be used carefully.5. Simple to implement and understand. 5. Slightly more complex due to pointer usage.6.Example: Swappingnum1=5, num2=7 → After function:num1=5, num2=76. Example: Swappingnum1=5, num2=7 → After function:num1=7, num2=57. Use when original data should not change. 7. Use when function needs to modify original data.*** *** ***

[8]ページ先頭

©2009-2025 Movatter.jp