0% found this document useful (0 votes)
78 views

Lecture Notes - Unit 5

This document describes a course on problem solving and programming using C. The key points are: 1. The course aims to teach students how to formulate algorithms, translate them into C programs, write, execute and test programs. It covers conditional branching, iteration, recursion, arrays, pointers, structures, and solving numerical problems. 2. The learning objectives are to acquire knowledge of problem solving techniques and to use appropriate data types, control structures, arrays, pointers, functions, and structures to solve problems. 3. The assessment includes two exams, assignments, and an end semester exam. Sources of content include online courses and lectures.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

Lecture Notes - Unit 5

This document describes a course on problem solving and programming using C. The key points are: 1. The course aims to teach students how to formulate algorithms, translate them into C programs, write, execute and test programs. It covers conditional branching, iteration, recursion, arrays, pointers, structures, and solving numerical problems. 2. The learning objectives are to acquire knowledge of problem solving techniques and to use appropriate data types, control structures, arrays, pointers, functions, and structures to solve problems. 3. The assessment includes two exams, assignments, and an end semester exam. Sources of content include online courses and lectures.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

U18CSI1202

PROBLEM SOLVING AND PROGRAMMING USING C


Course Name:PROBLEM SOLVING AND PROGRAMMING USING C
Course Number: U18CSI1202
Credits: 3
Pre-requisite: Nil

Course Description:
This course is aimed at enabling the students to

·  Formulate simple algorithms for arithmetic and logical problems


·  Translate the algorithms to programs (in C language)
·  Write, execute and test the programs .
·  Implement conditional branching, iteration and recursion
·  Decompose a problem into functions and synthesize a complete program using divide
and conquer approach
·  Use arrays, pointers and structures to formulate algorithms and programs
·  Apply programming to solve matrix problems, searching and sorting problems 
Apply programming to solve simple numerical method problems, namely root finding,
differentiation of function and simple integration
Learning Objectives
• After undergoing this course the student able
to
COs

CO1 Acquire knowledge on different problem solving techniques.


CO2 Use appropriate data types and control structures for solving a given problem.
CO3 Execute different array and string operations.
CO4 Experiment with the usage of pointers and functions.
CO5 Organize data using structures and unions.
Source of Content
• https://courses.edx.org/dashboard
• https://www.khanacademy.org/
• https://www.youtube.com/watch?v=h-HBipu_1P0
• https://ocw.mit.edu/courses/electrical-engineering-
and-computer-science/6-s096-effective-programmi
ng-in-c-and-c-january-iap-2014/
• https://ocw.mit.edu/courses/electrical-engineering-
and-computer-science/6-087-practical-
programming-in-c-january-iap-2010/lecture-notes/
Grading

CAT (2 Exams each 25%) 50%

10 Assignments (1% at each) 10%

End semester exam 40%

Total 100%
Lecture Notes
UNIT V

STRUCTURE, UNION AND TYPEDEF


Learning Objectives
❏ To introduce the structure, union, and
typedef
❏ To declaring, Initializing, Accessing a
structure and use structures in programs
❏ To be able to use unions in programs
❏ To understand the typedef concept.
STRUCTURE
Introduction of C Structure
A structure is a collection of related elements, possibly of
different types, having a single name.
Many structure variables can be declared for same structure and
memory will be allocated for each separately.
Struct is keyword used
Structure is heterogeneous data where as array is homogeneous

Note
Elements in a structure can be of the same or different types. However, all elements in
the structure should be logically related.
C Variable, C Array and C Structure
 A normal C variable can hold only one data of one data type
at a time.
 An array can hold group of data of same data type.
 A structure can hold group of data of different data types
 Data types can be int, char, float, double and long double
etc.

Figure 1 Structure Example


Figure 2 Tagged Structure Format
Data C variable C array C structure
Syntax Exampl Syntax Example Syntax Example
type
e

int int a a = 20 int a[3] a[0] = 10


struct student a = 10
a[1] = 20
{ b = “Hello”
a[2] = 30
int a;
a[3] = ‘\0′
char b[10];
char char What
b b=’Z’ does this
char b[10] program
b=”Hello” } do?

Figure 3 Example
Structure Declaration Format and Example

Declaring a Structure using a


pointer variable:
struct student *report, rep;

