This presentation covers very frequently used standard library functions also called as inbuilt functions. a brief description about function and its declaration (syntax) is defined for help.
This presentation covers very frequently used standard library functions also called as inbuilt functions. a brief description about function and its declaration (syntax) is defined for help.
Programming Fundamentals Arrays and Strings imtiazalijoono
Programming Fundamentals
Arrays and Strings
• Arrays
• Initializing arrays
• Multidimensional arrays
• Arrays as arguments to functions
• Strings
• String functions
Accessing Individual Components
Declaring Arrays
Arrays: Example Garbage
Multidimensional Arrays
1) Write a C program using arrays that produces the multiplication of two 2x2 matrices.
3-Dimensional Array
Write a program of your own choice that makes use of arrays of more than 2 dimensions.
2-Dimensional Arrays
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
hey this is Rupendra choudhary..!! i shared my "c" lang ppt..!!! u just goto that ppt if u r in deep with "c" ..!!! i create after i hv played a much with "c"..(sorry bt ppt is slightly disturbd may be due to unsupportable msppt2010 by slideshare)...find me on rupendrachoudhary1990@gmail.com or https://rupendrachoudhary.wordpress.com
PowerPoint presentation of functions in C language. It will give you brief idea how function works in C along with its unique features like return statement.
Programming Fundamentals Arrays and Strings imtiazalijoono
Programming Fundamentals
Arrays and Strings
• Arrays
• Initializing arrays
• Multidimensional arrays
• Arrays as arguments to functions
• Strings
• String functions
Accessing Individual Components
Declaring Arrays
Arrays: Example Garbage
Multidimensional Arrays
1) Write a C program using arrays that produces the multiplication of two 2x2 matrices.
3-Dimensional Array
Write a program of your own choice that makes use of arrays of more than 2 dimensions.
2-Dimensional Arrays
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
hey this is Rupendra choudhary..!! i shared my "c" lang ppt..!!! u just goto that ppt if u r in deep with "c" ..!!! i create after i hv played a much with "c"..(sorry bt ppt is slightly disturbd may be due to unsupportable msppt2010 by slideshare)...find me on rupendrachoudhary1990@gmail.com or https://rupendrachoudhary.wordpress.com
PowerPoint presentation of functions in C language. It will give you brief idea how function works in C along with its unique features like return statement.
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Quality defects in TMT Bars, Possible causes and Potential Solutions.PrashantGoswami42
Maintaining high-quality standards in the production of TMT bars is crucial for ensuring structural integrity in construction. Addressing common defects through careful monitoring, standardized processes, and advanced technology can significantly improve the quality of TMT bars. Continuous training and adherence to quality control measures will also play a pivotal role in minimizing these defects.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxR&R Consult
CFD analysis is incredibly effective at solving mysteries and improving the performance of complex systems!
Here's a great example: At a large natural gas-fired power plant, where they use waste heat to generate steam and energy, they were puzzled that their boiler wasn't producing as much steam as expected.
R&R and Tetra Engineering Group Inc. were asked to solve the issue with reduced steam production.
An inspection had shown that a significant amount of hot flue gas was bypassing the boiler tubes, where the heat was supposed to be transferred.
R&R Consult conducted a CFD analysis, which revealed that 6.3% of the flue gas was bypassing the boiler tubes without transferring heat. The analysis also showed that the flue gas was instead being directed along the sides of the boiler and between the modules that were supposed to capture the heat. This was the cause of the reduced performance.
Based on our results, Tetra Engineering installed covering plates to reduce the bypass flow. This improved the boiler's performance and increased electricity production.
It is always satisfying when we can help solve complex challenges like this. Do your systems also need a check-up or optimization? Give us a call!
Work done in cooperation with James Malloy and David Moelling from Tetra Engineering.
More examples of our work https://www.r-r-consult.dk/en/cases-en/
Forklift Classes Overview by Intella PartsIntella Parts
Discover the different forklift classes and their specific applications. Learn how to choose the right forklift for your needs to ensure safety, efficiency, and compliance in your operations.
For more technical information, visit our website https://intellaparts.com
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...Amil Baba Dawood bangali
Contact with Dawood Bhai Just call on +92322-6382012 and we'll help you. We'll solve all your problems within 12 to 24 hours and with 101% guarantee and with astrology systematic. If you want to take any personal or professional advice then also you can call us on +92322-6382012 , ONLINE LOVE PROBLEM & Other all types of Daily Life Problem's.Then CALL or WHATSAPP us on +92322-6382012 and Get all these problems solutions here by Amil Baba DAWOOD BANGALI
#vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore#blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #blackmagicforlove #blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #Amilbabainuk #amilbabainspain #amilbabaindubai #Amilbabainnorway #amilbabainkrachi #amilbabainlahore #amilbabaingujranwalan #amilbabainislamabad
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfKamal Acharya
The College Bus Management system is completely developed by Visual Basic .NET Version. The application is connect with most secured database language MS SQL Server. The application is develop by using best combination of front-end and back-end languages. The application is totally design like flat user interface. This flat user interface is more attractive user interface in 2017. The application is gives more important to the system functionality. The application is to manage the student’s details, driver’s details, bus details, bus route details, bus fees details and more. The application has only one unit for admin. The admin can manage the entire application. The admin can login into the application by using username and password of the admin. The application is develop for big and small colleges. It is more user friendly for non-computer person. Even they can easily learn how to manage the application within hours. The application is more secure by the admin. The system will give an effective output for the VB.Net and SQL Server given as input to the system. The compiled java program given as input to the system, after scanning the program will generate different reports. The application generates the report for users. The admin can view and download the report of the data. The application deliver the excel format reports. Because, excel formatted reports is very easy to understand the income and expense of the college bus. This application is mainly develop for windows operating system users. In 2017, 73% of people enterprises are using windows operating system. So the application will easily install for all the windows operating system users. The application-developed size is very low. The application consumes very low space in disk. Therefore, the user can allocate very minimum local disk space for this application.
Overview of the fundamental roles in Hydropower generation and the components involved in wider Electrical Engineering.
This paper presents the design and construction of hydroelectric dams from the hydrologist’s survey of the valley before construction, all aspects and involved disciplines, fluid dynamics, structural engineering, generation and mains frequency regulation to the very transmission of power through the network in the United Kingdom.
Author: Robbie Edward Sayers
Collaborators and co editors: Charlie Sims and Connor Healey.
(C) 2024 Robbie E. Sayers
Courier management system project report.pdfKamal Acharya
It is now-a-days very important for the people to send or receive articles like imported furniture, electronic items, gifts, business goods and the like. People depend vastly on different transport systems which mostly use the manual way of receiving and delivering the articles. There is no way to track the articles till they are received and there is no way to let the customer know what happened in transit, once he booked some articles. In such a situation, we need a system which completely computerizes the cargo activities including time to time tracking of the articles sent. This need is fulfilled by Courier Management System software which is online software for the cargo management people that enables them to receive the goods from a source and send them to a required destination and track their status from time to time.
Explore the innovative world of trenchless pipe repair with our comprehensive guide, "The Benefits and Techniques of Trenchless Pipe Repair." This document delves into the modern methods of repairing underground pipes without the need for extensive excavation, highlighting the numerous advantages and the latest techniques used in the industry.
Learn about the cost savings, reduced environmental impact, and minimal disruption associated with trenchless technology. Discover detailed explanations of popular techniques such as pipe bursting, cured-in-place pipe (CIPP) lining, and directional drilling. Understand how these methods can be applied to various types of infrastructure, from residential plumbing to large-scale municipal systems.
Ideal for homeowners, contractors, engineers, and anyone interested in modern plumbing solutions, this guide provides valuable insights into why trenchless pipe repair is becoming the preferred choice for pipe rehabilitation. Stay informed about the latest advancements and best practices in the field.
About
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Technical Specifications
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
Key Features
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface
• Compatible with MAFI CCR system
• Copatiable with IDM8000 CCR
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
Application
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
2. FUNCTION
A Function is a sub-program, which contains one or
more statements and it performs some task when its
called.
A computer program cannot handle all the tasks by it
self. Instead its requests other program like entities –
called functions in C to get its tasks done.
A function is a self contained block of statements that
perform a coherent task of same kind
3. Why we use functions?
Writing functions avoids rewriting the same code over and
over.
Suppose that there is a section of code in a program that
calculates area of a circle. If later in the program we want to
calculate the area of a different circle, we wont like to write
the same instructions again.
Instead, we would prefer to jump to a “section of code” that
calculates area and then jump back to the place from where
we left off.
This section of code is nothing but a function.
4. Using functions it becomes easier to write programs and
keep track of what they are doing.
If the operation of a program can be divided in to separate
activities, and each activity placed in a different function,
then each could be written and checked more or less
independently.
Separating the code in to modular functions also makes the
pro-gram easier to design and understand.
Why we use functions?
5. TYPES
There are two different types of functions:
Pre-defined functions
User-defined functions
6. Pre-Defined Functions
The pre-defined functions or library functions are
built-in functions.
The user can use the functions, but cannot modify
those functions.
Example: sqrt(), main()
7. User-Defined Functions
The functions defined by the user for their
requirements are called user-defined functions.
Whenever it is needed, the user can modify this
function.
Example: sum(a,b)
8. Advantage of User-Defined Functions
The length of the source program can be reduced.
It is easy to locate errors.
It avoids coding of repeated instructions.
10. Function
Syntax for function definition
datatype function_name (parameters/arguments list)
{
local variable declaration;
…………………………
body of the function;
…………………………
return(expression);
}
11. How Function Works?
Once a function is called the control passes to the
called function.
The working of calling function is temporarily
stopped.
When the execution of called function is completed
then the control returns back to the calling function
and executes the next statement.
12.
13. Parameters
Actual Parameter
These are the parameters which are transferred from
the calling function to the called function.
Formal Parameter
These are the parameters which are used in the called
function.
14.
15. return Statement
The return statement may or may not send some
values to the calling function.
Syntax:
return; (or)
return (expression);
16. Function Prototypes
There are four types:
Function with no arguments and no return values.
Function with arguments and no return values.
Function with arguments and return values.
Function with no arguments and with return values.
17. Function with no arguments
and no return values
Here no data transfer takes place between the calling
function and the called function.
These functions act independently, i.e. they get input
and display output in the same block.
18.
19. Example
#include <stdio.h>
#include<conio.h>
void main() //calling function
{
void add();
add();
}
void add() //called function
{
int a,b,c;
printf("nEnter two number:");
scanf("%d%d",&a,&b);
c=a+b;
printf("nSum is:%d",c);
}
21. Function with arguments
and no return values
Here data transfer take place between the calling
function and the called function.
It is a one way data communication, i.e. the called
program receives data from calling program but it does
not return any value to the calling program.
25. Function with arguments
and return values
Here data transfer takes place between the calling
function and the called function as well as between
called function and calling function .
It is a two way data communication, i.e. the called
program receives data from calling program and it
returns some value to the calling program.
29. Function with no arguments
and with return values
Here data transfer takes place between the called
function and the calling function.
It is a one way data communication, i.e. the called
program does not any receive data from the calling
program but it returns some value to the calling
program.
33. Parameter Passing Methods
There are two different ways of passing parameters to a
method, they are:
Call by value
Call by reference
34. Call by value
Actual arguments are passed to the formal arguments.
Any changes made to the formal argument does not
affect the actual argument.
35. Example
#include <stdio.h>
#include<conio.h>
void main()
{
int x,y,change(int,int);
printf("nEnter value of x:");
scanf("%d",&x);
printf("nEnter value of y:");
scanf("%d",&y);
change(x,y);
printf("nnValues in the
Main()-->x=%d,y=%d",x,y);
}
int change(int a,int b)
{
int c;
c=a;
a=b;
b=c;
printf("nValues in the
Fuction --
>x=%d,y=%d",a,b);
}
36. Output
Enter value of x:5
Enter value of y:6
Values in the Function -->x=6,y=5
Values in the Main()-->x=5,y=6
37. Call by reference
Instead of passing values, the address of the argument
will be passed.
Any changes made to the formal argument will affect
the actual argument.
38. Example
#include <stdio.h>
#include<conio.h>
void main()
{
int x,y,change(int*,int*);
printf("nEnter value of
x:");
scanf("%d",&x);
printf("nEnter value of
y:");
scanf("%d",&y);
change(&x,&y);
printf("nnValues in
the Main()--
>x=%d,y=%d",x,y);
}
int change(int *a,int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
printf("nValues in the
Function --
>x=%d,y=%d",*a,*b);
}
39. Output
Enter value of x:5
Enter value of y:6
Values in the Function -->x=6,y=5
Values in the Main()-->x=6,y=5
40. Recursion
It is a process of calling the same function itself again and
again until some condition is satisfied.
Syntax:
func1()
{
………..
func1();
…………
}
41. Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
int rec(int);
printf("nEnter the number:");
scanf("%d",&a);
printf("The factorial of %d! is
%d",a,rec(a));
}
int rec(int x)
{
int f;
if(x==1)
return(1);
else
f=x*rec(x-1);
return(f);
}
Output:
Enter the number:5
The factorial of 5! is 120
43. Sum of natural numbers using recursion
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;
}
44. int sum(int n)
{
if (n != 0) // sum() function calls itself
return n + sum(n-1);
else
return n;
}
45. Library Function
Library functions are the pre-defined functions.
The library function provides functions like
mathematical, string manipulation etc,.
In order to use a library function, it is necessary to call
the appropriate header file at the beginning of the
program.
The header file informs the program of the name,
type, and number and type of arguments, of all of the
functions contained in the library in question.
A header file is called via the preprocessor statement.
46. Some Examples of Library
Functions
sqrt(x):
It is used to find the square root of x
Example: sqrt(36) is 6
abs(x):
It is used to find the absolute value of x
Example: abs(-36) is 36
pow(x,y):
It is used to find the value of xy
Example: pow(5,2) is 25
47. ceil(x):
It is used to find the smallest integer greater than or equal to x.
Example: ceil(7.7) is 8
floor(x):
returns the largest integer value less than or equal to x.
example: floor(7.5) is 6
rand():
It is used to generate a random number.
sin(x):
It is used to find the sine value of x
Example: sin(30) is 0.5
cos (x):
It is used to find the cosine value of x
Example: cos(30) is 0.86
48. tan(x):
It is used to find the tan value of x
Example: tan(30) is 0.577
toascii(x):
It is used to find the ASCII value of x
Example: toascii(a) is 97
toupper(x):
It is used to convert lowercase character to uppercase.
Example: toupper(‘a’) is A
tolower(x):
It is used to convert uppercase character to lowercase.
Example: tolower(‘A’) is a
50. printf("nThe absolute value of -6 is %d",abs(-6));
printf("nThe value of sin 45 is %f",sin(45));
printf("nThe uppercase of 'a' is %c",toupper('a'));
printf("nThe uppercase of 97 is %c",toupper(97));
getch();
}
51. Output:
Enter the number:6
The square root of 6 is 2.449490
The value of 6 power 2 is 36.000000
The ceiling of 6.7 is 7.000000
The floor of 6.7 is 6.000000
The absolute value of -6 is 6
The value of sin 45 is 0.850904
The uppercase of 'a' is A
The uppercase of 97 is A
52. Computation of Sine Series
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n;
float x, sum, t;
printf(" Enter the value for x : ");
scanf("%f",&x);
x=x*3.14159/180;
t=x;
sum=x;
53. /* Loop to calculate the value of Sine */
for(i=1;i<=n;i++)
{
t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
}
printf(" The value of Sin(%f) = %.4f",x,sum);
}
54. Random Number Generation
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Generates and prints 'count' random
// numbers in range [lower, upper].
void printRandoms(int lower, int upper, int count)
{
int i;
for (i = 0; i < count; i++) {
int num = (rand() %(upper - lower + 1)) + lower;
printf("%d ", num);
55. int main()
{
int lower = 10, upper = 20, count = 1;
// Use current time as
// seed for random generator
srand(time(0));
printRandoms(lower, upper, count);
return 0;
}
59. Pointers
Pointer is a variable that contains the address of
another variable i.e.. direct address of the memory
location.
Like any variable or constant, you must declare a
pointer before you can use it to store any variable
address.
62. Pointer Declaration
Syntax:
data-type *pointer-name;
data-type - Type of the data to
which the pointer points.
pointer-name - Name of the pointer
Example: int *a;
63. Accessing Variable through Pointer
If a pointer is declared and assigned to a variable, then
the variable can be accessed through the pointer.
Example:
int *a;
x=5;
a=&x;
70. Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
int *b,**c;
b=&a;
c=&b;
printf("n The Value of a = %d",a);
printf("n The Address of a = %u",&a);
printf("n The Value of b = %d",b);
printf("n The Address of b = %u",&b);
printf("n The Value of c = %d",c);
printf("n The Address of c = %u",&c);
}
71. Output
The Value of a = 10
The Address of a = 5001
The Value of b = 5001
The Address of b = 8000
The Value of c = 8000
The Address of c = 9000
72. Pointers and Arrays
The elements of the array can also be accessed through
a pointer.
Example
int a[3]={2,3,7};
int *b;
b=a;
77. Illustration of the example:
2 3 7 9 10
a[0] a[1] a[2] a[3] a[4]
8724 8726 8728 8730 8732
Array
Value
Address
78. Output
The Value of a[0] = 2
The Address of a[0] = 8724
The Value of a[1] = 3
The Address of a[1] = 8726
The Value of a[2] = 7
The Address of a[2] = 8728
The Value of a[3] = 9
The Address of a[3] = 8730
The Value of a[4] = 10
The Address of a[4] = 8732
81. Pointer Arithmetic
A pointer in c is an address, which is a numeric value.
Therefore, you can perform arithmetic operations on a
pointer just as you can on a numeric value.
here are four arithmetic operators that can be used on
pointers: ++, --, +, and –
To understand pointer arithmetic, let us consider
that ptr is an integer pointer which points to the
address 1000. Assuming 32-bit integers, let us perform
the following arithmetic operation on the pointer −
82. ptr++
After the above operation, the ptr will point to the
location 1004 because each time ptr is incremented, it
will point to the next integer location which is 4 bytes
next to the current location. This operation will move
the pointer to the next memory location without
impacting the actual value at the memory location.
If ptr points to a character whose address is 1000, then
the above operation will point to the location 1001
because the next character will be available at 1001.
83. Incrementing a Pointer
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr; /* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++)
{
printf("Address of var[%d] = %xn", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr ); /* move to the next location */
ptr++;
}
return 0;
}
85. Dynamic Memory Allocation
Since C is a structured language, it has some fixed
rules for programming.
One of it includes changing the size of an array.
An array is collection of items stored at continuous
memory locations.
86. If there is a requirement to change this length (size). For
Example,
If there is a situation where only 5 elements are needed
to be entered in this array. In this case, the remaining 4
indices are just wasting memory in this array. So there
is a requirement to lessen the length (size) of the array
from 9 to 5.
Take another situation. In this, there is an array of 9
elements with all 9 indices filled. But there is a need to
enter 3 more elements in this array. In this case 3
indices more are required. So the length (size) of the
array needs to be changed from 9 to 12.
This procedure is referred to as Dynamic Memory
Allocation in C.
87. Therefore, C Dynamic Memory Allocation can be
defined as a procedure in which the size of a data
structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks.
There are 4 library functions provided by C defined
under <stdlib.h> header file to facilitate dynamic
memory allocation in C programming. They are:
malloc()
calloc()
free()
realloc()
88. malloc()
“malloc” or “memory allocation” method in C is
used to dynamically allocate a single large block of
memory with the specified size.
It returns a pointer of type void which can be cast into
a pointer of any form.
It initializes each block with default garbage value.
Syntax
ptr = (cast-type*) malloc(byte-size)
Example:
ptr = (int*) malloc(100 * sizeof(int));
89.
90. Note:
If space is insufficient, allocation fails and returns a
NULL pointer.
91. #include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
92. }
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
93. Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
94. Calloc()
“calloc” or “contiguous allocation” method in C
is used to dynamically allocate the specified
number of blocks of memory of the specified type.
It initializes each block with a default value ‘0’.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in
memory for 25 elements each with the size of the
float.
95.
96. Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by calloc or not
if (ptr == NULL) {
97. printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0; }
98. cfree()
“free” method in C is used to dynamically de-allocate the memory.
The memory allocated using functions malloc() and calloc() is not de-
allocated on their own.
Hence the free() method is used, whenever the dynamic memory
allocation takes place. It helps to reduce wastage of memory by freeing it.
Syntax:
free(ptr);
99. Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Dynamically allocate memory using calloc()
ptr1 = (int*)calloc(n, sizeof(int));
100. // Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.n");
// Free the memory
free(ptr);
printf("Malloc Memory successfully freed.n");
// Memory has been successfully allocated
printf("nMemory successfully allocated using calloc.n");
102. realloc()
“realloc” or “re-allocation” method in C is used to
dynamically change the memory allocation of a
previously allocated memory.
In other words, if the memory previously allocated with
the help of malloc or calloc is insufficient, realloc can be
used to dynamically re-allocate memory.
re-allocation of memory maintains the already present
value and new blocks will be initialized with default
garbage value.
Syntax:
ptr = realloc(ptr, newSize); where ptr is reallocated with new
size 'newSize'.
103.
104. Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %dn", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
105. if (ptr == NULL) {
printf("Memory not allocated.n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
106. // Get the new size for the array
n = 10;
printf("nnEnter the new size of the array: %dn", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));
// Memory has been successfully allocated
printf("Memory successfully re-allocated using
realloc.n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
108. Card Shuffling and Dealing Simulation
Collection of playing cards is known as deck
A deck of card contains 52 cards.
There are 4 suits and each 4 suits contains 13 faces
The 4 suits are
Hearts, Diamonds, Clubs, Spades
The 13 faces are
Ace, Deuce, Three, Four, Five, Six, Seven, Eight, Nine,
Ten, Jack, Queen, King