Movatterモバイル変換


[0]ホーム

URL:


37 views

Programming in C: Unit-III: Arrays, Structures and Unions

Unit-3Arrays - One Dimensional arrays - Declaration, Initialization and Memoryrepresentation. Two Dimensional arrays - Declaration, Initialization and Memoryrepresentation.Structures - Structure Definition, Advantages of Structure, declaring , initializationaccessing structure members. Unions - Union definition,declaration,initialization.difference between Structures and Unions

Embed presentation

Download to read offline
Programming in C Unit-III 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-III: Arrays, Structures and UnionsIntroduction• In C programming, data handling requires grouping related elements and managingcollections of values.• arrays, structures, and unions, which provide systematic ways to organise and manage data.• These concepts are essential for writing efficient, structured, and memory-optimized Cprograms, useful in handling tasks like record management and matrix operations.I)ArraysIntroduction to Arrays• When handling many similar data values, using separate variables increases complexity.• To simplify this, C provides arrays, which allow storing multiple values of the same datatype in a single variable.• Arrays enable efficient storage and easy access using an index, making them ideal forstoring items like student marks or employee salaries.
Programming in C Unit-III 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/bcaDefinition of an Array• An array is a finite, ordered, homogeneous collection of elements stored in contiguousmemory locations, accessed using a common name and an index.• It is a linear static data structure, meaning its size is fixed during declaration.Examples of Arrays1.Integer Arrayint numArray[12] = {11, 9, 17, 89, 1, 90, 19, 5, 3, 23, 43, 99};2. Float Arrayfloat marks[5] = {88.5, 76.0, 92.3, 69.5, 80.0};3.Character Array (String)char subject[8] = "Computer";Characteristics of Arrays1. Arrays store multiple elements of the same data type.2. All elements are placed in contiguous (continuous) memory locations.3. Each element is accessed using an index, with C following 0-based indexing.4. The size of an array is fixed at the time of declaration and cannot be changed later.5. Arrays provide fast and direct access to elements through indexing.Need for Arrays1. Arrays store many values of the same data type efficiently.2. They remove the need to declare multiple separate variables.3. Arrays provide quick access to elements using indices.4. They make programs simpler and easier to manage.5. Arrays help in systematic processing of large data sets.
Programming in C Unit-III 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/bcaOperations on an Array1. Traversing: Accessing and processing each element of the array sequentially.2. Searching: Finding whether a particular element exists in the array.3. Sorting: Arranging array elements in a specific order (ascending or descending).4. Inserting: Adding a new element at a specified position in the array.5. Deleting: Removing an element from a specified position in the array.Applications of Arrays1. Used for storing and processing lists of data such as marks, salaries, or ages.2. Helpful in representing mathematical vectors, matrices, and tables.3. Widely used in searching and sorting algorithms.4. Form the basis for data structures like stacks, queues, and graphs.Advantages of Arrays1. Code optimisation: Arrays allow accessing data with fewer lines of code.2. Easy traversal: Elements can be easily processed using loops.3. Easy sorting: Sorting operations can be performed with simple code.4. Random access: Any element can be accessed directly using its index.5. Supports data structures: Arrays make it easy to implement structures like stacks andqueues.6. Improves readability: Programs become more organised and easier to understand.Disadvantages of Arrays1. Fixed size: The array size cannot be changed during program execution.2. Costly insertion/deletion: Adding or removing elements requires shifting, which is time-consuming.3. Memory wastage: Unused allocated space leads to memory loss.4. Homogeneous data only: Arrays can store only one data type at a time
Programming in C Unit-III 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/bcaClassification of ArraysIn C programming, arrays are classified mainly based on their dimensionality. There are two typesof arrays:I) One Dimensional arrays (1-D arrays)DefinitionA one-dimensional array is a collection of elements of the same data type arranged in a singlerow (linear form) and stored in contiguous memory locations.a)1-D Array Declaration in C• To declare an array in C, we use square brackets [] after the array name.• The size of the array (number of elements) is written inside the brackets.Syntax:data_type array_name[size];➢ data_type → type of elements (int, float, char, etc.)➢ array_name → name of the array➢ size → number of elementsExamples:int numbers[10]; // array of 10 integersfloat marks[5]; // array of 5 floatschar name[20]; // array of 20 characters (strings)
Programming in C Unit-III 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/bcab) Types of 1-D Array Initialization in C1. Compile-time (static)InitializationValues are assigned at the time of declaration.int marks[5] = {90, 85, 78, 92, 88};2. Partial InitializationOnly some values are given; the remaining are set to 0.int numbers[5] = {1, 2}; // stores 1, 2, 0, 0, 03. Implicit Size InitializationThe size is automatically determined by the number of elements.int nums[] = {10, 20, 30, 40};4. Runtime (Dynamic) InitializationValues are entered by the user or assigned during program execution.int arr[5];for(int i = 0; i < 5; i++){scanf("%d", &arr[i]);}c) Accessing Elements of a 1-D ArrayUse the index (starting from 0) to read an element:#include <stdio.h>int main(){int arr[5] = {10, 20, 30, 40, 50}; // Compile-time initialization// Access elementsprintf("First element: %dn", arr[0]); //10printf("Third element: %dn", arr[2]); //30return 0;}
Programming in C Unit-III 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/bcad) Updating Elements of a 1-D ArrayAssign a new value to an element using its index:#include <stdio.h>int main(){int arr[5] = {10, 20, 30, 40, 50};// Update elementsarr[1] = 25; // Update second elementarr[4] = 55; // Update fifth element// Display updated arrayprintf("nUpdated Array Elements:n");for(int i = 0; i < 5; i++){printf("arr[%d] = %dn", i, arr[i]);}return 0;}e) Memory Representation of 1-D Array• In C, the elements of an array are stored in continuous memory locations.• Each element is accessed using an index, which starts from 0.• The base address refers to the memory location of the first element.• The address of the i-th element is calculated as:Address of element = Base address + (i × size of each element)Example:• If int marks[5] = {90, 97, 95, 99, 100}; is stored at base address 3020 and each integertakes 2 bytes (depends on system), memory allocation will be:
Programming in C Unit-III 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/bcaII) Multidimensional Arrays• In C, arrays store multiple values of the same data type.• Multidimensional arrays represent data in tables, grids, or matrices (e.g., student marks,chessboard, image pixels).• A multidimensional array is an array of arrays, created with more than one dimension.• Common types include 2-D, 3-D, and higher-dimensional arrays, with 2-D arrays being themost common (rows and columns).Syntax for declaration:data_type array_name[size1][size2]........[sizeN];Examples:int matrix[3][3]; // 2-D array (3 rows, 3 columns)int cube[3][3][3]; // 3-D array (like a cube of data)Two-Dimensional (2-D) ArraysDefinitionA two-dimensional (2-D) array is a collection of elements arranged in rows and columns,where each element is accessed using two indices.• It is used to store data in the form of a table or matrix with rows and columns.
Programming in C Unit-III 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/bcaa) Declaration of 2-D ArraysTo declare a 2-D array, we use two sets of square brackets [ ] [ ]:Syntax:data_type array_name[rows][columns];• data_type → type of elements (int, float, char, etc.)• array_name → name of the array• rows, columns → size (number of rows and columns)Example:int matrix[3][3]; // 3x3 integer matrix, this can store 3 × 3 = 09 elements.float marks[2][5]; // 2 rows and 5 columns of floats, this can store 2 × 5 = 10 elements.char name[4][20]; // 4 strings, each of max length 20, his can store 4 × 20 = 80 elements.b) Types of 2-D Array Initialization1. Compile-time InitializationValues assigned during declaration.int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };2. Partial InitializationRemaining elements are set to 0.int mat[2][3] = { {1, 2}, {4} }; // stores: {1,2,0} and {4,0,0}3. Implicit Row Size InitializationNumber of rows can be left empty (columns must be given).int mat[][3] = { {1, 2, 3}, {4, 5, 6} };
Programming in C Unit-III 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/bca4. Runtime (Dynamic) InitializationValues entered by user at runtime.int mat[2][3];for(int i = 0; i < 2; i++){for(int j = 0; j < 3; j++){scanf("%d", &mat[i][j]);}}c) Accessing Elements of a 2-D ArrayUse row index and column index.#include <stdio.h>int main(){int mat[2][3] = { {10, 20, 30}, {40, 50, 60} };printf("Element at [0][1] = %dn", mat[0][1]); // 20printf("Element at [1][2] = %dn", mat[1][2]); // 60return 0;}
Programming in C Unit-III 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/bcad) Updating Elements of a 2-D ArrayAssign new values using row and column index.#include <stdio.h>int main(){int mat[2][3] = { {10, 20, 30}, {40, 50, 60} };// Update elementsmat[0][1] = 25; // Update row 0, col 1mat[1][2] = 65; // Update row 1, col 2// Display updated matrixprintf("nUpdated Matrix:n");for(int i = 0; i < 2; i++){for(int j = 0; j < 3; j++){printf("%d ", mat[i][j]);}printf("n");}return 0;}
Programming in C Unit-III 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/bcae) Memory representation of 2-D Arrayint arr[3][3] = { {24, 15, 34}, {26, 134, 194}, {67, 23, 345} } is stored in memory asHere, the base address is the address of the 2-D array or the address of the first object stored in the2-D array. The memory address increases by 4 bytes (the size of the int data type).II) StructuresIntroduction:• A structure in C is a user-defined data type that groups variables of different types undera single name.• It is useful for representing real-world entities, such as student details or textbookinformation.Definition:A structure is a collection of heterogeneous variables under a single name, enabling logicalrepresentation of real-world entities and improving program organisation.Syntax:• A structure is defined using the keyword struct.• The items in the structure are called its members and they can be of any valid data type.struct StructureName{data_type member1;data_type member2;...data_type memberN;};
Programming in C Unit-III 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/bcaExample:1Memory Size of a Structure:• The total memory size of a structure is the sum of the sizes of its members plus anypadding added by the compiler for alignment.Example:2struct textbook{char name[40];char author[20];int pages;};
Programming in C Unit-III 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/bcaApplications of Structures1. Representing real-world entities like students, employees, books, or patients withmultiple attributes.2. Managing records in databases or file systems.3. Creating arrays of structures for handling collections of related data.4. Implementing complex data structures like linked lists, stacks, and queues.5. Organising data for file handling and data exchange between functions.Need for Structures/ Advantages of Structures1. To group different data types into a single unit.2. To model real-world entities like students, employees, or books with multiple attributes.3. To improve program readability and logical organisation of data.4. To reduce program complexity and enhance reusability.5. To serve as a foundation for advanced concepts like arrays of structures, pointers tostructures, and file handling.Disadvantages of Structures1. Cannot directly perform arithmetic or operations on entire structures.2. Memory allocation is fixed and may lead to wastage if not used efficiently.3. Accessing individual members requires explicit member names.4. Structures cannot contain operations (functions) directly like objects in OOP.5. Handling very large structures can increase program complexity and execution time.
Programming in C Unit-III 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/bcaDeclaring Structure VariablesStructure variables can be declared in two ways:1)Method 1 – After structure definition:struct Student{int rollno;char name[20];float marks;};struct Student s1, s2; // declaring variables2)Method 2 – Along with structure definition:struct Student{int rollno;char name[20];float marks;} s1, s2;Initializing Structure Members1) Initialize a structure at the time of declaration:#include <stdio.h>// Define the structurestruct Student{int rollno;char name[20];float marks;};
Programming in C Unit-III 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/bcaint main(){// Declare and initialize structure variablesstruct Student s1 = {101, "Arun", 85.5};struct Student s2 = {102, "Riya", 92.0};// Display values of s1printf("Student 1 Details:n");printf("Roll Number: %dn", s1.rollno);printf("Name: %sn", s1.name);printf("Marks: %.2fnn", s1.marks);// Display values of s2printf("Student 2 Details:n");printf("Roll Number: %dn", s2.rollno);printf("Name: %sn", s2.name);printf("Marks: %.2fn", s2.marks);return 0;}2) assign values later:s1.rollno = 102;strcpy(s1.name, "Meena"); // for strings use strcpy()s1.marks = 90.0;Accessing Structure MembersMembers are accessed using the dot operator (.)
Programming in C Unit-III 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/bcaIII) UnionsIntroduction:• A union in C is a user-defined data type similar to a structure, but all members sharethe same memory location.• Only one member can hold a value at a time.Definition:A union is a C data type where all members share the same memory location, allowing only oneactive value at a time.Memory Allocation:• The memory allocated for a union equals the size of its largest member.• Assigning a value to one member overwrites the previous value stored in the unionApplications of Unions1. Save memory in programs with limited resources.2. Share memory in embedded systems and device drivers.3. Use the same data in different ways, like bit fields or packets.4. Access the same memory as different data types (type punning).5. Help in designing compilers and operating systems efficiently.Advantages/Need of Unions in C1. Efficient memory usage, as all members share the same memory.2. Handle different data types at different times using the same memory.3. Useful in embedded systems and low-level programming where memory is limited.4. Facilitates type conversion, e.g., accessing the same data as integer or float.5. Optimized storage when only one value is needed at a time.
Programming in C Unit-III 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/bcaDisadvantages of Unions1. Only one member can hold a value at a time.2. Assigning a value to one member overwrites the previous value.3. Cannot store multiple values simultaneously.4. Accessing the wrong member may lead to unexpected results.5. Not suitable when multiple data elements need to be stored concurrently.Declaration of UnionUnions are declared using the keyword union.Syntax:union UnionName{data_type member1;data_type member2;...data_type memberN;};Initialization of Union1)Method 1 – At the time of declaration:#include <stdio.h>// Define the unionunion Data{int i;float f;char str[20];};
Programming in C Unit-III 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/bcaint main(){// Method 1: Initialize at the time of declarationunion Data d1 = {10}; // Initializes the first member 'i'// Access and display the valueprintf("Value of i: %dn", d1.i);return 0;}2) Method 2 – Assigning later:int main(){// Declare a union variableunion Data d2;// Assign integer valued2.i = 10;printf("After assigning integer:ni = %dnn", d2.i);// Assign float valued2.f = 5.5;printf("After assigning float:nf = %.2fnn", d2.f);// Assign string valuestrcpy(d2.str, "BCA");printf("After assigning string:nstr = %sn", d2.str);return 0;}
Programming in C Unit-III 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/bcaComparison of Arrays, Structures, and Unions in CArrays Structures Unions1. Store multiple values ofthe same data type.1. Can store multiplevariables of different datatypes.1. Can store multiple variables ofdifferent types, but only one valueat a time.2. Size is fixed at the timeof declaration.2. Size depends on allmembers combined.2. Size is equal to the largestmember.3. Elements are accessedusing indices.3. Members are accessedusing the dot (.) operator.3. Members are accessed usingthe dot (.) operator.4. All elements occupyseparate memory locations.4. Each member has itsown memory location.4. All members share the samememory location.5. Used for storing lists,matrices, or sequences ofsimilar data.5. Used to represent real-world entities logically.5. Used for memory-efficientstorage where only one value isneeded at a time.6. Supports traversal,searching, and sortingoperations.6. Can be nested orcombined with arrays andpointers.6. Efficient in low-memoryapplications like embeddedsystems.7. Applications: storingstudent marks, employeesalaries, matrices.Applications: storingstudent records, bookdetails, employee profiles.Applications: type punning,sharing memory in embeddedsystems, interpreting data inmultiple formats.*** *** ***

Recommended

PPTX
Arrays & Strings
DOCX
arrays.docx
PPT
Arrays
PDF
Arrays
PPT
SPL Lecture Slide 08- Array sing and Multi dimentional.ppt
PDF
Arrays In C- Logic Development Programming
PPTX
Unit4pptx__2024_11_ 11_10_16_09.pptx
PPTX
Array 2 hina
PPT
Arrays Basics
PPTX
Module_3_Arrays - Updated.pptx............
PPTX
PDF
PPTX
10 arrays and pointers.pptx for array and pointer
PPTX
Programming fundamentals week 12.pptx
 
PPTX
unit 2.pptx
PPTX
Arrays.pptx
PPTX
Chapter 13.pptx
PPTX
Basic Arrays in C Programming Language I
PDF
Array
PPTX
UNIT-5_Array in c_part1.pptx
PPTX
Data structure.pptx
PDF
Cunit3.pdf
PPT
UNIT_II_part_2_arrays.ppt UNIT_II_part_2_arrays.ppt
PPTX
Arrays.pptx
PPTX
vnd.openxmlformats-officedocument.presentationml.presentation&rendition=1.pptx
PDF
Unit 3 How strings and arrays work in Programming.pdf
PPTX
CSE 1102 - Lecture 6 - Arrays in C .pptx
PPTX
Arrays basics
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...

More Related Content

PPTX
Arrays & Strings
DOCX
arrays.docx
PPT
Arrays
PDF
Arrays
PPT
SPL Lecture Slide 08- Array sing and Multi dimentional.ppt
PDF
Arrays In C- Logic Development Programming
PPTX
Unit4pptx__2024_11_ 11_10_16_09.pptx
PPTX
Array 2 hina
Arrays & Strings
arrays.docx
Arrays
Arrays
SPL Lecture Slide 08- Array sing and Multi dimentional.ppt
Arrays In C- Logic Development Programming
Unit4pptx__2024_11_ 11_10_16_09.pptx
Array 2 hina

Similar to Programming in C: Unit-III: Arrays, Structures and Unions

PPT
Arrays Basics
PPTX
Module_3_Arrays - Updated.pptx............
PPTX
PDF
PPTX
10 arrays and pointers.pptx for array and pointer
PPTX
Programming fundamentals week 12.pptx
 
PPTX
unit 2.pptx
PPTX
Arrays.pptx
PPTX
Chapter 13.pptx
PPTX
Basic Arrays in C Programming Language I
PDF
Array
PPTX
UNIT-5_Array in c_part1.pptx
PPTX
Data structure.pptx
PDF
Cunit3.pdf
PPT
UNIT_II_part_2_arrays.ppt UNIT_II_part_2_arrays.ppt
PPTX
Arrays.pptx
PPTX
vnd.openxmlformats-officedocument.presentationml.presentation&rendition=1.pptx
PDF
Unit 3 How strings and arrays work in Programming.pdf
PPTX
CSE 1102 - Lecture 6 - Arrays in C .pptx
PPTX
Arrays basics
Arrays Basics
Module_3_Arrays - Updated.pptx............
10 arrays and pointers.pptx for array and pointer
Programming fundamentals week 12.pptx
 
unit 2.pptx
Arrays.pptx
Chapter 13.pptx
Basic Arrays in C Programming Language I
Array
UNIT-5_Array in c_part1.pptx
Data structure.pptx
Cunit3.pdf
UNIT_II_part_2_arrays.ppt UNIT_II_part_2_arrays.ppt
Arrays.pptx
vnd.openxmlformats-officedocument.presentationml.presentation&rendition=1.pptx
Unit 3 How strings and arrays work in Programming.pdf
CSE 1102 - Lecture 6 - Arrays in C .pptx
Arrays basics

More from Kuvempu University

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-IV Pointers and User Defined Functions
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
PDF
ELS: 2.4.1 POWER ELECTRONICS
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-IV Pointers and User Defined Functions
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
ELS: 2.4.1 POWER ELECTRONICS

Recently uploaded

PDF
Navigating SEC Regulations for Crypto Exchanges Preparing for a Compliant Fut...
PPTX
AI Clinic Management Software for Pulmonology Clinics Bringing Clarity, Contr...
PPTX
Binance Smart Chain Development Guide.pptx
PDF
Advanced Prompt Engineering: The Art and Science
PPTX
Deep Dive into Durable Functions, presented at Cloudbrew 2025
PDF
Intelligent CRM for Insurance Brokers: Managing Clients with Precision
PPTX
Lecture 3 - Scheduling - Operating System
PDF
Virtual Study Circles Innovative Ways to Collaborate Online.pdf
PDF
What Is A Woman (WIAW) Token – Smart Contract Security Audit Report by EtherA...
PDF
API_SECURITY CONSULTANCY SERVICES IN USA
PPTX
GDS Integration Solution | GDS Integration Service
PDF
Cloud-Based Underwriting Software for Insurance
PDF
Influence Without Power - Why Empathy is Your Best Friend.pdf
PDF
INTRODUCTION TO DATABASES, MYSQL, MS ACCESS, PHARMACY DRUG DATABASE.pdf
PDF
How Does AI Improve Location-Based Mobile App Development for Businesses.pdf
PPTX
Struggling with Pentaho Limitations How Helical Insight Solves Them.pptx
PDF
Combinatorial Interview Problems with Backtracking Solutions - From Imperativ...
PDF
Constraints First - Why Our On-Prem Ticketing System Starts With Limits, Not ...
PDF
Blueprint to build quality before the code exists - StackConnect Milan 2025
PDF
KoderXpert – Odoo, Web & AI Solutions for Growing Businesses
Navigating SEC Regulations for Crypto Exchanges Preparing for a Compliant Fut...
AI Clinic Management Software for Pulmonology Clinics Bringing Clarity, Contr...
Binance Smart Chain Development Guide.pptx
Advanced Prompt Engineering: The Art and Science
Deep Dive into Durable Functions, presented at Cloudbrew 2025
Intelligent CRM for Insurance Brokers: Managing Clients with Precision
Lecture 3 - Scheduling - Operating System
Virtual Study Circles Innovative Ways to Collaborate Online.pdf
What Is A Woman (WIAW) Token – Smart Contract Security Audit Report by EtherA...
API_SECURITY CONSULTANCY SERVICES IN USA
GDS Integration Solution | GDS Integration Service
Cloud-Based Underwriting Software for Insurance
Influence Without Power - Why Empathy is Your Best Friend.pdf
INTRODUCTION TO DATABASES, MYSQL, MS ACCESS, PHARMACY DRUG DATABASE.pdf
How Does AI Improve Location-Based Mobile App Development for Businesses.pdf
Struggling with Pentaho Limitations How Helical Insight Solves Them.pptx
Combinatorial Interview Problems with Backtracking Solutions - From Imperativ...
Constraints First - Why Our On-Prem Ticketing System Starts With Limits, Not ...
Blueprint to build quality before the code exists - StackConnect Milan 2025
KoderXpert – Odoo, Web & AI Solutions for Growing Businesses

Programming in C: Unit-III: Arrays, Structures and Unions

  • 1.
    Programming in CUnit-III 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-III: Arrays, Structures and UnionsIntroduction• In C programming, data handling requires grouping related elements and managingcollections of values.• arrays, structures, and unions, which provide systematic ways to organise and manage data.• These concepts are essential for writing efficient, structured, and memory-optimized Cprograms, useful in handling tasks like record management and matrix operations.I)ArraysIntroduction to Arrays• When handling many similar data values, using separate variables increases complexity.• To simplify this, C provides arrays, which allow storing multiple values of the same datatype in a single variable.• Arrays enable efficient storage and easy access using an index, making them ideal forstoring items like student marks or employee salaries.
  • 2.
    Programming in CUnit-III 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/bcaDefinition of an Array• An array is a finite, ordered, homogeneous collection of elements stored in contiguousmemory locations, accessed using a common name and an index.• It is a linear static data structure, meaning its size is fixed during declaration.Examples of Arrays1.Integer Arrayint numArray[12] = {11, 9, 17, 89, 1, 90, 19, 5, 3, 23, 43, 99};2. Float Arrayfloat marks[5] = {88.5, 76.0, 92.3, 69.5, 80.0};3.Character Array (String)char subject[8] = "Computer";Characteristics of Arrays1. Arrays store multiple elements of the same data type.2. All elements are placed in contiguous (continuous) memory locations.3. Each element is accessed using an index, with C following 0-based indexing.4. The size of an array is fixed at the time of declaration and cannot be changed later.5. Arrays provide fast and direct access to elements through indexing.Need for Arrays1. Arrays store many values of the same data type efficiently.2. They remove the need to declare multiple separate variables.3. Arrays provide quick access to elements using indices.4. They make programs simpler and easier to manage.5. Arrays help in systematic processing of large data sets.
  • 3.
    Programming in CUnit-III 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/bcaOperations on an Array1. Traversing: Accessing and processing each element of the array sequentially.2. Searching: Finding whether a particular element exists in the array.3. Sorting: Arranging array elements in a specific order (ascending or descending).4. Inserting: Adding a new element at a specified position in the array.5. Deleting: Removing an element from a specified position in the array.Applications of Arrays1. Used for storing and processing lists of data such as marks, salaries, or ages.2. Helpful in representing mathematical vectors, matrices, and tables.3. Widely used in searching and sorting algorithms.4. Form the basis for data structures like stacks, queues, and graphs.Advantages of Arrays1. Code optimisation: Arrays allow accessing data with fewer lines of code.2. Easy traversal: Elements can be easily processed using loops.3. Easy sorting: Sorting operations can be performed with simple code.4. Random access: Any element can be accessed directly using its index.5. Supports data structures: Arrays make it easy to implement structures like stacks andqueues.6. Improves readability: Programs become more organised and easier to understand.Disadvantages of Arrays1. Fixed size: The array size cannot be changed during program execution.2. Costly insertion/deletion: Adding or removing elements requires shifting, which is time-consuming.3. Memory wastage: Unused allocated space leads to memory loss.4. Homogeneous data only: Arrays can store only one data type at a time
  • 4.
    Programming in CUnit-III 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/bcaClassification of ArraysIn C programming, arrays are classified mainly based on their dimensionality. There are two typesof arrays:I) One Dimensional arrays (1-D arrays)DefinitionA one-dimensional array is a collection of elements of the same data type arranged in a singlerow (linear form) and stored in contiguous memory locations.a)1-D Array Declaration in C• To declare an array in C, we use square brackets [] after the array name.• The size of the array (number of elements) is written inside the brackets.Syntax:data_type array_name[size];➢ data_type → type of elements (int, float, char, etc.)➢ array_name → name of the array➢ size → number of elementsExamples:int numbers[10]; // array of 10 integersfloat marks[5]; // array of 5 floatschar name[20]; // array of 20 characters (strings)
  • 5.
    Programming in CUnit-III 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/bcab) Types of 1-D Array Initialization in C1. Compile-time (static)InitializationValues are assigned at the time of declaration.int marks[5] = {90, 85, 78, 92, 88};2. Partial InitializationOnly some values are given; the remaining are set to 0.int numbers[5] = {1, 2}; // stores 1, 2, 0, 0, 03. Implicit Size InitializationThe size is automatically determined by the number of elements.int nums[] = {10, 20, 30, 40};4. Runtime (Dynamic) InitializationValues are entered by the user or assigned during program execution.int arr[5];for(int i = 0; i < 5; i++){scanf("%d", &arr[i]);}c) Accessing Elements of a 1-D ArrayUse the index (starting from 0) to read an element:#include <stdio.h>int main(){int arr[5] = {10, 20, 30, 40, 50}; // Compile-time initialization// Access elementsprintf("First element: %dn", arr[0]); //10printf("Third element: %dn", arr[2]); //30return 0;}
  • 6.
    Programming in CUnit-III 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/bcad) Updating Elements of a 1-D ArrayAssign a new value to an element using its index:#include <stdio.h>int main(){int arr[5] = {10, 20, 30, 40, 50};// Update elementsarr[1] = 25; // Update second elementarr[4] = 55; // Update fifth element// Display updated arrayprintf("nUpdated Array Elements:n");for(int i = 0; i < 5; i++){printf("arr[%d] = %dn", i, arr[i]);}return 0;}e) Memory Representation of 1-D Array• In C, the elements of an array are stored in continuous memory locations.• Each element is accessed using an index, which starts from 0.• The base address refers to the memory location of the first element.• The address of the i-th element is calculated as:Address of element = Base address + (i × size of each element)Example:• If int marks[5] = {90, 97, 95, 99, 100}; is stored at base address 3020 and each integertakes 2 bytes (depends on system), memory allocation will be:
  • 7.
    Programming in CUnit-III 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/bcaII) Multidimensional Arrays• In C, arrays store multiple values of the same data type.• Multidimensional arrays represent data in tables, grids, or matrices (e.g., student marks,chessboard, image pixels).• A multidimensional array is an array of arrays, created with more than one dimension.• Common types include 2-D, 3-D, and higher-dimensional arrays, with 2-D arrays being themost common (rows and columns).Syntax for declaration:data_type array_name[size1][size2]........[sizeN];Examples:int matrix[3][3]; // 2-D array (3 rows, 3 columns)int cube[3][3][3]; // 3-D array (like a cube of data)Two-Dimensional (2-D) ArraysDefinitionA two-dimensional (2-D) array is a collection of elements arranged in rows and columns,where each element is accessed using two indices.• It is used to store data in the form of a table or matrix with rows and columns.
  • 8.
    Programming in CUnit-III 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/bcaa) Declaration of 2-D ArraysTo declare a 2-D array, we use two sets of square brackets [ ] [ ]:Syntax:data_type array_name[rows][columns];• data_type → type of elements (int, float, char, etc.)• array_name → name of the array• rows, columns → size (number of rows and columns)Example:int matrix[3][3]; // 3x3 integer matrix, this can store 3 × 3 = 09 elements.float marks[2][5]; // 2 rows and 5 columns of floats, this can store 2 × 5 = 10 elements.char name[4][20]; // 4 strings, each of max length 20, his can store 4 × 20 = 80 elements.b) Types of 2-D Array Initialization1. Compile-time InitializationValues assigned during declaration.int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };2. Partial InitializationRemaining elements are set to 0.int mat[2][3] = { {1, 2}, {4} }; // stores: {1,2,0} and {4,0,0}3. Implicit Row Size InitializationNumber of rows can be left empty (columns must be given).int mat[][3] = { {1, 2, 3}, {4, 5, 6} };
  • 9.
    Programming in CUnit-III 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/bca4. Runtime (Dynamic) InitializationValues entered by user at runtime.int mat[2][3];for(int i = 0; i < 2; i++){for(int j = 0; j < 3; j++){scanf("%d", &mat[i][j]);}}c) Accessing Elements of a 2-D ArrayUse row index and column index.#include <stdio.h>int main(){int mat[2][3] = { {10, 20, 30}, {40, 50, 60} };printf("Element at [0][1] = %dn", mat[0][1]); // 20printf("Element at [1][2] = %dn", mat[1][2]); // 60return 0;}
  • 10.
    Programming in CUnit-III 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/bcad) Updating Elements of a 2-D ArrayAssign new values using row and column index.#include <stdio.h>int main(){int mat[2][3] = { {10, 20, 30}, {40, 50, 60} };// Update elementsmat[0][1] = 25; // Update row 0, col 1mat[1][2] = 65; // Update row 1, col 2// Display updated matrixprintf("nUpdated Matrix:n");for(int i = 0; i < 2; i++){for(int j = 0; j < 3; j++){printf("%d ", mat[i][j]);}printf("n");}return 0;}
  • 11.
    Programming in CUnit-III 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/bcae) Memory representation of 2-D Arrayint arr[3][3] = { {24, 15, 34}, {26, 134, 194}, {67, 23, 345} } is stored in memory asHere, the base address is the address of the 2-D array or the address of the first object stored in the2-D array. The memory address increases by 4 bytes (the size of the int data type).II) StructuresIntroduction:• A structure in C is a user-defined data type that groups variables of different types undera single name.• It is useful for representing real-world entities, such as student details or textbookinformation.Definition:A structure is a collection of heterogeneous variables under a single name, enabling logicalrepresentation of real-world entities and improving program organisation.Syntax:• A structure is defined using the keyword struct.• The items in the structure are called its members and they can be of any valid data type.struct StructureName{data_type member1;data_type member2;...data_type memberN;};
  • 12.
    Programming in CUnit-III 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/bcaExample:1Memory Size of a Structure:• The total memory size of a structure is the sum of the sizes of its members plus anypadding added by the compiler for alignment.Example:2struct textbook{char name[40];char author[20];int pages;};
  • 13.
    Programming in CUnit-III 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/bcaApplications of Structures1. Representing real-world entities like students, employees, books, or patients withmultiple attributes.2. Managing records in databases or file systems.3. Creating arrays of structures for handling collections of related data.4. Implementing complex data structures like linked lists, stacks, and queues.5. Organising data for file handling and data exchange between functions.Need for Structures/ Advantages of Structures1. To group different data types into a single unit.2. To model real-world entities like students, employees, or books with multiple attributes.3. To improve program readability and logical organisation of data.4. To reduce program complexity and enhance reusability.5. To serve as a foundation for advanced concepts like arrays of structures, pointers tostructures, and file handling.Disadvantages of Structures1. Cannot directly perform arithmetic or operations on entire structures.2. Memory allocation is fixed and may lead to wastage if not used efficiently.3. Accessing individual members requires explicit member names.4. Structures cannot contain operations (functions) directly like objects in OOP.5. Handling very large structures can increase program complexity and execution time.
  • 14.
    Programming in CUnit-III 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/bcaDeclaring Structure VariablesStructure variables can be declared in two ways:1)Method 1 – After structure definition:struct Student{int rollno;char name[20];float marks;};struct Student s1, s2; // declaring variables2)Method 2 – Along with structure definition:struct Student{int rollno;char name[20];float marks;} s1, s2;Initializing Structure Members1) Initialize a structure at the time of declaration:#include <stdio.h>// Define the structurestruct Student{int rollno;char name[20];float marks;};
  • 15.
    Programming in CUnit-III 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/bcaint main(){// Declare and initialize structure variablesstruct Student s1 = {101, "Arun", 85.5};struct Student s2 = {102, "Riya", 92.0};// Display values of s1printf("Student 1 Details:n");printf("Roll Number: %dn", s1.rollno);printf("Name: %sn", s1.name);printf("Marks: %.2fnn", s1.marks);// Display values of s2printf("Student 2 Details:n");printf("Roll Number: %dn", s2.rollno);printf("Name: %sn", s2.name);printf("Marks: %.2fn", s2.marks);return 0;}2) assign values later:s1.rollno = 102;strcpy(s1.name, "Meena"); // for strings use strcpy()s1.marks = 90.0;Accessing Structure MembersMembers are accessed using the dot operator (.)
  • 16.
    Programming in CUnit-III 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/bcaIII) UnionsIntroduction:• A union in C is a user-defined data type similar to a structure, but all members sharethe same memory location.• Only one member can hold a value at a time.Definition:A union is a C data type where all members share the same memory location, allowing only oneactive value at a time.Memory Allocation:• The memory allocated for a union equals the size of its largest member.• Assigning a value to one member overwrites the previous value stored in the unionApplications of Unions1. Save memory in programs with limited resources.2. Share memory in embedded systems and device drivers.3. Use the same data in different ways, like bit fields or packets.4. Access the same memory as different data types (type punning).5. Help in designing compilers and operating systems efficiently.Advantages/Need of Unions in C1. Efficient memory usage, as all members share the same memory.2. Handle different data types at different times using the same memory.3. Useful in embedded systems and low-level programming where memory is limited.4. Facilitates type conversion, e.g., accessing the same data as integer or float.5. Optimized storage when only one value is needed at a time.
  • 17.
    Programming in CUnit-III 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/bcaDisadvantages of Unions1. Only one member can hold a value at a time.2. Assigning a value to one member overwrites the previous value.3. Cannot store multiple values simultaneously.4. Accessing the wrong member may lead to unexpected results.5. Not suitable when multiple data elements need to be stored concurrently.Declaration of UnionUnions are declared using the keyword union.Syntax:union UnionName{data_type member1;data_type member2;...data_type memberN;};Initialization of Union1)Method 1 – At the time of declaration:#include <stdio.h>// Define the unionunion Data{int i;float f;char str[20];};
  • 18.
    Programming in CUnit-III 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/bcaint main(){// Method 1: Initialize at the time of declarationunion Data d1 = {10}; // Initializes the first member 'i'// Access and display the valueprintf("Value of i: %dn", d1.i);return 0;}2) Method 2 – Assigning later:int main(){// Declare a union variableunion Data d2;// Assign integer valued2.i = 10;printf("After assigning integer:ni = %dnn", d2.i);// Assign float valued2.f = 5.5;printf("After assigning float:nf = %.2fnn", d2.f);// Assign string valuestrcpy(d2.str, "BCA");printf("After assigning string:nstr = %sn", d2.str);return 0;}
  • 19.
    Programming in CUnit-III 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/bcaComparison of Arrays, Structures, and Unions in CArrays Structures Unions1. Store multiple values ofthe same data type.1. Can store multiplevariables of different datatypes.1. Can store multiple variables ofdifferent types, but only one valueat a time.2. Size is fixed at the timeof declaration.2. Size depends on allmembers combined.2. Size is equal to the largestmember.3. Elements are accessedusing indices.3. Members are accessedusing the dot (.) operator.3. Members are accessed usingthe dot (.) operator.4. All elements occupyseparate memory locations.4. Each member has itsown memory location.4. All members share the samememory location.5. Used for storing lists,matrices, or sequences ofsimilar data.5. Used to represent real-world entities logically.5. Used for memory-efficientstorage where only one value isneeded at a time.6. Supports traversal,searching, and sortingoperations.6. Can be nested orcombined with arrays andpointers.6. Efficient in low-memoryapplications like embeddedsystems.7. Applications: storingstudent marks, employeesalaries, matrices.Applications: storingstudent records, bookdetails, employee profiles.Applications: type punning,sharing memory in embeddedsystems, interpreting data inmultiple formats.*** *** ***

[8]ページ先頭

©2009-2025 Movatter.jp