SlideShare a Scribd company logo
1 of 33
Download to read offline
Computing Fundamentals
Dr. Muhammad Yousaf Hamza
Deputy Chief Engineer, PIEAS
STRUCTURES
Dr. Yousaf, PIEAS
//Structures //Collection of various types of variables
#include <stdio.h>
struct student //declares a structure
{
int rollnumber;
int semnumber;
double age_years;
}; // See the use of semicolon
int main()
{
struct student student1; /*defines a variable student1 of type structure*/
student1.rollnumber = 15;
student1.semnumber = 1;
student1.age_years = 18.5;
//Print the structure members
printf("Roll Nomber = %dn",student1.rollnumber);
printf("Semesetr Number = %dn",student1.semnumber);
printf("Age = %lfn",student1.age_years);
getchar(); return 0; }
Dr. Yousaf, PIEAS
• They make your programming easier.
• You can extend the language - for example, if you use
complex numbers a lot then you can write structures
and functions which deal with complex numbers.
• Structures are C’s way of grouping collections of
data into a single manageable unit.
– This is also the fundamental element of C upon which
most of C++ is built (i.e., classes).
– Similar to Java's classes.
Dr. Yousaf, PIEAS
Structures
Structures
• struct is used to describe a new data type.
• int, double and char are types of variables.
With struct you can create your own. It is a
new way to extend the C programming language.
• If programmers do a good job of this, the end
user doesn't even have to know what is in the
data type.
Dr. Yousaf, PIEAS
Structures
• An example:
– Defining a structure type:
struct student //declares a structure
{
int rollnumber;
int semnumber;
double age_years;
};
• This defines a new type struct student.
• No variable is actually declared or generated.
Dr. Yousaf, PIEAS
#include <stdio.h>
//group things together
struct database
{
int id_number;
int age;
float salary;
};
int main()
{
struct database employee;
employee.age = 22;
employee.id_number = 1;
employee.salary = 12000.21;
}
Structures
Dr. Yousaf, PIEAS
#include <stdio.h>
//group things together
struct database
{
int id_number;
int age;
float salary;
};
int main()
{
struct database employee;
employee.age = 22;
employee.id_number = 1;
employee.salary = 12000.21;
}
Structures
Dr. Yousaf, PIEAS
• Members of the structure
• No space in memory
• Accessing the members of
structure using Dot operator
// Program using Concept of
Structures
#include <stdio.h>
struct student //declares a structure
{
int rollnumber;
int semnumber;
double age_years;
}; // See the use of semicolon
int main()
{
struct student student1;
/*defines a variable student1 of
type structure */
struct student student2;
student1.rollnumber = 15;
student1.semnumber = 1;
student1.age_years = 18.5;
//Print the structure members
printf("Roll Nomber =
%dn",student1.rollnumber);
printf("Semesetr Number =
%dn",student1.semnumber);
printf("Age = %lfn",
student1.age_years);
student2.rollnumber = 22;
student2.semnumber = 1;
//Print the structure members
printf("nnRoll Nomber =
%dn",student2.rollnumber);
printf("Semesetr Number =
%dn",student2.semnumber);
getchar(); return 0;
}
Dr. Yousaf, PIEAS
/*More features of structures
Initialization of member variables
Program using Concept of
Structures*/
#include <stdio.h>
struct student //declares a structure
{
int rollnumber;
int semnumber;
double age_years;
}; // See the use of semicolon
int main()
{
struct student student1 =
{15,1,18.5}; /*defines a variable
student1 of type structure */
struct student student2;
//Print the structure members
printf("Roll Nomber =
%dn",student1.rollnumber);
printf("Semesetr Number =
%dn",student1.semnumber);
printf("Age =
%lfn",student1.age_years);
student2 = student1;
//Print the structure members
printf("nnRoll Nomber =
%dn",student2.rollnumber);
printf("Semesetr Number =
%dn",student2.semnumber);
printf("Age =
%lfn",student1.age_years);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
/*More features of structures
Initialization of member variables
Program using Concept of
Structures*/
#include <stdio.h>
struct student //declares a structure
{
int rollnumber;
int semnumber;
double age_years;
} student1, student2;
int main()
{
student1 = {15,1,18.5}; /*defines
a variable student1 of type
structure */
//Print the structure members
printf("Roll Nomber =
%dn",student1.rollnumber);
printf("Semesetr Number =
%dn",student1.semnumber);
printf("Age =
%lfn",student1.age_years);
student2 = student1;
//Print the structure members
printf("nnRoll Nomber =
%dn",student2.rollnumber);
printf("Semesetr Number =
%dn",student2.semnumber);
printf("Age =
%lfn",student1.age_years);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
• Define struct variables:
struct coord
{
int x,y ;
} first, second;
• Another Approach:
struct coord
{
int x,y ;
};
...............
struct coord first, second, third; /* declare variables */
Dr. Yousaf, PIEAS
Structures
• Access structure variables by the dot (.) operator
• Generic form:
structure_var.member_name
• For example:
first.x = 50 ;
second.y = 100;
• These member names are like the public data members
of a class in Java (or C++).
– No equivalent to function members/methods.
• struct_var.member_name can be used anywhere a
variable can be used:
– printf ("%d , %d", second.x , second.y );
– scanf("%d, %d", &first.x, &first.y);
Dr. Yousaf, PIEAS
Structures
• You can assign structures as a unit with =
first = second;
instead of writing:
first.x = second.x ;
first.y = second.y ;
• Although the saving here is not great
– It will reduce the likelihood of errors and
– Is more convenient with large structures
• This is different from Java where variables are simply
references to objects.
first = second;
makes first and second refer to the same object.
Dr. Yousaf, PIEAS
Structures
/* Addition of lengths using
concept of structures*/
#include <stdio.h>
struct AddLength
{
int feet;
float inches;
}; // See the use of semicolon
int main()
{
struct AddLength d1, d2, d3;
int carry;
puts("This program adds two
values of lengths");
puts("Enter the value of length in
feet and inches");
puts("Enter the value of feet
for first length");
scanf("%d", &d1.feet);
puts("Enter the value of inches
for first length");
scanf("%f", &d1.inches);
puts("Enter the value of feet
for second length");
scanf("%d", &d2.feet);
puts("Enter the value of inches
for second length");
scanf("%f", &d2.inches);
// continued to next slide
Dr. Yousaf, PIEAS
d3.inches = d1.inches + d2.inches;
carry = 0;
if (d3.inches >=12.0)
{
d3.inches -= 12.0;
carry++;
}
d3.feet = d1.feet + d2.feet + carry;
//Print the structure members
printf("First length = %d feet %f inchesn", d1.feet,d1.inches);
printf("Second length = %d feet %f inchesn", d2.feet,d2.inches);
printf("Addition of lengths = %d feet %f inchesn", d3.feet,d3.inches);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
• C program to add, subtract, multiply and divide
Complex Numbers
• C Program to add, subtract, multiply and divide
complex numbers :- This program performs basic
operations on complex numbers i.e addition,
subtraction, multiplication and division. This is a
menu driven program in which user will have to
enter his/her choice to perform an operation. User
can perform operations until desired. To easily
handle a complex number a structure named
complex has been used, which consists of two
integers first integer is for real part of a complex
number and second for imaginary part.
Dr. Yousaf, PIEAS
// C programming code for addition of
complex numbers
#include<stdio.h>
#include<stdlib.h>
struct complex
{
int real, img;
};
int main()
{
struct complex c1, c2, c3;
printf("Enter a and b where a + ib is the
first complex number.");
printf("na = ");
scanf("%d", &c1.real);
printf("b = ");
scanf("%d", &c1.img);
printf("Enter c and d where c + id is
the second complex number.");
printf("nc = ");
scanf("%d", &c2.real);
printf("d = ");
scanf("%d", &c2.img);
c3.real = c1.real + c2.real;
c3.img = c1.img + c2.img;
if ( c3.img >= 0 )
printf("Sum of two complex numbers
= %d + %di",c3.real,c3.img);
else
printf("Sum of two complex numbers
= %d %di",c3.real,c3.img);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
Solve a Problem
To represent a complex number, write a structure
complexNum , decide the members of the structure
and their type, create two variables of type
complexNum and initialize them from user input,
check whether the number are equal or not?
Dr. Yousaf, PIEAS
What else can we do with structs?
We can pass and return structs to/from
functions. But make sure the function prototype
is _AFTER_ the struct is declared.
Dr. Yousaf, PIEAS
/*Multiplication of complex numbers through function
using the concept of structures*/
struct complex
{
float imag;
float real;
};
complex mult_complex (complex no1, complex no2);
int main()
{
/* Main goes here */
}
// Definition of function
complex mult_complex (complex no1, complex no2)
{
struct complex answer;
answer.real= no1.real*no2.real - no1.imag*no2.imag;
answer.imag= no1.imag*no2.real + no1.real*no2.imag;
return answer;
} Dr. Yousaf, PIEAS
/*Multiplication of complex numbers through function
using the concept of structures*/
typedef struct complex
{
float imag;
float real;
} CPLX;
CPLX mult_complex (CPLX, CPLX);
int main()
{
CPLX n1,n2;
/* Main goes here */
}
// Definition of function
CPLX mult_complex (CPLX no1, CPLX no2)
{
CPLX answer;
answer.real= no1.real*no2.real - no1.imag*no2.imag;
answer.imag= no1.imag*no2.real + no1.real*no2.imag;
return answer;}
Dr. Yousaf, PIEAS
The typedef keyword is
used to create a new name
for an existing data type. In
fact, typedef creates a
synonym.
When typedef is used in
structure definition, then
don’t write struct for
variables declaration.
/*Multiplication of complex numbers through function
using the concept of structures*/
typedef struct // even no name here also works
{
float imag;
float real;
} CPLX;
CPLX mult_complex (CPLX, CPLX);
int main()
{
CPLX n1,n2;
/* Main goes here */
}
CPLX mult_complex (CPLX no1, CPLX no2)
{
CPLX answer;
answer.real= no1.real*no2.real - no1.imag*no2.imag;
answer.imag= no1.imag*no2.real + no1.real*no2.imag;
return answer; Dr. Yousaf, PIEAS
Structures Containing Arrays
• Arrays within structures are the same as any other
member element.
• For example:
struct record
{
float x;
char y [5] ;
} ;
Dr. Yousaf, PIEAS
An Example
#include <stdio.h>
struct data
{
float amount;
char fname[30];
char lname[30];
} rec;
int main ()
{
struct data rec;
printf ("Enter the donor's first and last names, n");
printf ("separated by a space: ");
scanf ("%s %s", rec.fname, rec.lname);
printf ("nEnter the donation amount: ");
scanf ("%f", &rec.amount);
printf ("nDonor %s %s gave $%.2f.n", rec.fname,rec.lname,rec.amount);
}
Dr. Yousaf, PIEAS
Arrays of Structures
Dr. Yousaf, PIEAS
Arrays of Structures
• The converse of a structure with arrays:
• Example:
struct entry
{
char fname [10] ;
char lname [12] ;
char phone [8] ;
} ;
struct entry list [1000];
• This creates a list of 1000 identical entry(s).
• Assignments:
list [1] = list [6];
strcpy (list[1].phone, list[6].phone);
list[6].phone[1] = list[3].phone[4] ;
Dr. Yousaf, PIEAS
Initializing Structures
• Simple example:
struct sale
{
char customer [20] ;
char item [20] ;
int amount ;
};
struct sale mysale = { “Mr. XYZ", “Biscuits", 10000 } ;
Dr. Yousaf, PIEAS
Initializing Structures
• Structures within structures:
struct customer
{
char firm [20] ;
char contact [25] ;
};
struct sale
{
struct customer buyer ;
char item [20] ;
int amount ;
} mysale =
{ { “Shaheen Industries", “Mr. XYZ"} ,
“Biscuits", 10000
} ;
Dr. Yousaf, PIEAS
// An Example
#include <stdio.h>
struct employee
{
char fname [20];
char lname [20];
char phone [10];
} ;
int main()
{
struct employee list[4];
int i;
for (i=0; i < 4; i++)
{
printf(Enter the data of employee %d:”, i+1)
printf ("nEnter first name: ");
scanf ("%s", list[i].fname);
printf ("Enter last name: ");
scanf ("%s", list[i].lname);
printf ("Enter phone in 123-4567 format: ");
scanf ("%s", list[i].phone);
}
printf ("nn");
for (i=0; i < 4; i++)
{
printf ("Name: %s %s", list[i].fname,
list[i].lname);
printf ("ttPhone: %sn", list[i].phone);
}
} Dr. Yousaf, PIEAS
Nested Structures
Dr. Yousaf, PIEAS
// Example of Nested structures
#include <stdio.h>
struct Distance
{
int feet;
float inches;
}; // observe the semicolon
struct Room //rectangular room
{
struct Distance length; //length of room
struct Distance width; //width of room
};
int main()
{
float l,w;
struct Room dining; /*dining is
of type Room*/
dining.length.feet = 13;
dining.length.inches = 6.5;
dining.width.feet = 10;
dining.width.inches = 0.0;
//convert length & width
l=dining.length.feet+
dining.length.inches/12;
w=dining.width.feet+
dining.width.inches/12;
//find area and display it
printf("Dining room area is %f
square feetn",l*w);
return 0; }
Dr. Yousaf, PIEAS
• Accessing nested Structured Members
dining.length.feet = 13;
• Initializing Nested Structures
Room dining = { {13, 6.5}, {10, 0.0} };
• Depth of Nesting
apartment1.laundry_room.washing_machine.width.feet
Dr. Yousaf, PIEAS
Nested Structures

More Related Content

Similar to C Language Lecture 21

Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiMuhammed Thanveer M
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and PointersPrabu U
 
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxINTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxDeepasCSE
 
VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4YOGESH SINGH
 
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfEasy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfsudhakargeruganti
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and StructuresGem WeBlog
 
Diploma ii cfpc- u-5.3 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.3 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.3 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.3 pointer, structure ,union and intro to file handlingRai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsITNet
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
 

Similar to C Language Lecture 21 (20)

Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxINTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
 
VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4
 
C Language Lecture 16
C Language Lecture 16C Language Lecture 16
C Language Lecture 16
 
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfEasy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and Structures
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Structures
StructuresStructures
Structures
 
Diploma ii cfpc- u-5.3 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.3 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.3 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.3 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objects
 
C Language Lecture 15
C Language Lecture 15C Language Lecture 15
C Language Lecture 15
 
Bc0037
Bc0037Bc0037
Bc0037
 
Oop concepts
Oop conceptsOop concepts
Oop concepts
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
Structure
StructureStructure
Structure
 
Structures
StructuresStructures
Structures
 

More from Shahzaib Ajmal

More from Shahzaib Ajmal (19)

C Language Lecture 22
C Language Lecture 22C Language Lecture 22
C Language Lecture 22
 
C Language Lecture 20
C Language Lecture 20C Language Lecture 20
C Language Lecture 20
 
C Language Lecture 19
C Language Lecture 19C Language Lecture 19
C Language Lecture 19
 
C Language Lecture 18
C Language Lecture 18C Language Lecture 18
C Language Lecture 18
 
C Language Lecture 17
C Language Lecture 17C Language Lecture 17
C Language Lecture 17
 
C Language Lecture 14
C Language Lecture 14C Language Lecture 14
C Language Lecture 14
 
C Language Lecture 13
C Language Lecture 13C Language Lecture 13
C Language Lecture 13
 
C Language Lecture 12
C Language Lecture 12C Language Lecture 12
C Language Lecture 12
 
C Language Lecture 11
C Language Lecture  11C Language Lecture  11
C Language Lecture 11
 
C Language Lecture 10
C Language Lecture 10C Language Lecture 10
C Language Lecture 10
 
C Language Lecture 9
C Language Lecture 9C Language Lecture 9
C Language Lecture 9
 
C Language Lecture 8
C Language Lecture 8C Language Lecture 8
C Language Lecture 8
 
C Language Lecture 7
C Language Lecture 7C Language Lecture 7
C Language Lecture 7
 
C Language Lecture 6
C Language Lecture 6C Language Lecture 6
C Language Lecture 6
 
C Language Lecture 5
C Language Lecture  5C Language Lecture  5
C Language Lecture 5
 
C Language Lecture 4
C Language Lecture  4C Language Lecture  4
C Language Lecture 4
 
C Language Lecture 3
C Language Lecture  3C Language Lecture  3
C Language Lecture 3
 
C Language Lecture 2
C Language Lecture  2C Language Lecture  2
C Language Lecture 2
 
C Language Lecture 1
C Language Lecture  1C Language Lecture  1
C Language Lecture 1
 

Recently uploaded

Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxAdelaideRefugio
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...Nguyen Thanh Tu Collection
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSean M. Fox
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...Nguyen Thanh Tu Collection
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFVivekanand Anglo Vedic Academy
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...EduSkills OECD
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024Borja Sotomayor
 
Scopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS PublicationsScopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS PublicationsISCOPE Publication
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....Ritu480198
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxMarlene Maheu
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project researchCaitlinCummins3
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code ExamplesPeter Brusilovsky
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17Celine George
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint23600690
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppCeline George
 

Recently uploaded (20)

Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
Scopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS PublicationsScopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS Publications
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 

C Language Lecture 21

  • 1. Computing Fundamentals Dr. Muhammad Yousaf Hamza Deputy Chief Engineer, PIEAS
  • 3. //Structures //Collection of various types of variables #include <stdio.h> struct student //declares a structure { int rollnumber; int semnumber; double age_years; }; // See the use of semicolon int main() { struct student student1; /*defines a variable student1 of type structure*/ student1.rollnumber = 15; student1.semnumber = 1; student1.age_years = 18.5; //Print the structure members printf("Roll Nomber = %dn",student1.rollnumber); printf("Semesetr Number = %dn",student1.semnumber); printf("Age = %lfn",student1.age_years); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 4. • They make your programming easier. • You can extend the language - for example, if you use complex numbers a lot then you can write structures and functions which deal with complex numbers. • Structures are C’s way of grouping collections of data into a single manageable unit. – This is also the fundamental element of C upon which most of C++ is built (i.e., classes). – Similar to Java's classes. Dr. Yousaf, PIEAS Structures
  • 5. Structures • struct is used to describe a new data type. • int, double and char are types of variables. With struct you can create your own. It is a new way to extend the C programming language. • If programmers do a good job of this, the end user doesn't even have to know what is in the data type. Dr. Yousaf, PIEAS
  • 6. Structures • An example: – Defining a structure type: struct student //declares a structure { int rollnumber; int semnumber; double age_years; }; • This defines a new type struct student. • No variable is actually declared or generated. Dr. Yousaf, PIEAS
  • 7. #include <stdio.h> //group things together struct database { int id_number; int age; float salary; }; int main() { struct database employee; employee.age = 22; employee.id_number = 1; employee.salary = 12000.21; } Structures Dr. Yousaf, PIEAS
  • 8. #include <stdio.h> //group things together struct database { int id_number; int age; float salary; }; int main() { struct database employee; employee.age = 22; employee.id_number = 1; employee.salary = 12000.21; } Structures Dr. Yousaf, PIEAS • Members of the structure • No space in memory • Accessing the members of structure using Dot operator
  • 9. // Program using Concept of Structures #include <stdio.h> struct student //declares a structure { int rollnumber; int semnumber; double age_years; }; // See the use of semicolon int main() { struct student student1; /*defines a variable student1 of type structure */ struct student student2; student1.rollnumber = 15; student1.semnumber = 1; student1.age_years = 18.5; //Print the structure members printf("Roll Nomber = %dn",student1.rollnumber); printf("Semesetr Number = %dn",student1.semnumber); printf("Age = %lfn", student1.age_years); student2.rollnumber = 22; student2.semnumber = 1; //Print the structure members printf("nnRoll Nomber = %dn",student2.rollnumber); printf("Semesetr Number = %dn",student2.semnumber); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 10. /*More features of structures Initialization of member variables Program using Concept of Structures*/ #include <stdio.h> struct student //declares a structure { int rollnumber; int semnumber; double age_years; }; // See the use of semicolon int main() { struct student student1 = {15,1,18.5}; /*defines a variable student1 of type structure */ struct student student2; //Print the structure members printf("Roll Nomber = %dn",student1.rollnumber); printf("Semesetr Number = %dn",student1.semnumber); printf("Age = %lfn",student1.age_years); student2 = student1; //Print the structure members printf("nnRoll Nomber = %dn",student2.rollnumber); printf("Semesetr Number = %dn",student2.semnumber); printf("Age = %lfn",student1.age_years); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 11. /*More features of structures Initialization of member variables Program using Concept of Structures*/ #include <stdio.h> struct student //declares a structure { int rollnumber; int semnumber; double age_years; } student1, student2; int main() { student1 = {15,1,18.5}; /*defines a variable student1 of type structure */ //Print the structure members printf("Roll Nomber = %dn",student1.rollnumber); printf("Semesetr Number = %dn",student1.semnumber); printf("Age = %lfn",student1.age_years); student2 = student1; //Print the structure members printf("nnRoll Nomber = %dn",student2.rollnumber); printf("Semesetr Number = %dn",student2.semnumber); printf("Age = %lfn",student1.age_years); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 12. • Define struct variables: struct coord { int x,y ; } first, second; • Another Approach: struct coord { int x,y ; }; ............... struct coord first, second, third; /* declare variables */ Dr. Yousaf, PIEAS Structures
  • 13. • Access structure variables by the dot (.) operator • Generic form: structure_var.member_name • For example: first.x = 50 ; second.y = 100; • These member names are like the public data members of a class in Java (or C++). – No equivalent to function members/methods. • struct_var.member_name can be used anywhere a variable can be used: – printf ("%d , %d", second.x , second.y ); – scanf("%d, %d", &first.x, &first.y); Dr. Yousaf, PIEAS Structures
  • 14. • You can assign structures as a unit with = first = second; instead of writing: first.x = second.x ; first.y = second.y ; • Although the saving here is not great – It will reduce the likelihood of errors and – Is more convenient with large structures • This is different from Java where variables are simply references to objects. first = second; makes first and second refer to the same object. Dr. Yousaf, PIEAS Structures
  • 15. /* Addition of lengths using concept of structures*/ #include <stdio.h> struct AddLength { int feet; float inches; }; // See the use of semicolon int main() { struct AddLength d1, d2, d3; int carry; puts("This program adds two values of lengths"); puts("Enter the value of length in feet and inches"); puts("Enter the value of feet for first length"); scanf("%d", &d1.feet); puts("Enter the value of inches for first length"); scanf("%f", &d1.inches); puts("Enter the value of feet for second length"); scanf("%d", &d2.feet); puts("Enter the value of inches for second length"); scanf("%f", &d2.inches); // continued to next slide Dr. Yousaf, PIEAS
  • 16. d3.inches = d1.inches + d2.inches; carry = 0; if (d3.inches >=12.0) { d3.inches -= 12.0; carry++; } d3.feet = d1.feet + d2.feet + carry; //Print the structure members printf("First length = %d feet %f inchesn", d1.feet,d1.inches); printf("Second length = %d feet %f inchesn", d2.feet,d2.inches); printf("Addition of lengths = %d feet %f inchesn", d3.feet,d3.inches); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 17. • C program to add, subtract, multiply and divide Complex Numbers • C Program to add, subtract, multiply and divide complex numbers :- This program performs basic operations on complex numbers i.e addition, subtraction, multiplication and division. This is a menu driven program in which user will have to enter his/her choice to perform an operation. User can perform operations until desired. To easily handle a complex number a structure named complex has been used, which consists of two integers first integer is for real part of a complex number and second for imaginary part. Dr. Yousaf, PIEAS
  • 18. // C programming code for addition of complex numbers #include<stdio.h> #include<stdlib.h> struct complex { int real, img; }; int main() { struct complex c1, c2, c3; printf("Enter a and b where a + ib is the first complex number."); printf("na = "); scanf("%d", &c1.real); printf("b = "); scanf("%d", &c1.img); printf("Enter c and d where c + id is the second complex number."); printf("nc = "); scanf("%d", &c2.real); printf("d = "); scanf("%d", &c2.img); c3.real = c1.real + c2.real; c3.img = c1.img + c2.img; if ( c3.img >= 0 ) printf("Sum of two complex numbers = %d + %di",c3.real,c3.img); else printf("Sum of two complex numbers = %d %di",c3.real,c3.img); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 19. Solve a Problem To represent a complex number, write a structure complexNum , decide the members of the structure and their type, create two variables of type complexNum and initialize them from user input, check whether the number are equal or not? Dr. Yousaf, PIEAS
  • 20. What else can we do with structs? We can pass and return structs to/from functions. But make sure the function prototype is _AFTER_ the struct is declared. Dr. Yousaf, PIEAS
  • 21. /*Multiplication of complex numbers through function using the concept of structures*/ struct complex { float imag; float real; }; complex mult_complex (complex no1, complex no2); int main() { /* Main goes here */ } // Definition of function complex mult_complex (complex no1, complex no2) { struct complex answer; answer.real= no1.real*no2.real - no1.imag*no2.imag; answer.imag= no1.imag*no2.real + no1.real*no2.imag; return answer; } Dr. Yousaf, PIEAS
  • 22. /*Multiplication of complex numbers through function using the concept of structures*/ typedef struct complex { float imag; float real; } CPLX; CPLX mult_complex (CPLX, CPLX); int main() { CPLX n1,n2; /* Main goes here */ } // Definition of function CPLX mult_complex (CPLX no1, CPLX no2) { CPLX answer; answer.real= no1.real*no2.real - no1.imag*no2.imag; answer.imag= no1.imag*no2.real + no1.real*no2.imag; return answer;} Dr. Yousaf, PIEAS The typedef keyword is used to create a new name for an existing data type. In fact, typedef creates a synonym. When typedef is used in structure definition, then don’t write struct for variables declaration.
  • 23. /*Multiplication of complex numbers through function using the concept of structures*/ typedef struct // even no name here also works { float imag; float real; } CPLX; CPLX mult_complex (CPLX, CPLX); int main() { CPLX n1,n2; /* Main goes here */ } CPLX mult_complex (CPLX no1, CPLX no2) { CPLX answer; answer.real= no1.real*no2.real - no1.imag*no2.imag; answer.imag= no1.imag*no2.real + no1.real*no2.imag; return answer; Dr. Yousaf, PIEAS
  • 24. Structures Containing Arrays • Arrays within structures are the same as any other member element. • For example: struct record { float x; char y [5] ; } ; Dr. Yousaf, PIEAS
  • 25. An Example #include <stdio.h> struct data { float amount; char fname[30]; char lname[30]; } rec; int main () { struct data rec; printf ("Enter the donor's first and last names, n"); printf ("separated by a space: "); scanf ("%s %s", rec.fname, rec.lname); printf ("nEnter the donation amount: "); scanf ("%f", &rec.amount); printf ("nDonor %s %s gave $%.2f.n", rec.fname,rec.lname,rec.amount); } Dr. Yousaf, PIEAS
  • 26. Arrays of Structures Dr. Yousaf, PIEAS
  • 27. Arrays of Structures • The converse of a structure with arrays: • Example: struct entry { char fname [10] ; char lname [12] ; char phone [8] ; } ; struct entry list [1000]; • This creates a list of 1000 identical entry(s). • Assignments: list [1] = list [6]; strcpy (list[1].phone, list[6].phone); list[6].phone[1] = list[3].phone[4] ; Dr. Yousaf, PIEAS
  • 28. Initializing Structures • Simple example: struct sale { char customer [20] ; char item [20] ; int amount ; }; struct sale mysale = { “Mr. XYZ", “Biscuits", 10000 } ; Dr. Yousaf, PIEAS
  • 29. Initializing Structures • Structures within structures: struct customer { char firm [20] ; char contact [25] ; }; struct sale { struct customer buyer ; char item [20] ; int amount ; } mysale = { { “Shaheen Industries", “Mr. XYZ"} , “Biscuits", 10000 } ; Dr. Yousaf, PIEAS
  • 30. // An Example #include <stdio.h> struct employee { char fname [20]; char lname [20]; char phone [10]; } ; int main() { struct employee list[4]; int i; for (i=0; i < 4; i++) { printf(Enter the data of employee %d:”, i+1) printf ("nEnter first name: "); scanf ("%s", list[i].fname); printf ("Enter last name: "); scanf ("%s", list[i].lname); printf ("Enter phone in 123-4567 format: "); scanf ("%s", list[i].phone); } printf ("nn"); for (i=0; i < 4; i++) { printf ("Name: %s %s", list[i].fname, list[i].lname); printf ("ttPhone: %sn", list[i].phone); } } Dr. Yousaf, PIEAS
  • 32. // Example of Nested structures #include <stdio.h> struct Distance { int feet; float inches; }; // observe the semicolon struct Room //rectangular room { struct Distance length; //length of room struct Distance width; //width of room }; int main() { float l,w; struct Room dining; /*dining is of type Room*/ dining.length.feet = 13; dining.length.inches = 6.5; dining.width.feet = 10; dining.width.inches = 0.0; //convert length & width l=dining.length.feet+ dining.length.inches/12; w=dining.width.feet+ dining.width.inches/12; //find area and display it printf("Dining room area is %f square feetn",l*w); return 0; } Dr. Yousaf, PIEAS
  • 33. • Accessing nested Structured Members dining.length.feet = 13; • Initializing Nested Structures Room dining = { {13, 6.5}, {10, 0.0} }; • Depth of Nesting apartment1.laundry_room.washing_machine.width.feet Dr. Yousaf, PIEAS Nested Structures