C Programming 2
C Programming 2
C Programming 2
Data type is an attribute of data which tells the compiler, which type of data a variable is
holding. It can be of type integer, float( decimal), character , Boolean( true/false ) etc. Formally
we use data types to specify the type of data our variables are holding.
1. Integer – We use these for storing various whole numbers, such as 5, 8, 67, 2390, etc.
2. Character – It refers to all ASCII character sets as well as the single alphabets, such as ‘x’,
‘Y’, etc.
3. Double – These include all large types of numeric values that do not come under either
floating-point data type or integer data type. Visit Double Data Type in C to know more.
4. Floating-point – These refer to all the real number values or decimal points, such as 40.1,
820.673, 5.9, etc.
5. Void – This term refers to no values at all. We mostly use this data type when defining the
functions in a program.
Various keywords are used in a program for specifying the data types mentioned above. Here
are the keywords that we use
The size of every data type gets defined in bytes/ bits. Also, these data types are capable of
holding a very wide range of values.
These are used to define the amount of memory space that the compiler will allocate. In case of short
int, it is typically 2 bytes and in long int, it is 4 bytes.
A "signed" integer can represent both positive and negative numbers, as well as zero. The sign of a
signed integer is determined by its most significant bit, with 0 representing positive numbers and 1
representing negative numbers (using two's complement representation).
An "unsigned" integer can only represent non-negative numbers (including zero), as it doesn't have a
sign bit. This means that an unsigned integer has a larger range of non-negative values than a signed
integer of the same size.
For presenting the unsigned (only +) and signed (- and +) values in any given data type
These are mostly used with decimal numbers. By using these prefixes, we can increase the range of
values represented in float. Float is of 4 bytes, double is of 8 bytes and long double is of 10 bytes.
By using the relation mentioned above(int data type), we can calculate the length of the number in
float and decimal.
unsigned 4 0 to 4,294,967,295 %u
int
int 4 -2,147,483,648 to %d
2,147,483,647
unsigned 8 0 to %llu
long long 18,446,744,073,709,551,615
int
unsigned 1 0 to 255 %c
char
These data types are defined by the user as per their convenience. If a user feels a need of having a
data type which is not predefined in C library, then they make their own
It is a typical data type that we can derive out of any existing data type in a program. We can
utilise them for extending those built-in types that are already available in a program, and then
you can create various customized data types of your own
Structure
Structure in C is a user-defined data type that allow you to group variable of different data types
under a single name
It enables you to store multiple pieces of related information together and treat them as a single
entity.
Each member of a structure is stored in different memory location and the memory locations for
each member is allocated separately This means that the size of a structure is the sum of size of
its members
In structures each member has its own sperate memory location so you can access all of the
members of structure at the same time
Defining structure
A structure is defined using the struct keyword
Syntax:----
Creating structure in c
struct structure_name
{
data_type variable_name
1;
data_type variable_name
2;
.
.
data_type variable_name
N;
};
struct employee
{
char name[100];
int age;
float salary;
char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};
struct employee
{
char name[100];
int age;
float salary;
char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};
struct employee {
char name[100];
int age;
float salary;
char department[50];
};
int main(){
struct employee employee_one, *ptr;
return 0;
}
array_name[index].member_name
For Example
employees[5].age
Nesting of Structures
Nesting of structures is supported in C programming language.
We can declare a structure variable as member of structure or
write one Structure inside another structure.
A. B.
struct Address struct Employee
{ {
int houseNumber; char name[100];
char street[100]; int age;
char zipCode; float salary;
}; struct Address
{
struct Employee int houseNumber;
{ char street[100];
char name[100]; char zipCode;
int age; } address;
float salary; } employee;
struct Address address;
} employee;
Outer_Structure_variable.Inner_Structure_variable.Member
employee.address.zipCode
#include <stdio.h>
strict employee {
char name[100];
int age;
float salary;
struct address {
int houseNumber;
char street[100];
}location;
};
int main(){
struct employee employee_one, *ptr;
printf("Employee Details\n");
printf(" Name : %s\n Age : %d\n Salary = %f\n House Number :
%d\n Street : %s\n",
employee_one.name, employee_one.age, employee_one.salary,
employee_one.location.houseNumber,
employee_one.location.street);
return 0;
}
struct student
{
int id;
char name[20];
float percentage;
};
int main()
{
struct student stu1;
stu1.id=21;
strcpy(stu1.name, "Rambo");
stu1.percentage = 96.5;
func(stu1);
return 0;
}
void func(struct student stu1)
{
printf(" Id is: %d \n", stu1.id);
printf(" Name is: %s \n", stu1.name);
printf(" Percentage is: %f \n", stu1.percentage);
}
Passing structure to a function by address(reference)
In this program, the whole structure is passed to another function by address. It means only the
address of the structure is passed to another function. The whole structure is not passed to another
function with all members and their values. So, this structure can be accessed from called function by
its address.
struct student
{
int id;
char name[20];
float percentage;
};
int main()
{
struct student stu1;
stu1.id=21;
strcpy(stu1.name, "Rambo");
stu1.percentage = 96.5;
func(&stu1);
return 0;
}
int main(void)
{
struct struct_type record1;
record1.a = 1070;
f1(record1);
return 0;
}
void f1(struct struct_type parameter)
{
printf("%d \n", parameter.a);
}
Declare structure variable as global
When a structure variable is declared as global, then it is visible to all the functions in a program. In
this scenario, we don't need to pass the structure to any function separately.
struct student
{
int id;
char name[20];
float percentage;
};
struct student stu1; // Global declaration of structure
void structurefunction();
int main()
{
stu1.id=21;
strcpy(stu1.name, "Rambo");
stu1.percentage = 96.5;
structurefunction();
return 0;
}
void structurefunction()
{
printf(" Id is: %d \n", stu1.id);
printf(" Name is: %s \n", stu1.name);
printf(" Percentage is: %f \n",
stu1.percentage);
}
Union
A union is a user defined data type that allow you to store Variable of different data type in a
same memory location it is similar to structures but all the members of union share same memory
location
It often to save memory by reusing the same memory location for different data type variable at
different time
The memory occupied by a union variable is equal to the storage space needed by the largest data
member of the union.
You can access the most recent stored value in the union because the other value have been over
written We can access only one member of union at a time. We can’t access all member values at
the same time in union
Declaring a Union in C
Syntax----creating union in c
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Creating and Using union
union Student
{
char stud_name[30];
int roll_number;
float percentage;
Union employee
{
char name[100];
int age;
float salary;
char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};
c program
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
return 0;
}
Difference Between Structure and Union in C
In union, we can only initialize the first data member whereas in a structure, we can
initialize many data members at once.
Compiler allocates memory for each member of a structure while for a union, it allocates
memory equal to the size of the largest data member.
Union members share a memory location while structure members have a unique
storage location each.
If we change the value of a member in a structure, it won't affect its other members but
in a union, changing the value of one member will affect the others.
Bit fields
A bit field is a data structure that allows the programmer to allocate memory to structures and
unions in bits in order to utilize computer memory in an efficient manner .The idea of bit-field is
to use memory efficiently when we know that the value of a field or group of fields will never
exceed a limit or is within a small range. Bit fields are used when the storage of our program is
limited. Need of bit fields in C programming language:
Typedef
Using typedef keyword we can create a temporary name to the system defined datatypes like
int, float, char and double. we use that temporary name to create a variable.
typedef int Array[5]; // Here Array acts like an integer array type of size 5.
void main(){
stud s1;
clrscr() ;
printf("Enter the student name: ") ;
scanf("%s", s1.stud_name);
printf("Enter the student Roll Number: ");
scanf("%d", &s1.stud_rollNo);
printf("\nStudent Information\n");
printf("Name - %s\nHallticket Number - %d", s1.stud_name,s1.stud_rollNo);
}
Pointer
#include<stdio.h>
#include<conio.h>
void main(){
clrscr() ;
ptr = &a;
printf("Address of a = %u ",ptr) ;
printf("\nValue of a = %d ",*ptr);
}
The enum in C is also known as the enumerated type. Enum in C is a user-defined data type that
consists of integer values, and it provides meaningful names to these values. The use of an
enum in C makes the program easy to understand and maintain. The enum is defined by using
the enum keyword.
return 0;
}
Note - In enumeration, more than one name may given with same integral constant.
The compiler will automatically give default values beginning at 0 to the enum names if
we do not supply any values for them.
The values can be given to the enum names in any sequence, and the unassigned names
will receive the preceding value plus one by default.
Enum name values must be integral constants; they cannot be of other kinds, such as
string, float, etc.
If we define two enums with the same scope, then these two enums should have
separate enum names else the compiler will produce an error. All enum names must be
unique in their scope.
Classes
This is an also a user defined data type We should discuss it later in c++….
1. Arrays
2. Pointers
3. Functions
4. Reference
Arrays
Arrays is collection of values or elements of similar data type under a single
variable, instead of declaring separate variables for each value.
Types of Arrays
One-dimensional arrays
Multi-dimensional arrays
1. Two dimensional
2. Three dimensional
Array Initialization
1. General syntax to create an array...
arrayName [ indexValue ] ;
Single dimensional array or 1-D array is one of the most used types of the array in C. It is a linear
collection of similar types of data, and the allocated memory for all data blocks in the single-
dimensional array remains consecutive.
Compile-Time Initialization
Compile-Time initialization is also known as static-initialization. In this, array elements are
initialized when we declare the array implicitly
Run-Time Initialization
Runtime initialization is also known as dynamic-initialization. Array elements are initialized at the
runtime after successfully compiling the program
This is done by reading values from the user or from a file during the program execution:
int numbers[5];
for (int i = 0; i < 5; i++) {
printf("Enter a number: ");
scanf("%d", &numbers[i]);
}
Two Dimensional Arrays can be thought of as an array of arrays or as a matrix consisting of rows and columns
Indexing
indexing refers to accessing elements of an array or string by specifying their position in the data
structure.
The elements of an array can be accessed by their index, which is an integer that represents their
position in the array
The first element of the array arr is arr[0], the second is arr[1], and so on.
Indexing can be useful when you want to access a specific element in an array or string, or when you
want to iterate over the elements of the data structure.
Note:- the count of elements within the {} the must be less than the size of the array if we do this
remaining position considered to be ‘0’
Array of a Pointer
Array of pointers are used to store multiple address values and are very useful in case of storing various
string values.
An array of pointers is similar to any other array in C Language. It is an array which contains numerous
pointer variables and these pointer variables can store address values of some other variables having
the same data type.
data_type (*array_name)[sizeof_array];
We are using * operator to define that the ptr array is an array of pointers.
C Program
#include <stdio.h>
int main()
{
char *fruits[5] = {"apple", "banana", "mango", "grapes", "orange"}, i;
for(i = 0; i < 5; i++)
{
printf("%s\n", fruits[i]);
}
return 0;
}
Array of Structure
An array of structres in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities. The array of structures in C are used
to store information about multiple entities of different data types. The array of structures is also
known as the collection of structures.
#include <stdio.h>
struct Person {
char name[20];
int age;
};
int main() {
struct Person people[10];
Array of String
An array of strings is an array of arrays of characters, where each inner array represents a string.
Each inner array of characters is terminated by a null character '\0' to indicate the end of the
string. The syntax to declare an array of strings is as follows:
Code:
#include <stdio.h>
int main() {
char *array_of_strings[] = { "hello", "world", "how", "are", "you" };
int size = sizeof(array_of_strings) / sizeof(array_of_strings[0]);
Array of character
An array of characters in C is a data structure that stores a sequence of characters in contiguous
memory. In C, a character array is often used to represent a string.