SlideShare a Scribd company logo
Structures
Structures - C Programming - Union - Basic Programming
Structures - C Programming - Union - Basic Programming
Structures - C Programming - Union - Basic Programming
Structures - C Programming - Union - Basic Programming
Structures - C Programming - Union - Basic Programming
• Write a C program to add two distances (in inch-feet system) using
Structures
• Structure name is Distance
• Two members – feet as integer, inch as float
• Three structure variables - d1,d2,result
• Get d1 and d2 from the user. Then add and get the result
• Convert inches to feet if it is greater than or equal to 12
• Print the final result
#include <stdio.h>
struct Distance {
int feet;
float inch;
} d1, d2, result;
int main() {
// take first distance input
printf("Enter 1st distancen");
printf("Enter feet: ");
scanf("%d", &d1.feet);
printf("Enter inch: ");
scanf("%f", &d1.inch);
// take second distance input
printf("nEnter 2nd distancen");
printf("Enter feet: ");
scanf("%d", &d2.feet);
printf("Enter inch: ");
scanf("%f", &d2.inch);
// adding distances
result.feet = d1.feet + d2.feet;
result.inch = d1.inch + d2.inch;
// convert inches to feet if greater than 12
while (result.inch >= 12.0) {
result.inch = result.inch - 12.0;
++result.feet;
}
printf("nSum of distances = %d'-%.1f"", result.feet,
result.inch);
return 0;
}
Structures - C Programming - Union - Basic Programming
Structures - C Programming - Union - Basic Programming
Structures - C Programming - Union - Basic Programming
Passing structs to functions
#include <stdio.h>
struct student {
char name[50];
int age;
};
// function prototype
void display(struct student s);
int main() {
struct student s1;
printf("Enter name: ");
gets(s1.name);
printf("Enter age: ");
scanf("%d", &s1.age);
display(s1); // passing struct as an argument
return 0;
}
void display(struct student s) {
printf("nDisplaying informationn");
printf("Name: %s", s.name);
printf("nAge: %d", s.age);
}
Return struct from a function
#include <stdio.h>
struct student
{
char name[50];
int age;
};
// function prototype
struct student getInformation();
struct student getInformation()
{
struct student s1;
printf("Enter name: ");
gets(s1.name);
printf("Enter age: ");
scanf("%d", &s1.age);
return s1;
}
int main()
{
struct student s;
s = getInformation();
printf("nDisplaying informationn");
printf("Name: %s", s.name);
printf("nRoll: %d", s.age);
return 0;
}
Passing struct by reference – Example
1
#include <stdio.h>
typedef struct Complex
{
float real;
float imag;
} complex;
void addNumbers(complex c1,
complex c2, complex *result);
int main()
{
complex c1, c2, result;
printf("For first number,n");
printf("Enter real part: ");
scanf("%f", &c1.real);
printf("Enter imaginary part: ");
scanf("%f", &c1.imag);
printf("For second number, n");
printf("Enter real part: ");
scanf("%f", &c2.real);
printf("Enter imaginary part: ");
scanf("%f", &c2.imag);
addNumbers(c1, c2, &result);
printf("nresult.real = %.1fn", result.real);
printf("result.imag = %.1f", result.imag);
return 0;
}
void addNumbers(complex c1, complex c2,
complex *result)
{
result->real = c1.real + c2.real;
result->imag = c1.imag + c2.imag;
}
Passing struct by reference – Example
2
Union
Unions
Union
• Only store information in one field at any one time
• When a new value is assigned to a field, existing data is replaced with
the new data.
• Thus unions are used to save memory.
• They are useful for applications that involve multiple members, where
values need not be assigned to all the members at any one time.
Declaration & initialization of union
• Like structures, an union can be declared with the keyword union
union student
{
int marks;
char gender;
};
• To access the members of the union, use the dot operator (.)
Declaration &
initialization of
union
• Unlike structures, initialization cannot be done to all members together.
#include <stdio.h>
typedef struct point1
{
int x,y;
};
typedef union point2
{
int x;
int y;
};
main()
{
point1 p1={2,3};
// point p2={4,5}; illegal with union
point2 p2;
p2.x=4;
p2.y=5;
printf(“The coordinates of p1 are % and %d”, p1.x,p1.y);
printf(“The coordinates of p2 are % and %d”, p2.x,p2.y);
}
Wrong output
• Output
The coordinated of p1 are 2 and 3
The coordinated of p2 are 5 and 5
//Corrected program
#include <stdio.h>
struct point1
{
int x,y;
};
union point2
{
int x,y;
};
main()
{
struct point1 p1={2,3};
// point p2={4,5}; illegal with union
union point2 p2;
p2.x=4;
printf("The coordinates of p1 are %d and %d n", p1.x,p1.y);
printf("The x coordinates of p2 is %d n", p2.x);
p2.y=5;
printf("The y coordinates of p2 is %d", p2.y);
}
Correct output
• Output:
The coordinates of p1 are 2 and 3
The x coordinates of p2 are 4
The y coordinates of p2 are 5
Another example
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %dn", data.i);
data.f = 220.5;
printf( "data.f : %fn", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %sn", data.str);
return 0;
}
Difference between structure & union
Ad