Figure-4 Structure Declaration Format and Example

• SYNTAX

struct tag_name struct student


{ {
data type var_name1; int  id;
data type var_name2; char name[10];
data type var_name3; float percentage;
}member variable; } report;
Initializing a Structure variable

Initializing a Structure variable using a


normal variable

struct student report = {100, “Mani”, 99.5};

Using a pointer variable

struct student rep={100,“Mani”,99.5};


report = &rep;

Figure 5- Initializing Structures


Accessing a structure variable

• It cannot access members of a • Example


structure directly in any expression by
specifying their name alone.
Using a normal variable:
• There are two ways to access report.id
structure members report.name
1.Using Member Access Operator(.) report.percentage
or Dot Operator Using a pointer variable:
structure_variable.member_name;
report  -> id
2.Using Member Structure Pointer
Operator or Arrow Operator(->) report -> name
structure_pointer->member_name; report ->percentage

Figure 6 Structure Direct Selection Operator


Example of structure // 3rd student's record
  record[2].id=3;
struct student strcpy(record[2].name,"Thiyagu");
{ record[2].percentage = 81.5; 
int id; for(i=0; i<3; i++)
char name[30]; {
float percentage; printf(" Records of STUDENT : %d \n", i+1);
};  printf(" Id is: %d \n", record[i].id);
int main() printf("Name is: %s \n", record[i].name);
{ printf(" Percentage is: %f\n\n",record[i].percentage);
int i;
struct student record[2];  } return 0;} of STUDENT : 1
Records
Id is: 1
//1st student's record
Name is: Raju
record[0].id=1; Percentage is: 86.500000
strcpy(record[0].name,"Raju"); Records of STUDENT : 2
record[0].percentage = 86.5;  Id is: 2
// 2nd student's record Name is: Surendren
Percentage is: 90.500000
record[1].id=2;
Records of STUDENT : 3
strcpy(record[1].name,"Surendren"); Id is: 3
record[1].percentage = 90.5;  Name is: Thiyagu
Percentage is: 81.500000
C – Passing struct to function

 A structure can be passed to any function from main function or


from any sub function.
 Structure definition will be available within the function only.
 Passing structure to function in C:
It can be done in below 3 ways.
1. Passing structure to a function by value

2. Passing structure to a function by address(reference)


3. No need to pass a structure – Declare structure variable as global
Example- passing structure to function in C by value

struct student { void func(struct student record)


int id; {
char name[20]; printf(" Id is: %d \n", record.id);
float percentage;};  printf(" Name is: %s \n", record.name);
void func(struct student record);
printf(" Percentage is: %f \n",
 int main() { record.percentage);
struct student record;  }
record.id=1;
Id is: 1
strcpy(record.name, "Raju");
Name is: Raju

record.percentage = 86.5;  Percentage is: 86.500000


func(record);
return 0;
}
 
Example-To declare a structure variable as global in C
struct student
{
void structure demo()
int id;
{
char name[20];
float percentage; printf(" Id is: %d \n", record.id);
}; printf(" Name is: %s \n", record.name);
struct student record; // Global
declaration of structure void printf(" Percentage is: %f \n",
structure_demo(); 
record.percentage);
int main()
{ }
Id is: 1
record.id=1;
Name is: Raju
strcpy(record.name, "Raju");
Percentage is: 86.500000
record.percentage = 86.5; 
structure_demo();
return 0;} 
Structure using Pointers
 A pointer to a structure is not itself a structure, but merely a variable that
holds the address of a structure. .
 Declaring pointers to structures is basically the same as declaring a normal
pointer.
 There are many reasons for using a pointer to a struct. One of them is to
make a two-way communication possible within functions.
(*pointerName).fieldName « pointerName->fieldName.

Figure-7 Pointers to Structures


Structure using Pointers-Example
struct tag_name struct student
{ { int id;
data_type member_name_1; char name[30];
float percentage;}; 
data_type member_name_2;
int main()
...
{ int i;
data_type member_name_n; struct student record1 = {1, "Raju", 90.5};
}*pointer member variable; struct student *ptr; 
ptr = &record1;  
printf("Records of STUDENT1: \n");
Records of STUDENT1: printf(" Id is: %d \n", ptr->id);
Id is: 1 printf(" Name is: %s \n", ptr->name);
Name is: Raju printf(" Percentage is: %f \n\n", ptr->percentage); 
Percentage is: 90.500000
return 0;
}
Nested-Structure
 Nested structure in C is
