This document discusses how different C data types are stored in memory. It describes the basic integer and floating point types, including their storage sizes and value ranges. It also covers void, enumerated, pointer, array, structure, and union types. For integers, it provides the memory representations of char, both signed and unsigned. It explains the memory layout of a C program, including the text, data, stack, and heap segments. Finally, it briefly discusses big and little endian formats for multibyte data storage.
The document discusses one-dimensional arrays in C++. It defines an array as a series of elements of the same type that can be referenced collectively by a common name. These elements are placed in consecutive memory locations and can be individually referenced using a subscript or index. The document covers declaring and initializing one-dimensional arrays, accessing array elements individually and collectively, inputting and displaying array elements, and provides examples of programs that work with arrays.
Arrays allow storing multiple values of the same type sequentially in memory. An array is declared with the type, name, and size. Elements are accessed using indexes from 0 to size-1. Strings are represented as character arrays terminated with a null character. Arrays can be passed to and returned from functions, and multidimensional arrays store arrays within arrays. Standard libraries provide functions for string and character manipulation.
An array is a collection of similar data types stored in contiguous memory locations. Arrays in C can store primitive data types like int, char, float, etc. Elements of an array are accessed using indexes and they are stored sequentially in memory. Strings in C are arrays of characters terminated by a null character. Common functions to manipulate strings include strlen(), strcpy(), strcat(), strcmp(), strrev(), strlwr(), and strupr().
function, storage class and array and stringsRai University
The document discusses one-dimensional arrays in C programming. It defines arrays, explains how to declare and initialize them, and provides examples of accessing array elements. It also discusses reading and printing arrays, and summarizes common string handling functions in C like strcat(), strcmp(), and strcpy().
Strings in C can be declared as character arrays that are terminated with a null character '\0'. Strings can be initialized by assigning character constants in quotes or curly braces. Common string library functions allow input of strings with scanf and gets, getting the length with strlen, concatenating with strcat, comparing with strcmp, and copying with strcpy.
The document discusses various string handling, mathematical, and random number generation functions available in C++ library. It provides examples of functions like strlen(), strcpy(), strcmp(), sqrt(), pow(), randomize(), random(). It also provides programs to demonstrate the use of these functions for tasks like checking palindromes, searching strings, toggling case, generating random numbers in a given range.
This document discusses how different C data types are stored in memory. It describes the basic integer and floating point types, including their storage sizes and value ranges. It also covers void, enumerated, pointer, array, structure, and union types. For integers, it provides the memory representations of char, both signed and unsigned. It explains the memory layout of a C program, including the text, data, stack, and heap segments. Finally, it briefly discusses big and little endian formats for multibyte data storage.
The document discusses one-dimensional arrays in C++. It defines an array as a series of elements of the same type that can be referenced collectively by a common name. These elements are placed in consecutive memory locations and can be individually referenced using a subscript or index. The document covers declaring and initializing one-dimensional arrays, accessing array elements individually and collectively, inputting and displaying array elements, and provides examples of programs that work with arrays.
Arrays allow storing multiple values of the same type sequentially in memory. An array is declared with the type, name, and size. Elements are accessed using indexes from 0 to size-1. Strings are represented as character arrays terminated with a null character. Arrays can be passed to and returned from functions, and multidimensional arrays store arrays within arrays. Standard libraries provide functions for string and character manipulation.
An array is a collection of similar data types stored in contiguous memory locations. Arrays in C can store primitive data types like int, char, float, etc. Elements of an array are accessed using indexes and they are stored sequentially in memory. Strings in C are arrays of characters terminated by a null character. Common functions to manipulate strings include strlen(), strcpy(), strcat(), strcmp(), strrev(), strlwr(), and strupr().
function, storage class and array and stringsRai University
The document discusses one-dimensional arrays in C programming. It defines arrays, explains how to declare and initialize them, and provides examples of accessing array elements. It also discusses reading and printing arrays, and summarizes common string handling functions in C like strcat(), strcmp(), and strcpy().
Strings in C can be declared as character arrays that are terminated with a null character '\0'. Strings can be initialized by assigning character constants in quotes or curly braces. Common string library functions allow input of strings with scanf and gets, getting the length with strlen, concatenating with strcat, comparing with strcmp, and copying with strcpy.
The document discusses various string handling, mathematical, and random number generation functions available in C++ library. It provides examples of functions like strlen(), strcpy(), strcmp(), sqrt(), pow(), randomize(), random(). It also provides programs to demonstrate the use of these functions for tasks like checking palindromes, searching strings, toggling case, generating random numbers in a given range.
Introduction of arrays, Declaration of array, Initialization of array, Sorting, Multidimensional array. Some code examples that will make you clear about the concept of arrays.
https://github.com/ashim888/csit-c
This document discusses input/output (I/O) functions and string functions in C programming. It describes formatted I/O functions like printf() and scanf() for writing and reading, as well as unformatted I/O functions like getchar() and putchar() for single characters. Common string functions like strcat(), strcmp(), strcpy() are also explained, which are used to concatenate, compare, and copy strings. The document provides syntax and examples for using these I/O and string handling functions in C code.
This set of slides introduces the reader to the concept of multidimensional arrays in C++ (with elements of C++11 and C++14). The true nature of multidimensional arrays is discussed by means of an intermediate type alias. The pheonomenon of array-to-pointer decay and pointer arithmetic is then generalized to arrays of arrays. The presentation proceeds with a discussion on how to pass multidimensional arrays to functions.
1. Arrays allow storing a collection of related data items and can be one-dimensional or multidimensional.
2. Two-dimensional arrays are arrays of one-dimensional arrays with two indices to access elements.
3. Preprocessor directives like #include and #define are instructions to the compiler and are not part of the C language itself. They expand the scope of the programming environment.
This set of slides introduces the reader to the concept of resource wrappers, i.e., classes that are responsible for the correct handling of resources of some kind (e.g., memory). In particular, the presentation discusses the design and implementation of a simplified version of std::vector for the specific case of integer elements. In this regard, we first discuss the fundamental role of destructors as a deterministic, general-purpose undo mechanism. Second, we notice that providing an explicit destructor entails the need of a consequent explicit implementation for the copy constructor and copy assignment operator. We conclude with the formulation of the so-called "rule of three".
This document discusses handling character strings in C. It covers:
1. How strings are stored in memory as ASCII codes appended with a null terminator.
2. Common string operations like reading, comparing, concatenating and copying strings.
3. How to initialize, declare, read and write strings.
4. Useful string handling functions like strlen(), strcpy(), strcat(), strcmp() etc to perform various operations on strings.
Arrays allow storing and accessing multiple values of the same data type. A two-dimensional array represents data in a tabular form and can be used to store values in a matrix. It is declared with two sets of brackets and initialized with nested curly braces. Elements are accessed using two indices, such as array[row][column]. Memory for a two-dimensional array is allocated in a contiguous block, with the first dimension iterating fastest.
● Concept of Structure and Union
● Declaration and Initialization of structure and union
● Nested structures
● Array of Structures
● Passing structure to functions
This document discusses strings in C++. It defines a string as a sequence of characters and provides examples of single character constants like 'h' and string constants like "hello". It describes two ways to declare strings in C++ - using a C-style character array or the standard string class. It also demonstrates different ways to initialize and copy strings, including using string constants, character constants, the length operator, and user input. Finally, it lists some common string functions like strcpy(), strcat(), strlen(), and strcmp().
● Introduction to Arrays
● Declaration and initialization of one dimensional and two-dimensional
arrays.
● Definition and initialization of String
● String functions
This document discusses pointers in C++. It begins by defining a pointer as a variable that holds the memory address of another variable. It then lists three reasons why pointers are one of C++'s most useful features: 1) they allow direct access and manipulation of memory locations, 2) they support dynamic memory allocation, and 3) they can improve efficiency of certain routines. The document goes on to explain pointer declaration, initialization, arithmetic, and how to allocate and free dynamic memory using new and delete operators. It also discusses pointers and strings as well as constant pointers.
This document provides information about strings in C++. It defines a string as a collection of characters within double quotes. Strings are stored as character arrays terminated by a null character. The document discusses declaring and initializing strings, inputting strings from the user, and functions for manipulating strings like strcat(), strcmp(), and memcpy(). It also covers arrays of strings and comparing, concatenating, copying and other operations on strings.
This document provides an overview of fundamental concepts in C programming such as keywords, identifiers, data types, constants, variables, and operators. Key points include:
- Keywords are reserved words in C that have special meaning, while identifiers are names given to variables, functions, etc. Identifiers cannot be the same as keywords.
- There are different data types in C like int, char, float, etc. that determine the type of data a variable can hold.
- Constants cannot change value once defined, while the value of variables can change during program execution.
- Operators like unary, binary, and ternary are used to perform operations on operands. Unary operators require a single
This set of slides introduces the reader to the concept of arrays in C++ (with elements of C++11 and C++14). After presenting the array data type, the concept of array-to-pointer decay is introduced. The presentation proceeds with a discussion on how to pass arrays to functions. To this extent, the reader is guided to the use of bounded ranges as the first step towards the use of the Standard Template Library (STL).
Arrays in C allow storing multiple values of the same data type in contiguous memory locations. An array is declared with a data type, array name, and size. Individual elements are accessed using the array name and index. Arrays are useful for storing lists of values, performing matrix operations, implementing algorithms like search and sort, and more. Strings in C are implemented as arrays of characters that are null-terminated. Functions like strcpy(), strcat(), strcmp() allow manipulating strings.
This document provides an introduction to strings in C programming. It discusses that strings are arrays of characters terminated by a null character. It explains how to declare and initialize strings, and provides examples of simple string programs. It also lists common string functions like strlen(), strcpy(), and strcat(), and provides examples of using each function. The document is intended as a presentation on strings for C programming.
This document provides an overview of common string operations in C++, including how to declare and initialize strings, access individual characters, compare strings, append to strings, search within strings, and convert between C++ strings and C-style character arrays. It also describes some additional string utility functions provided in the CS106 library like converting case and converting between strings and numbers.
The document discusses arrays and strings in C programming. It defines arrays as groups of data items of the same type that share a common name. One-dimensional arrays are declared with a datatype and size, and can be initialized. Multi-dimensional arrays have multiple subscripts. Strings are arrays of characters that are null-terminated. Strings can be initialized and manipulated using functions like strcpy(), strlen(), strcmp(). Examples are provided to demonstrate array and string declarations, initialization, manipulation and differences between the two data structures.
1) A string is a one-dimensional array of characters terminated by a null character. Strings are declared using char arrays or string literals.
2) There are two ways to declare and initialize strings in C: using a char array and specifying the size, or using a string literal which automatically inserts a null terminator.
3) Common string functions include strlen() to return the length, strcpy() to copy one string to another, strcat() to concatenate strings, and strcmp() to compare two strings.
Introduction of arrays, Declaration of array, Initialization of array, Sorting, Multidimensional array. Some code examples that will make you clear about the concept of arrays.
https://github.com/ashim888/csit-c
This document discusses input/output (I/O) functions and string functions in C programming. It describes formatted I/O functions like printf() and scanf() for writing and reading, as well as unformatted I/O functions like getchar() and putchar() for single characters. Common string functions like strcat(), strcmp(), strcpy() are also explained, which are used to concatenate, compare, and copy strings. The document provides syntax and examples for using these I/O and string handling functions in C code.
This set of slides introduces the reader to the concept of multidimensional arrays in C++ (with elements of C++11 and C++14). The true nature of multidimensional arrays is discussed by means of an intermediate type alias. The pheonomenon of array-to-pointer decay and pointer arithmetic is then generalized to arrays of arrays. The presentation proceeds with a discussion on how to pass multidimensional arrays to functions.
1. Arrays allow storing a collection of related data items and can be one-dimensional or multidimensional.
2. Two-dimensional arrays are arrays of one-dimensional arrays with two indices to access elements.
3. Preprocessor directives like #include and #define are instructions to the compiler and are not part of the C language itself. They expand the scope of the programming environment.
This set of slides introduces the reader to the concept of resource wrappers, i.e., classes that are responsible for the correct handling of resources of some kind (e.g., memory). In particular, the presentation discusses the design and implementation of a simplified version of std::vector for the specific case of integer elements. In this regard, we first discuss the fundamental role of destructors as a deterministic, general-purpose undo mechanism. Second, we notice that providing an explicit destructor entails the need of a consequent explicit implementation for the copy constructor and copy assignment operator. We conclude with the formulation of the so-called "rule of three".
This document discusses handling character strings in C. It covers:
1. How strings are stored in memory as ASCII codes appended with a null terminator.
2. Common string operations like reading, comparing, concatenating and copying strings.
3. How to initialize, declare, read and write strings.
4. Useful string handling functions like strlen(), strcpy(), strcat(), strcmp() etc to perform various operations on strings.
Arrays allow storing and accessing multiple values of the same data type. A two-dimensional array represents data in a tabular form and can be used to store values in a matrix. It is declared with two sets of brackets and initialized with nested curly braces. Elements are accessed using two indices, such as array[row][column]. Memory for a two-dimensional array is allocated in a contiguous block, with the first dimension iterating fastest.
● Concept of Structure and Union
● Declaration and Initialization of structure and union
● Nested structures
● Array of Structures
● Passing structure to functions
This document discusses strings in C++. It defines a string as a sequence of characters and provides examples of single character constants like 'h' and string constants like "hello". It describes two ways to declare strings in C++ - using a C-style character array or the standard string class. It also demonstrates different ways to initialize and copy strings, including using string constants, character constants, the length operator, and user input. Finally, it lists some common string functions like strcpy(), strcat(), strlen(), and strcmp().
● Introduction to Arrays
● Declaration and initialization of one dimensional and two-dimensional
arrays.
● Definition and initialization of String
● String functions
This document discusses pointers in C++. It begins by defining a pointer as a variable that holds the memory address of another variable. It then lists three reasons why pointers are one of C++'s most useful features: 1) they allow direct access and manipulation of memory locations, 2) they support dynamic memory allocation, and 3) they can improve efficiency of certain routines. The document goes on to explain pointer declaration, initialization, arithmetic, and how to allocate and free dynamic memory using new and delete operators. It also discusses pointers and strings as well as constant pointers.
This document provides information about strings in C++. It defines a string as a collection of characters within double quotes. Strings are stored as character arrays terminated by a null character. The document discusses declaring and initializing strings, inputting strings from the user, and functions for manipulating strings like strcat(), strcmp(), and memcpy(). It also covers arrays of strings and comparing, concatenating, copying and other operations on strings.
This document provides an overview of fundamental concepts in C programming such as keywords, identifiers, data types, constants, variables, and operators. Key points include:
- Keywords are reserved words in C that have special meaning, while identifiers are names given to variables, functions, etc. Identifiers cannot be the same as keywords.
- There are different data types in C like int, char, float, etc. that determine the type of data a variable can hold.
- Constants cannot change value once defined, while the value of variables can change during program execution.
- Operators like unary, binary, and ternary are used to perform operations on operands. Unary operators require a single
This set of slides introduces the reader to the concept of arrays in C++ (with elements of C++11 and C++14). After presenting the array data type, the concept of array-to-pointer decay is introduced. The presentation proceeds with a discussion on how to pass arrays to functions. To this extent, the reader is guided to the use of bounded ranges as the first step towards the use of the Standard Template Library (STL).
Arrays in C allow storing multiple values of the same data type in contiguous memory locations. An array is declared with a data type, array name, and size. Individual elements are accessed using the array name and index. Arrays are useful for storing lists of values, performing matrix operations, implementing algorithms like search and sort, and more. Strings in C are implemented as arrays of characters that are null-terminated. Functions like strcpy(), strcat(), strcmp() allow manipulating strings.
This document provides an introduction to strings in C programming. It discusses that strings are arrays of characters terminated by a null character. It explains how to declare and initialize strings, and provides examples of simple string programs. It also lists common string functions like strlen(), strcpy(), and strcat(), and provides examples of using each function. The document is intended as a presentation on strings for C programming.
This document provides an overview of common string operations in C++, including how to declare and initialize strings, access individual characters, compare strings, append to strings, search within strings, and convert between C++ strings and C-style character arrays. It also describes some additional string utility functions provided in the CS106 library like converting case and converting between strings and numbers.
The document discusses arrays and strings in C programming. It defines arrays as groups of data items of the same type that share a common name. One-dimensional arrays are declared with a datatype and size, and can be initialized. Multi-dimensional arrays have multiple subscripts. Strings are arrays of characters that are null-terminated. Strings can be initialized and manipulated using functions like strcpy(), strlen(), strcmp(). Examples are provided to demonstrate array and string declarations, initialization, manipulation and differences between the two data structures.
1) A string is a one-dimensional array of characters terminated by a null character. Strings are declared using char arrays or string literals.
2) There are two ways to declare and initialize strings in C: using a char array and specifying the size, or using a string literal which automatically inserts a null terminator.
3) Common string functions include strlen() to return the length, strcpy() to copy one string to another, strcat() to concatenate strings, and strcmp() to compare two strings.
This document provides an introduction and overview of mechanics of materials. It defines key terms like stress, strain, normal stress, shear stress, factor of safety, and allowable stress. It also gives examples of calculating stresses in structural members subjected to various loads. The document is an introductory reading for a mechanics of materials course that will analyze the relationship between external forces and internal stresses and strains in structural elements.
All solutions appear to converge to the equilibrium solution C > œ !. For some differential equations, all solutions diverge from the equilibrium solution. The direction field and slopes of the solutions help determine whether solutions converge or diverge. Initial conditions determine whether a solution increases or decreases over time.
This document discusses solutions to higher order differential equations with constant coefficients. It begins by introducing homogeneous linear equations of order two or higher of the form y'' + ay' + by + c = 0. It then presents the method of solving such equations by finding the roots of the characteristic or auxiliary equation. Depending on whether the roots are real/distinct, real/equal, or complex conjugates, the general solution will take different forms involving exponential or trigonometric functions. Several examples are worked through. The document also discusses solving higher order differential equations and presents solutions to sample third and fourth order equations.
This document discusses storage classes in the C programming language. It begins with an introduction to the C language and its history. The main body of the document then covers the four primary storage classes in C - automatic, register, static, and external. For each class, it provides details on storage location, default initial value, scope, and lifetime. Examples are provided to illustrate the behavior and usage of variables for each storage class. The key differences between the four classes are summarized in a table at the end.
I am working as a Assistant Professor in ITS, Ghaziabad.This is very useful to U.P.Technical University,Uttrakhand Technical University students. Give feedback to rakeshroshan@its.edu.in
This document gives the class notes of Unit 2 stresses in composite sections. Subject: Mechanics of materials.
Syllabus contest is as per VTU, Belagavi, India.
Notes Compiled By: Hareesha N Gowda, Assistant Professor, DSCE, Bengaluru-78.
This document provides an overview of Chapter 2 from the textbook "Mechanics of Materials" which covers stress and strain under axial loading. The chapter discusses key topics like normal strain, stress-strain diagrams for ductile and brittle materials, Hooke's law, elastic vs plastic behavior, fatigue, deformations under axial loading, static indeterminacy, thermal stresses, and Poisson's ratio. It also includes sample problems and examples to demonstrate calculating deformations and reactions for axially loaded members.
3 torsion- Mechanics of Materials - 4th - BeerNhan Tran
This document provides an overview of chapter 3 from the textbook "Mechanics of Materials" which covers the topic of torsion. It begins with an introduction to torsional loads on circular shafts and the concept of net torque due to internal stresses. Key concepts discussed include shear strain, stresses in the elastic range using elastic torsion formulas, and failure modes under torsion. The document provides examples of solving sample problems involving statically indeterminate shafts, determining required shaft diameters, and calculating stresses and angles of twist. It concludes with discussing plastic deformations and torsion of noncircular members.
1) Ordinary differential equations relate a dependent variable to one or more independent variables by means of differential coefficients. They can be classified based on order, degree, whether they are linear or non-linear, and type (exact, separable variables, homogeneous).
2) First order differential equations can sometimes be solved by separation of variables, or by finding an integrating factor. Homogeneous equations can be transformed by substitution.
3) Second order linear differential equations can be reduced to a system of two first order equations. The complementary function and particular solutions combine to form the general solution. Unequal or equal roots of the characteristic equation determine the form of the complementary function.
This document discusses various methods for solving first order differential equations, including:
1. Variable separable methods where the equation can be written as a function of x multiplied by a function of y.
2. Homogeneous equations where both sides are homogeneous functions of the same degree.
3. Exact equations where there exists an integrating factor.
4. Equations that can be transformed to an exact or separable form through substitution.
5. Linear equations that can be solved using an integrating factor that is a function of x.
Mechanics of materials lecture 01, Engr. Abdullah KhanAbdullah Khan
This document provides information about a Mechanics of Materials course, including:
- The instructor's contact information and the course grading criteria.
- An outline of the course content which will cover topics like stresses, strains, bending of beams, torsion, and failure theories.
- Recommended study sources and learning objectives/outcomes which aim to equip students to analyze and design agricultural machinery and structures.
- An introduction to mechanics of materials and definitions of important material properties like strength, hardness, ductility, and elasticity that engineers must understand when designing with different materials.
The document discusses higher order differential equations. It defines nth order differential equations and describes their general forms. For homogeneous equations, the general solution method involves making an operator form, constructing an auxiliary equation, solving for roots, and finding the complementary solution. For non-homogeneous equations, the method of undetermined coefficients is used to find a particular solution and the general solution is the sum of the complementary and particular solutions. Examples are provided to illustrate the solution methods.
An array is a group of data items of same data type that share a common name. Ordinary variables are capable of holding only one value at a time. If we want to store more than one value at a time in a single variable, we use arrays.
An array is a collective name given to a group of similar variables. Each member in the group is referred to by its position in the group.
Arrays are alloted the memory in a strictly contiguous fashion. The simplest array is a one-dimensional array which is a list of variables of same data type. An array of one-dimensional arrays is called a two-dimensional array.
The document discusses arrays in C programming language. It defines arrays as fixed-sized sequenced collections of elements of the same data type that share a common name. One-dimensional arrays represent lists, while two-dimensional arrays represent tables with rows and columns. Arrays must be declared before use with the size specified. Elements can be accessed using indices and initialized. Common operations like input, output, sorting and searching of array elements are demonstrated through examples.
Arrays & Strings can be summarized as follows:
1. Arrays are fixed-size collections of elements of the same data type that are used to store lists of related data. They can be one-dimensional, two-dimensional, or multi-dimensional.
2. Strings in C are arrays of characters terminated by a null character. They are commonly used to store text data. Common string operations include reading, writing, combining, copying, comparing, and extracting portions of strings.
3. Arrays are declared with a data type, name, and size. They can be initialized with a block of comma-separated values. Individual elements are accessed using indexes in square brackets. Two-dimensional arrays represent tables
C programming language provides arrays as a data structure to store a fixed-size collection of elements of the same type. An array stores elements in contiguous memory locations. Individual elements in an array can be accessed using an index. Common array operations in C include declaration, initialization, accessing and modifying individual elements, and passing arrays to functions.
1. Arrays allow storing of multiple elements of the same data type under a single name. They can be one-dimensional, two-dimensional, or multi-dimensional. Strings are arrays of characters terminated by a null character.
2. Common array operations include declaring and initializing arrays, accessing elements using indexes, and performing element-by-element operations. Strings have specialized functions for operations like length calculation, copying, comparison and concatenation.
3. Pointers allow working with arrays by reference rather than value and are useful for passing arrays to functions. Structures group together different data types under one name and unions allow storing different data types in the same memory space.
Arrays allow storing multiple values in a single variable. To declare an array, specify the data type followed by the name of the array and square brackets containing the array size. Individual elements can then be accessed using their index number, starting from 0. Arrays can be initialized during declaration with curly braces containing comma-separated values. Loops and functions can also be used to iterate through and pass array elements.
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
Homework Assignment – Array Technical Document
Write a technical document that describes the structure and use of arrays. The document should
be 3 to 5 pages and include an Introduction section, giving a brief synopsis of the document and
arrays, a Body section, describing arrays and giving an annotated example of their use as a
programming construct, and a conclusion to revisit important information about arrays described
in the Body of the document. Some suggested material to include:
Declaring arrays of various types
Array pointers
Printing and processing arrays
Sorting and searching arrays
Multidimensional arrays
Indexing arrays of various dimension
Array representation in memory by data type
Passing arrays as arguments
If you find any useful images on the Internet, you can use them as long as you cite the source in
end notes.
Solution
Array is a collection of variables of the same type that are referenced by a common name.
Specific elements or variables in the array are accessed by means of index into the array.
If taking about C, In C all arrays consist of contiguous memory locations. The lowest address
corresponds to the first element in the array while the largest address corresponds to the last
element in the array.
C supports both single and multi-dimensional arrays.
1) Single Dimension Arrays:-
Syntax:- type var_name[size];
where type is the type of each element in the array, var_name is any valid identifier, and size is
the number of elements in the array which has to be a constant value.
*Array always use zero as index to first element.
The valid indices for array above are 0 .. 4, i.e. 0 .. number of elements - 1
For Example :- To load an array with values 0 .. 99
int x[100] ;
int i ;
for ( i = 0; i < 100; i++ )
x[i] = i ;
To determine to size of an array at run time the sizeof operator is used. This returns the size in
bytes of its argument. The name of the array is given as the operand
size_of_array = sizeof ( array_name ) ;
2) Initialisg array:-
Arrays can be initialised at time of declaration in the following manner.
type array[ size ] = { value list };
For Example :-
int i[5] = {1, 2, 3, 4, 5 } ;
i[0] = 1, i[1] = 2, etc.
The size specification in the declaration may be omitted which causes the compiler to count the
number of elements in the value list and allocate appropriate storage.
For Example :- int i[ ] = { 1, 2, 3, 4, 5 } ;
3) Multidimensional array:-
Multidimensional arrays of any dimension are possible in C but in practice only two or three
dimensional arrays are workable. The most common multidimensional array is a two
dimensional array for example the computer display, board games, a mathematical matrix etc.
Syntax :type name [ rows ] [ columns ] ;
For Example :- 2D array of dimension 2 X 3.
int d[ 2 ] [ 3 ] ;
A two dimensional array is actually an array of arrays, in the above case an array of two integer
arrays (the rows) each with three elements, and is stored row-wise in memory.
For Example :- Program to fill .
1. An array is a collection of data that holds a fixed number of values of the same type. Arrays allow storing multiple values in a single variable.
2. Arrays can have one dimension (1D), two dimensions (2D), or more dimensions. A 1D array stores values in a list, while a 2D array can be thought of as a table with rows and columns.
3. Array elements can be accessed using indices, with the first element having index 0. The last element of an array of size n has index n-1. Arrays must be initialized before use to assign starting values to elements.
An array is a collection of similar elements that are stored in contiguous memory locations. Arrays in C can have one or more dimensions. One-dimensional arrays are declared with the type of elements, name of the array, and number of elements within brackets (e.g. int marks[30]). Multi-dimensional arrays represent matrices and are declared with the number of rows and columns (e.g. int arr[5][10]). Individual elements within an array are accessed via indices (e.g. arr[2][7]). Pointers in C are related to arrays - the name of an array represents the address of its first element, and pointer arithmetic can be used to access successive elements in an array.
Array and its types and it's implemented programming Final.pdfajajkhan16
Arrays allow storing multiple values of the same type. An array has a fixed size that is declared and cannot be changed. Elements within an array are accessed via indices from 0 to size-1. Multidimensional arrays can represent tables of data and are arrays of arrays.
Arrays allow storing multiple values of the same type under one common name. They come in one-dimensional and two-dimensional forms. One-dimensional arrays store elements indexed with a single subscript, while two-dimensional arrays represent matrices with rows and columns indexed by two subscripts. Arrays can be passed to functions by passing their name and size for numeric arrays, or just the name for character/string arrays since strings are null-terminated. Functions can operate on arrays to perform tasks like finding the highest/lowest element or reversing a string.
C programming language allows for the declaration of arrays, which can store a fixed number of elements of the same data type. Arrays provide an efficient way to store and access related data sequentially in memory. Individual elements in an array are accessed via an index, and multi-dimensional arrays can model tables of data with multiple indices to access each element.
Here are the function definitions and declarations to transfer the variables and arrays between main and the function as specified:
(a)
float func1(float a, float b, int jstar[20]) {
float x;
// function body
return x;
}
int main() {
float a, b;
int jstar[20];
float x = func1(a, b, jstar);
}
(b)
float func2(int n, char c, double values[50]) {
float x;
// function body
return x;
}
int main() {
int n;
char c;
double values[50
An array is a collection of data that holds a fixed number of values of the same type. Arrays allow storing multiple values in a single variable through indices. There are one-dimensional, two-dimensional, and multi-dimensional arrays. One-dimensional arrays use a single subscript, two-dimensional arrays use two subscripts like rows and columns, and multi-dimensional arrays can have more than two subscripts. Arrays can be initialized during declaration with values or initialized at runtime by user input or other methods. Elements are accessed using their indices and operations can be performed on the elements.
An array is a collection of data that holds a fixed number of values of the same type. Arrays allow storing multiple values in a single variable through indices. There are one-dimensional, two-dimensional, and multi-dimensional arrays. One-dimensional arrays use a single subscript, two-dimensional arrays use two subscripts like rows and columns, and multi-dimensional arrays can have more than two subscripts. Arrays can be initialized during declaration with values or initialized at runtime by user input or other methods. Elements are accessed using their indices and operations can be performed on the elements.
Here is a C program that multiplies two matrices using 2D arrays:
#include <stdio.h>
int main() {
int a[2][2], b[2][2], product[2][2], i, j, k;
printf("Enter elements of first matrix:\n");
for(i=0; i<2; i++)
for(j=0; j<2; j++)
scanf("%d", &a[i][j]);
printf("Enter elements of second matrix:\n");
for(i=0; i<2; i++)
for(j=0; j<2; j++)
scanf("%d", &
This document discusses arrays in the C programming language. It begins by defining an array as a collection of elements of the same data type. It then covers key topics such as declaring and initializing one-dimensional and multi-dimensional arrays, accessing array elements using indexes, and performing input and output operations on arrays. Examples are provided to demonstrate how to declare, initialize, read from, and print arrays. The document serves as an introduction to working with arrays in C.
Array
Introduction
One-dimensional array
Multidimensional array
Advantage of Array
Write a C program using arrays that produces the multiplication of two matrices.
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
“An Outlook of the Ongoing and Future Relationship between Blockchain Technologies and Process-aware Information Systems.” Invited talk at the joint workshop on Blockchain for Information Systems (BC4IS) and Blockchain for Trusted Data Sharing (B4TDS), co-located with with the 36th International Conference on Advanced Information Systems Engineering (CAiSE), 3 June 2024, Limassol, Cyprus.
CAKE: Sharing Slices of Confidential Data on BlockchainClaudio Di Ciccio
Presented at the CAiSE 2024 Forum, Intelligent Information Systems, June 6th, Limassol, Cyprus.
Synopsis: Cooperative information systems typically involve various entities in a collaborative process within a distributed environment. Blockchain technology offers a mechanism for automating such processes, even when only partial trust exists among participants. The data stored on the blockchain is replicated across all nodes in the network, ensuring accessibility to all participants. While this aspect facilitates traceability, integrity, and persistence, it poses challenges for adopting public blockchains in enterprise settings due to confidentiality issues. In this paper, we present a software tool named Control Access via Key Encryption (CAKE), designed to ensure data confidentiality in scenarios involving public blockchains. After outlining its core components and functionalities, we showcase the application of CAKE in the context of a real-world cyber-security project within the logistics domain.
Paper: https://doi.org/10.1007/978-3-031-61000-4_16
HCL Notes and Domino License Cost Reduction in the World of DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-and-domino-license-cost-reduction-in-the-world-of-dlau/
The introduction of DLAU and the CCB & CCX licensing model caused quite a stir in the HCL community. As a Notes and Domino customer, you may have faced challenges with unexpected user counts and license costs. You probably have questions on how this new licensing approach works and how to benefit from it. Most importantly, you likely have budget constraints and want to save money where possible. Don’t worry, we can help with all of this!
We’ll show you how to fix common misconfigurations that cause higher-than-expected user counts, and how to identify accounts which you can deactivate to save money. There are also frequent patterns that can cause unnecessary cost, like using a person document instead of a mail-in for shared mailboxes. We’ll provide examples and solutions for those as well. And naturally we’ll explain the new licensing model.
Join HCL Ambassador Marc Thomas in this webinar with a special guest appearance from Franz Walder. It will give you the tools and know-how to stay on top of what is going on with Domino licensing. You will be able lower your cost through an optimized configuration and keep it low going forward.
These topics will be covered
- Reducing license cost by finding and fixing misconfigurations and superfluous accounts
- How do CCB and CCX licenses really work?
- Understanding the DLAU tool and how to best utilize it
- Tips for common problem areas, like team mailboxes, functional/test users, etc
- Practical examples and best practices to implement right away
Fueling AI with Great Data with Airbyte WebinarZilliz
This talk will focus on how to collect data from a variety of sources, leveraging this data for RAG and other GenAI use cases, and finally charting your course to productionalization.
GraphRAG for Life Science to increase LLM accuracyTomaz Bratanic
GraphRAG for life science domain, where you retriever information from biomedical knowledge graphs using LLMs to increase the accuracy and performance of generated answers
Things to Consider When Choosing a Website Developer for your Website | FODUUFODUU
Choosing the right website developer is crucial for your business. This article covers essential factors to consider, including experience, portfolio, technical skills, communication, pricing, reputation & reviews, cost and budget considerations and post-launch support. Make an informed decision to ensure your website meets your business goals.
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Speck&Tech
ABSTRACT: A prima vista, un mattoncino Lego e la backdoor XZ potrebbero avere in comune il fatto di essere entrambi blocchi di costruzione, o dipendenze di progetti creativi e software. La realtà è che un mattoncino Lego e il caso della backdoor XZ hanno molto di più di tutto ciò in comune.
Partecipate alla presentazione per immergervi in una storia di interoperabilità, standard e formati aperti, per poi discutere del ruolo importante che i contributori hanno in una comunità open source sostenibile.
BIO: Sostenitrice del software libero e dei formati standard e aperti. È stata un membro attivo dei progetti Fedora e openSUSE e ha co-fondato l'Associazione LibreItalia dove è stata coinvolta in diversi eventi, migrazioni e formazione relativi a LibreOffice. In precedenza ha lavorato a migrazioni e corsi di formazione su LibreOffice per diverse amministrazioni pubbliche e privati. Da gennaio 2020 lavora in SUSE come Software Release Engineer per Uyuni e SUSE Manager e quando non segue la sua passione per i computer e per Geeko coltiva la sua curiosità per l'astronomia (da cui deriva il suo nickname deneb_alpha).
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/building-and-scaling-ai-applications-with-the-nx-ai-manager-a-presentation-from-network-optix/
Robin van Emden, Senior Director of Data Science at Network Optix, presents the “Building and Scaling AI Applications with the Nx AI Manager,” tutorial at the May 2024 Embedded Vision Summit.
In this presentation, van Emden covers the basics of scaling edge AI solutions using the Nx tool kit. He emphasizes the process of developing AI models and deploying them globally. He also showcases the conversion of AI models and the creation of effective edge AI pipelines, with a focus on pre-processing, model conversion, selecting the appropriate inference engine for the target hardware and post-processing.
van Emden shows how Nx can simplify the developer’s life and facilitate a rapid transition from concept to production-ready applications.He provides valuable insights into developing scalable and efficient edge AI solutions, with a strong focus on practical implementation.
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxSitimaJohn
Ocean Lotus cyber threat actors represent a sophisticated, persistent, and politically motivated group that poses a significant risk to organizations and individuals in the Southeast Asian region. Their continuous evolution and adaptability underscore the need for robust cybersecurity measures and international cooperation to identify and mitigate the threats posed by such advanced persistent threat groups.
Infrastructure Challenges in Scaling RAG with Custom AI modelsZilliz
Building Retrieval-Augmented Generation (RAG) systems with open-source and custom AI models is a complex task. This talk explores the challenges in productionizing RAG systems, including retrieval performance, response synthesis, and evaluation. We’ll discuss how to leverage open-source models like text embeddings, language models, and custom fine-tuned models to enhance RAG performance. Additionally, we’ll cover how BentoML can help orchestrate and scale these AI components efficiently, ensuring seamless deployment and management of RAG systems in the cloud.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
1. Arrays: Array notations and representations, manipulating array elements, using multidimensional arrays, arrays of unknown or varying size. Structure : Purpose and usage of structures, declaring structures, assigning of structures. Pointers to Objects : Pointer and address arithmetic, pointer operations and declarations, using pointers as function arguments, Dynamic memory allocation, defining and using stacks and linked lists. UNIT IV
2.
3.
4.
5.
6.
7. 1 /* Arrays Example */ 2 /* Histogram printing program */ 3 #include <stdio.h> 4 #define SIZE 10 5 6 int main() 7 { 8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 9 int i, j; 10 11 printf( "%s%13s%17s", "Element", "Value", "Histogram" ); 12 13 for ( i = 0; i <= SIZE - 1; i++ ) { 14 printf( "%7d%13d ", i, n[ i ]) ; 15 16 for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */ 17 printf( "%c", '*' ); 18 19 printf( "" ); 20 } 21 22 return 0; 23 }
11. 1 /* 2 Passing arrays and individual array elements to functions */ 3 #include <stdio.h> 4 #define SIZE 5 5 6 void modifyArray( int [], int ); /* appears strange */ 7 void modifyElement( int ); 8 9 int main() 10 { 11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i; 12 13 printf( "Effects of passing entire array call " 14 "by reference:The values of the " 15 "original array are:" ); 16 17 for ( i = 0; i <= SIZE - 1; i++ ) 18 printf( "%3d", a[ i ] ); 19 20 printf( "" ); 21 modifyArray( a, SIZE ); /* passed call by reference */ 22 printf( "The values of the modified array are:" ); 23 24 for ( i = 0; i <= SIZE - 1; i++ ) 25 printf( "%3d", a[ i ] ); 26 27 printf( "Effects of passing array element call " 28 "by value:The value of a[3] is %d", a[ 3 ] ); 29 modifyElement( a[ 3 ] ); 30 printf( "The value of a[ 3 ] is %d", a[ 3 ] ); 31 return 0; 32 } Entire arrays passed call-by-reference, and can be modified Array elements passed call-by-value, and cannot be modified
12. Effects of passing entire array call by reference: The values of the original array are: 0 1 2 3 4 The values of the modified array are: 0 2 4 6 8 Effects of passing array element call by value: The value of a[3] is 6 Value in modifyElement is 12 The value of a[3] is 6 33 34 void modifyArray( int b[], int size ) 35 { 36 int j; 37 38 for ( j = 0; j <= size - 1; j++ ) 39 b[ j ] *= 2; 40 } 41 42 void modifyElement( int e ) 43 { 44 printf( "Value in modifyElement is %d", e *= 2 ); 45 }
13. /* Program to count the no of positive and negative numbers*/ #include< stdio.h > void main( ) { int a[50],n,count_neg=0,count_pos=0,I; printf(“Enter the size of the array”); scanf(“%d”,&n); printf(“Enter the elements of the array”); for(I=0;I < n;I++) scanf(“%d”,&a[I]); for(I=0;I < n;I++) { if(a[I] < 0) count_neg++; else count_pos++; } printf(“There are %d negative numbers in the array”,count_neg); printf(“There are %d positive numbers in the array”,count_pos); }
14.
15. Initialization of multidimensional arrays: Like the one dimension arrays, 2 dimension arrays may be initialized by following their declaration with a list of initial values enclosed in braces Example: Initializes the elements of first row to zero and second row to 1. int table[2][3]={{0,0,0},{1,1,1}} By surrounding the elements of each row by braces. C allows arrays of three or more dimensions. The compiler determines the maximum number of dimension. The general form of a multidimensional array declaration is: date_type array_name[s1][s2][s3]…..[sn]; Where s is the size of the ith dimension. Some examples are: int survey[3][5][12]; float table[5][4][5][3]; Survey is a 3 dimensional array declared to contain 180 integer elements. Similarly table is a four dimensional array containing 300 elements of floating point type.
16. example program to add two matrices & store the results in the 3rd matrix #include<stdio.h> #include<conio.h> void main() { int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q; clrscr(); printf("enter the order of first matrix:"); scanf("%d %d",&m,&n); printf("enter the order of the second matrix"); scanf("%d %d",&p,&q); if(m==p && n==q) { printf("matrix can be added"); printf("enter the elements of the matrix a"); for(i=0;i < m;i++) { for(j=0;j < n;j++) scanf("%d",&a[i][j]); } printf("enter the elements of the matrix b"); for(i=0;i < p;i++) { for(j=0;j < q;j++) scanf("%d",&b[i][j]); }
17. printf("the sum of the matrix a and b is"); for(i=0;i < m;i++) { for(j=0;j < n;j++) c[i][j]=a[i][j]+b[i][j]; } for(i=0;i < m;i++) { for(j=0;j < n;j++) printf("%d",c[i][j]); printf(""); } } }
18. Structure Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require using a collection of different data items of different data types we can use a structure. Structure is a method of packing data of different types. A structure is a convenient method of handling a group of related data items of different data types. G eneral format: struct tag_name { data type member1; data type member2; … … } Example: struct lib_books { char title[20]; char author[15]; int pages; float price; };
19. the keyword struct declares a structure to holds the details of four fields namely title, author pages and price. These are members of the structures. Each member may belong to different or same data type. The tag name can be used to define objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure. We can declare structure variables using the tag name any where in the program. For example the statement, struct lib_books book1, book2, book3; declares book1,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books. The complete structure declaration might look like this struct lib_books { char title[20]; char author[15]; int pages; float price; }; struct lib_books, book1, book2, book3; Structure Contd………
20. We can also combine both template declaration and variables declaration in one statement, the declaration struct lib_books { char title[20]; char author[15]; int pages; float price; } book1,book2,book3; is valid. book1, book2, book3 declares book1,book2,book3 as structure variables representing 3 books but does not include a tag name for use in the declaration. A structure is usually defines before main along with macro definitions. In such cases the structure assumes global status and all the functions can access the structure. Structure Contd………
21. Giving values to members: The link between a member and a structure variable is established using the member operator ‘.’ Which is known as dot operator or period operator. For example: Book1.price Is the variable representing the price of book1 and can be treated like any other ordinary variable. We can use scanf statement to assign values like scanf(“%s”,book1.file); scanf(“%d”,&book1.pages); book1.pages=250; book1.price=28.50;
22. #include<stdio.h> struct student { int id_no; char name[20]; char address[20]; int age; }newstudent; void main() { printf("Enter the student information"); printf("Now Enter the student id_no"); scanf("%d",&newstudent.id_no); printf("Enter the name of the student"); scanf("%s",&newstudent.name); printf("Enter the address of the student"); scanf("%s",&newstudent.address); printf("Enter the age of the student"); scanf("%d",&newstudent.age); printf("Student information"); printf("student id_number=%d",newstudent.id_no); printf("student name=%s",newstudent.name); printf("student Address=%s",newstudent.address); printf("Age of student=%d",newstudent.age); } EXAMPLE OF STRUCTURE
23. Initializing structure: Example: Struct student newstudent { 12345, “kapildev”, “Pes college”, 19; }; This initializes the id_no field to 12345, the name field to “kapildev”, the address field to “pes college” and the age field to 19.
24. Functions and structures: We can pass structures as arguments to functions. Unlike array names however, which always point to the start of the array, structure names are not pointers. As a result, when we change structure parameter inside a function, we don’t effect its corresponding argument. Passing structure to elements to functions: A structure may be passed into a function as individual member or a separate variable. A program example to display the contents of a structure passing the individual elements to a function is shown below. #include<stdio.h> struct emp { int emp_id; char name[25]; char department[10]; float salary; }; void display(int,char []); void main() { static struct emp emp1={125,"sampath","operator",7500.00}; display(emp1.emp_id,emp1.name); } /* function to display structure variables*/ void display(int e_no,char e_name[]) { printf("%d %s",e_no,e_name); }
25. Arrays of structure: It is possible to define a array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in the college. We need to use an array than single variables. We can define an array of structures as shown in the following example: structure information { int id_no; char name[20]; char address[20]; char combination[3]; int age; } student[100];
26. An array of structures can be assigned initial values just as any other array can. Remember that each element is a structure that must be assigned corresponding initial values as illustrated below. #include<stdio.h> void main() { struct info { int id_no; char name[20]; char address[20]; int age; }std[100]; int I,n; printf("Enter the number of students"); scanf("%d",&n); printf(" Enter Id_no,name address combination age"); for(I=0;I<n;I++) scanf ("%d%s%s%d", &std[I].id_no,std[I].name,std [I].address,&std[I].age); printf(" Student information"); for (I=0;I< n;I++) printf("%d %s %s %d",std[I].id_no,std[I].name,std[I].address,std[I].age ); }
27. Structure within a structure: A structure may be defined as a member of another structure. In such structures the declaration of the embedded structure must appear before the declarations of other structures. struct date { int day; int month; int year; }; struct student { int id_no; char name[20]; char address[20]; int age; struct date def; struct date doa; }oldstudent,newstudent; the sturucture student constains another structure date as its one of its members.
28. Union Unions like structure contain members whose individual data types may differ from one another. However the members that compose a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to observe memory. They are useful for application involving multiple members. Where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows: union item { int m; float p; char c; } code; this declares a variable code of type union item. The union contains three members each with a different data type. However we can use only one of them at a time. This is because if only one location is allocated for union variable irrespective of size. The compiler allocates a piece of storage that is large enough to access a union member we can use the same syntax that we use to access structure members. That is code.m code.p code.c are all valid member variables.
29. Pointers Pointer declaration: A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable. type *variable_name Example: int *ptr; float *ptr1; Address operator: Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example: ptr=# This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260.
30. /* A program to illustrate pointer declaration*/ #include<stdio.h> void main() { int *ptr; int num; num=45; ptr=# printf (“ num is %d”, num); printf (“ The num pointer is %d”,ptr); } Output: num is 45 The num pointer is 45
31. /* Program to display the contents of the variable their address using pointer variable*/ #include<stdio.h> void main() { int num, *intptr; float x, *floptr; char ch, *cptr; num=123; x=12.34; ch='a'; intptr=# cptr=&ch; floptr=&x; printf("Num %d stored at address %u",*intptr,intptr); printf("Value %f stored at address %u",*floptr,floptr); printf("Character %c stored at address %u",*cptr,cptr); }
32. Pointer expressions & pointer arithmetic Like other variables pointer variables can be used in expressions. For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid. y = *p1 * *p2; sum = sum + *p1; z = 5* - *p2/p1; *p2 = *p2 + 10; we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed.
33. /*Program to illustrate the pointer expression and pointer arithmetic*/ #include<stdio.h> #include<conio.h> void main() { int *ptr1,*ptr2; int a,b,x,y,z; clrscr(); a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2-6; y=6* (- *ptr1) / *ptr2 + 30; printf("Address of a %u",ptr1); printf("Address of b %u",ptr2); printf("a=%d, b=%d",a,b); printf("x=%d,y=%d",x,y); ptr1=ptr1 + 70; printf("a=%d, b=%d",a,b); printf("Adress of a %u",ptr1); getch(); }
34.
35. Pointers and function: The pointer are very much used in a function declaration. Sometimes only with a pointer a complex function can be easily represented and success. The usage of the pointers in a function definition may be classified into two groups. 1. Call by reference 2. Call by value. Call by value: We have seen that a function is invoked there will be a link established between the formal and actual parameters. A temporary storage is created where the value of actual parameters is stored. The formal parameters picks up its value from storage area the mechanism of data transfer between actual and formal parameters allows the actual parameters mechanism of data transfer is referred as call by value. The corresponding formal parameter represents a local variable in the called function. The current value of corresponding actual parameter becomes the initial value of formal parameter. The value of formal parameter may be changed in the body of the actual parameter. The value of formal parameter may be changed in the body of the subprogram by assignment or input statements. This will not change the value of actual parameters.
36. #include<stdio.h> void swap(int,int); void main() { int x,y; x=20; y=30; printf(" Value of x and y before function call =%d %d",x,y); swap(x,y); printf(" Value of x and y after function call =%d %d",x,y); } void swap(int p,int q) { int temp; temp=p; p=q; q=temp; } Output: Value of x and y before function call = 20 30 Value of x and y after function call = 20 30 Example of Call by Value
37. Call by Reference When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call. /* example of call by reference*? #include<stdio.h> void Swap(int *,int *); void main() { int x,y; x=20; y=30; printf(" Value of x and y before function call =%d %d",x,y); Swap(&x,&y); printf(" Value of x and y after function call =%d %d",x,y); } void Swap(int *p,int *q) { int temp; temp=*p; *p=*q; *q=temp; }
38.
39. Dynamic memory allocation: The process of allocating memory at run time is known as dynamic memory allocation . Although c does not inherently have this facility there are four library routines which allow this function. Many languages permit a programmer to specify an array size at run time. Such languages have the ability to calculate and assign during executions, the memory space required by the variables in the program. But c inherently does not have this facility but supports with memory management functions, which can be used to allocate and free memory during the program execution. The following functions are used in c for purpose of memory management. Function Task malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space calloc Allocates space for an array of elements initializes them to zero and returns a pointer to the memory free Frees previously allocated space realloc Modifies the size of previously allocated space.
40. Allocating a block of memory A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form: ptr=(cast_type *)malloc(byte-size); ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size. Example: x=(int *)malloc(100*sizeof(int)); On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int.
41. Allocating multiple blocks of memory Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is: ptr=(cast_type *) calloc(n,elem_size); The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.
42. Releasing the used space Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function. free(ptr); ptr is a pointer that has been created by using malloc or calloc.
43. To Alter the size of allocated memory The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is : ptr=realloc(ptr,newsize); This function allocates new memory space of size newsize to the pointer variable ptr and returns a pointer to the first byte of the memory block. The allocated new block may be or may not be at the same region.
45. Linked List A linked list is called so because each of items in the list is a part of a structure, which is linked to the structure containing the next item. This type of list is called a linked list since it can be considered as a list whose order is given by links from one item to the next. Structure Each item has a node consisting two fields one containing the variable and another consisting of address of the next item(i.e., pointer to the next item) in the list. A linked list is therefore a collection of structures ordered by logical links that are stored as the part of data. Consider the following example to illustrator the concept of linking. Suppose we define a structure as follows struct linked_list { float age; struct linked_list *next; } struct linked_list node1,node2; Item Item
46. Advantages of Linked List A linked list is a dynamic data structure and therefore the size of the linked list can grow or shrink in size during execution of the program. A linked list does not require any extra space therefore it does not waste extra memory. It provides flexibility in rearranging the items efficiently. The limitation of linked list is that it consumes extra space when compared to a array since each node must also contain the address of the next item in the list to search for a single item in a linked list is cumbersome and time consuming.
47. #include<stdio.h> #include<conio.h> #include<alloc.h> /* structure containing a data part and link part */ struct node { int data ; struct node *link ; }; void append(struct node **,int ); void display(struct node * ); void main( ) { struct node *p; p = NULL ; append ( &p, 14 ) ; append ( &p, 30 ) ; append ( &p, 25 ) ; append ( &p, 42 ) ; append ( &p, 17 ) ; display ( p ) ; } /* adds a node at the end of a linked list */ void append ( struct node **q, int num ) { struct node *temp, *r ; if (*q == NULL) { temp = malloc(sizeof(struct node)) ; temp -> data = num ; temp -> link = NULL ; *q = temp ; } else { temp = *q ; /* go to last node */ while ( temp -> link != NULL ) temp = temp -> link; /* add node at the end */ r = malloc ( sizeof ( struct node ) ) ; r -> data = num ; r -> link = NULL ; temp -> link = r ; } } void display ( struct node *q ) { printf ( "" ) ; /* traverse the entire linked list */ while ( q != NULL ) { printf (" %d ", q -> data ) ; q = q -> link ; } } Example of Linked List