More Related Content

Similar to Structures - C Programming - Union - Basic Programming (20)

Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
WondimuBantihun1
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
VAIBHAVKADAGANCHI
 
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04
Sivakumar M
 
Object Oriented Programming (OOP) using C++ - Lecture 1
Object Oriented Programming (OOP) using C++ - Lecture 1Object Oriented Programming (OOP) using C++ - Lecture 1
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
3- In the program figurespointers we have a base class location and va.pdf
3- In the program figurespointers we have a base class location and va.pdf3- In the program figurespointers we have a base class location and va.pdf
3- In the program figurespointers we have a base class location and va.pdf
atozshoppe
 
LMmanual.pdf
LMmanual.pdfLMmanual.pdf
LMmanual.pdf
NarutoUzumaki413489
 
Unit3 overview of_c_programming
Unit3 overview of_c_programmingUnit3 overview of_c_programming
Unit3 overview of_c_programming
Capuchino HuiNing
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
Umesh Nikam
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONSPPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
Sitamarhi Institute of Technology
 
C and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfC and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdf
janakim15
 
L7 pointers
L7 pointersL7 pointers
L7 pointers
Kathmandu University
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
HimanshuSharma997566
 
Report on Flutter.docx prasentation for study
Report on Flutter.docx prasentation for studyReport on Flutter.docx prasentation for study
Report on Flutter.docx prasentation for study
HetalVasava9
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
LidetAdmassu
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
AnkurSingh656748
 
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
RSathyaPriyaCSEKIOT
 
VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4
YOGESH SINGH
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
GebruGetachew2
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
ANUSUYA S
 
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04
Sivakumar M
 
3- In the program figurespointers we have a base class location and va.pdf
3- In the program figurespointers we have a base class location and va.pdf3- In the program figurespointers we have a base class location and va.pdf
3- In the program figurespointers we have a base class location and va.pdf
atozshoppe
 
Unit3 overview of_c_programming
Unit3 overview of_c_programmingUnit3 overview of_c_programming
Unit3 overview of_c_programming
Capuchino HuiNing
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
Umesh Nikam
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONSPPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
PPS 6.6.FUNCTION INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS
Sitamarhi Institute of Technology
 
C and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfC and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdf
janakim15
 
Report on Flutter.docx prasentation for study
Report on Flutter.docx prasentation for studyReport on Flutter.docx prasentation for study
Report on Flutter.docx prasentation for study
HetalVasava9
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
LidetAdmassu
 
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
RSathyaPriyaCSEKIOT
 
VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4
YOGESH SINGH
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
GebruGetachew2
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
ANUSUYA S
 

More from BharaniDharan195623 (6)