struct student_college_detail nothing but structure
within structure. One
{ int college_id; char college_name[50];}; structure can be declared
struct student_detail { int id; char name[20]; inside other structure as
float percentage; // structure within structure it declare structure
members inside a
struct student_college_detail clg_data;}stu_data; structure.
int main() {struct student_detail stu_data = {1,
"Raju", 90.5, 71145, "Anna University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", Figure-8 Nested Structure
stu_data.percentage); Id is: 1
printf(" College Id is: %d \n", Name is: Raju
Percentage is: 90.500000
stu_data.clg_data.college_id);
College Id is: 71145
printf(" College Name is: %s \n",
College Name is: Anna University
stu_data.clg_data.college_name);
UNION
Definition of union
Memory Allocation in union
Difference between union and structure
Accessing the members in union
Examples
Assignment
Union
 Union is a user defined data type.
 Collection of heterogeneous data types
 Allows memory to be shared by different types of data. Only one
members can be accessed at time
Syntax:
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
}; members name;
Difference between union and structure

Structure Union

Union allocates one common


Structure allocates storage space
storage space for all its members.
for all its members separately.
•high storage space

Union occupies lower memory


Structure occupies higher space over structure
memory space.

Access all members of structure at Access only one member of union


a time. at a time.
Structure Union

struct student union student


{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };

only 8 bytes of memory will be


memory allocation will be like allocated since double data type
below. will occupy maximum space of
int mark – 2B memory over other data types. 
char name[6] – 6B
double average – 8B  Total memory allocation = 8
Total memory allocation = Bytes
2+6+8 = 16 Bytes
Memory allocation in union

• Memory required to store a


union variable is the memory
required for the largest element
of an union.
Union name
{
char name[10]; Variable name
float salary; 10 bytes are allocated in
Memory
int workerNo;

} job1; Members of union


Example of union
#include <stdio.h>
union job
{ char name[32];
float salary;
int workerNo;
} job1;
int main()
{
printf("Enter name:\n");
scanf("%s", &job1.name);
printf("Enter salary: and worker no\n");
scanf("%f", &job1.salary);
scanf(“%d’, &workerNo);
printf("Displaying\nName :%s\n", job1.name);
printf("Salary: %.1f", job1.salary);
return 0;}
Example program

#include <stdio.h>
#include <string.h>
union Data
{ int i; float f;
char str[20];
};
int main( )
{ union Data data;  
printf( "Memory size occupied by data : %d\n", sizeof(data)); 

return 0;}
Output: Memory size occupied by data : 20
By using normal variables and pointer variables

using normal variable Using pointer variable

Syntax: Syntax:
union tag_name union tag_name
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };

Declaring union using normal Declaring union using


variable: pointer variable:
union student report; union student *report, rep;

Initializing union using pointer


Initializing union using normal
variable:
variable:
union student rep = {100, “Mani”,
union student report = {100,
99.5};
“Mani”, 99.5};
report = &rep;
Pointer to union
Pointer which stores address of union is called as pointer to union
union test
{
   int x;
   char y;
};

 int main()
{
   union test p1;
   p1.x = 65;
   union test *p2 = &p1; // p2 is a pointer to union p1
    printf("%d %c", p2->x, p2->y);   // Accessing union members using pointer
   return 0;
}

Output:
65 A
What is output of program ?

#include<stdio.h>
int main()
{
union var
{
int a, b;
};
union var v;
v.a=10;
v.b=20;
printf("%d\n", v.a);
return 0;
}
Output:20
What is output of program ?
#include <stdio.h>
union unionJob
{ char name[32];
float salary;
int workerNo;
} uJob;
struct structJob {
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{ printf("size of union = %d", sizeof(uJob));
printf("\nsize of structure = %d", sizeof(sJob));
}
Assignment