NOISE PERFORMANCE IN FM RECEIVERS - Figure of Merit
NOISE PERFORMANCE IN FM RECEIVERS - Figure of MeritNOISE PERFORMANCE IN FM RECEIVERS - Figure of Merit
NOISE PERFORMANCE IN FM RECEIVERS - Figure of Merit
BharaniDharan195623
 
Histogram equalization and matching - Digital Image Processing
Histogram equalization and matching - Digital Image ProcessingHistogram equalization and matching - Digital Image Processing
Histogram equalization and matching - Digital Image Processing
BharaniDharan195623
 
Image enhancement techniques - Digital Image Processing
Image enhancement techniques - Digital Image ProcessingImage enhancement techniques - Digital Image Processing
Image enhancement techniques - Digital Image Processing
BharaniDharan195623
 
Pulse Amplitude Modulation - Analog communication
Pulse Amplitude Modulation - Analog communicationPulse Amplitude Modulation - Analog communication
Pulse Amplitude Modulation - Analog communication
BharaniDharan195623
 
TOS based Embedded system design and development
TOS based Embedded system design and developmentTOS based Embedded system design and development
TOS based Embedded system design and development
BharaniDharan195623
 
Configuration of IoT devices - Systems managament
Configuration of IoT devices - Systems managamentConfiguration of IoT devices - Systems managament
Configuration of IoT devices - Systems managament
BharaniDharan195623
 
NOISE PERFORMANCE IN FM RECEIVERS - Figure of Merit
NOISE PERFORMANCE IN FM RECEIVERS - Figure of MeritNOISE PERFORMANCE IN FM RECEIVERS - Figure of Merit
NOISE PERFORMANCE IN FM RECEIVERS - Figure of Merit
BharaniDharan195623
 
Histogram equalization and matching - Digital Image Processing
Histogram equalization and matching - Digital Image ProcessingHistogram equalization and matching - Digital Image Processing
Histogram equalization and matching - Digital Image Processing
BharaniDharan195623
 
Image enhancement techniques - Digital Image Processing
Image enhancement techniques - Digital Image ProcessingImage enhancement techniques - Digital Image Processing
Image enhancement techniques - Digital Image Processing
BharaniDharan195623
 
Pulse Amplitude Modulation - Analog communication
Pulse Amplitude Modulation - Analog communicationPulse Amplitude Modulation - Analog communication
Pulse Amplitude Modulation - Analog communication
BharaniDharan195623
 
TOS based Embedded system design and development
TOS based Embedded system design and developmentTOS based Embedded system design and development
TOS based Embedded system design and development
BharaniDharan195623
 
Configuration of IoT devices - Systems managament
Configuration of IoT devices - Systems managamentConfiguration of IoT devices - Systems managament
Configuration of IoT devices - Systems managament
BharaniDharan195623
 
Ad

Recently uploaded (20)

01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
PawachMetharattanara
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
Personal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.pptPersonal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.ppt
ganjangbegu579
 
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Journal of Soft Computing in Civil Engineering
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
acid base ppt and their specific application in food
acid base ppt and their specific application in foodacid base ppt and their specific application in food
acid base ppt and their specific application in food
Fatehatun Noor
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
PawachMetharattanara
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
Personal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.pptPersonal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.ppt
ganjangbegu579
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
acid base ppt and their specific application in food
acid base ppt and their specific application in foodacid base ppt and their specific application in food
acid base ppt and their specific application in food
Fatehatun Noor
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Ad