 Write a C program to read the details of


students and display the student details by
using union
 Write the C program for passing structure to
the function
typedef in C

• Introduction to typedef in C

• Discuss the usage of typedef in structure and union

• Example Program

• Home work / Assignment


typedef - Definition

• C provides the typedef facility so that a descriptive


identifier can be used as the name of a specific type.

• typedef is a way of renaming any data type

typedef int color;

• This makes color a type that is synonymous with int, and


color can now be used as a type in declarations.

color red, green, blue;


typedef and its use

• The typedef keyword allows the programmer to create a new data type
name for an existing data type.

– The general form of the declaration statement using the


typedef keyword is given as follows.
typedef <existing data type> <new data type ,….>;
– The typedef statement does not occupy storage; it simply
defines a new type.
– typedef statements can be placed anywhere in a C program as
long as they come prior to their first use in the code.
Examples
typedef int aaa, bbb;
typedef int ar[15], arr[9][6];
typedef short SMALLINT;
typedef float weight;
/* now declare some objects */
aaa int1;
bbb int2;

ar yyy; /* array of 15 ints */


arr xxx; /* 9*6 array of int */

SMALLINT i;

weight wt1, wt2;


typedef with char

typedef char c, *cp, carr[100];


c ch; /* a char */
cp pnt; /* pointer to char */
carr chry; /* array of 100 char */

typedef char* itemType;


• It just creates another name for char* itemType
itself is not a variable but a data type. 
itemType str = (char*) malloc(50);
strcpy(str, "Hello World");
typedef vs #define

• #define is a C-directive which is also used to define the


aliases for various data types similar to typedef but with
the following differences −

– typedef is limited to giving symbolic names to types only where


as #define can be used to define alias for values as well, can be
used to define 1 as ONE etc.
#define TRUE 1
#define FALSE 0

– typedef interpretation is performed by the compiler


whereas #define statements are processed by the pre-processor.
#define UINT unsigned int
typedef unsigned int UINT Same thing is
achieved by both
Reuse name declared as typedef

• To re-use a name already declared as a


typedef, its declaration must include at least
one type specifier, which removes any
ambiguity.

typedef int new_thing;


func(new_thing x){
float new_thing;
new_thing = x;
}
typedef in struct
• The typedef feature is particularly convenient when
defining structures.
• In structure the typedef is used to avoid writing the
keyword struct again and again.

struct student
{
int mark [2];
char name [10];
float average;
}
Variable for the above structure can be declared in two ways.
typedef in struct

• 1st way of structure variable declarion

struct student record;


/* for normal variable */
struct student *record;
/* for pointer variable */
typedef in struct

• 2nd way of structure variable declaration

typedef struct student status;

E.g., typedef, lets you


status record; leave out the word “struct”
status *record;
typedef in struct

• Alternative Way For Structure Declaration


using typedef in C
typedef struct student
{
int mark [2];
char name [10];
float average;
} status;
status record;
status *record;
typedef in struct
#include <string.h>
typedef struct student
{
int id;
char name[20];
float percentage;
OUTPUT:
} status; Id is: 1
Name is: Ram
int main() Percentage is: 86.500000
{
status record;
record.id=1;
strcpy(record.name, "Ram");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}
typedef in Union

• To typedef union, the procedure is same as the


structure.
union birthDate
{
int day;
int month;
int year;
};
typedef union birthDate Date;
Date joiningDate;
typedef in Union
typedef union Data {
int i;
float f;
char str[20];
}data;
OUTPUT:
int main( ) { d1.i : 10
data d1; d1.f : 220.500000
d1.str : C Programming
d1.i = 10;
printf( “d1.i : %d\n", d1.i);

d1.f = 220.5;
printf( "d1.f : %f\n", d1.f);

strcpy( d1.str, "C Programming");


printf( "d1.str : %s\n", d1.str);

return 0;
}
typedef in enum

• Consider the following enumeration of color .


enum color{Red,Green,Blue}; 

• You can typedef it to another name.


typedef enum color Color;

• Then the new name of the enum is to be used


to declare variable
Color ball, leaf, sky;
typedef in enum

• typedef may be used to rename any type

– Convenience in naming

– Clarifies purpose of the type

– Cleaner, more readable code

– Portability across platforms


Homework/Assignment

 What is the use of typedef?


 Write a program to read and write students
mark details in a class and find sum and
average of marks. Use Structure and typedef.
 Write a program to read and write Employee
salary details. Use union and typedef.

You might also like