Structures - C Programming - Union - Basic Programming

  • 7. • Write a C program to add two distances (in inch-feet system) using Structures • Structure name is Distance • Two members – feet as integer, inch as float • Three structure variables - d1,d2,result • Get d1 and d2 from the user. Then add and get the result • Convert inches to feet if it is greater than or equal to 12 • Print the final result
  • 8. #include <stdio.h> struct Distance { int feet; float inch; } d1, d2, result; int main() { // take first distance input printf("Enter 1st distancen"); printf("Enter feet: "); scanf("%d", &d1.feet); printf("Enter inch: "); scanf("%f", &d1.inch); // take second distance input printf("nEnter 2nd distancen"); printf("Enter feet: "); scanf("%d", &d2.feet); printf("Enter inch: "); scanf("%f", &d2.inch); // adding distances result.feet = d1.feet + d2.feet; result.inch = d1.inch + d2.inch; // convert inches to feet if greater than 12 while (result.inch >= 12.0) { result.inch = result.inch - 12.0; ++result.feet; } printf("nSum of distances = %d'-%.1f"", result.feet, result.inch); return 0; }
  • 12. Passing structs to functions #include <stdio.h> struct student { char name[50]; int age; }; // function prototype void display(struct student s); int main() { struct student s1; printf("Enter name: "); gets(s1.name); printf("Enter age: "); scanf("%d", &s1.age); display(s1); // passing struct as an argument return 0; } void display(struct student s) { printf("nDisplaying informationn"); printf("Name: %s", s.name); printf("nAge: %d", s.age); }
  • 13. Return struct from a function #include <stdio.h> struct student { char name[50]; int age; }; // function prototype struct student getInformation(); struct student getInformation() { struct student s1; printf("Enter name: "); gets(s1.name); printf("Enter age: "); scanf("%d", &s1.age); return s1; } int main() { struct student s; s = getInformation(); printf("nDisplaying informationn"); printf("Name: %s", s.name); printf("nRoll: %d", s.age); return 0; }
  • 14. Passing struct by reference – Example 1 #include <stdio.h> typedef struct Complex { float real; float imag; } complex; void addNumbers(complex c1, complex c2, complex *result); int main() { complex c1, c2, result; printf("For first number,n"); printf("Enter real part: "); scanf("%f", &c1.real); printf("Enter imaginary part: "); scanf("%f", &c1.imag); printf("For second number, n"); printf("Enter real part: "); scanf("%f", &c2.real); printf("Enter imaginary part: "); scanf("%f", &c2.imag); addNumbers(c1, c2, &result); printf("nresult.real = %.1fn", result.real); printf("result.imag = %.1f", result.imag); return 0; } void addNumbers(complex c1, complex c2, complex *result) { result->real = c1.real + c2.real; result->imag = c1.imag + c2.imag; }
  • 15. Passing struct by reference – Example 2
  • 16. Union
  • 18. Union • Only store information in one field at any one time • When a new value is assigned to a field, existing data is replaced with the new data. • Thus unions are used to save memory. • They are useful for applications that involve multiple members, where values need not be assigned to all the members at any one time.
  • 19. Declaration & initialization of union • Like structures, an union can be declared with the keyword union union student { int marks; char gender; }; • To access the members of the union, use the dot operator (.)
  • 20. Declaration & initialization of union • Unlike structures, initialization cannot be done to all members together. #include <stdio.h> typedef struct point1 { int x,y; }; typedef union point2 { int x; int y; }; main() { point1 p1={2,3}; // point p2={4,5}; illegal with union point2 p2; p2.x=4; p2.y=5; printf(“The coordinates of p1 are % and %d”, p1.x,p1.y); printf(“The coordinates of p2 are % and %d”, p2.x,p2.y); }
  • 21. Wrong output • Output The coordinated of p1 are 2 and 3 The coordinated of p2 are 5 and 5
  • 22. //Corrected program #include <stdio.h> struct point1 { int x,y; }; union point2 { int x,y; }; main() { struct point1 p1={2,3}; // point p2={4,5}; illegal with union union point2 p2; p2.x=4; printf("The coordinates of p1 are %d and %d n", p1.x,p1.y); printf("The x coordinates of p2 is %d n", p2.x); p2.y=5; printf("The y coordinates of p2 is %d", p2.y); }
  • 23. Correct output • Output: The coordinates of p1 are 2 and 3 The x coordinates of p2 are 4 The y coordinates of p2 are 5
  • 24. Another example #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; printf( "data.i : %dn", data.i); data.f = 220.5; printf( "data.f : %fn", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %sn", data.str); return 0; }
  翻译: