Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C Programming 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

Data Types

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.

A .Primary data types


The primary data types in the C programming language are the basic data types. All the primary
data types are already defined in the system. Primary data types are also called as Built-In data
types. The following are the primary data types in c programming language...

1. Integer data type


2. Floating Point data type
3. Double data type
4. Character data type
Primary Data Types in C
Here are the five primitive or primary data types that one can find in C programming
language:

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

Keywords Data Types


int Integer
char Character
float Float point
double float Double
void Void

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.

Data Type Modifiers


There are basically four types of modifiers for all data types used in C language. We use these
along with all the basic data types for categorising them further.

SHORT AND LONG

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.

SIGNED AND UNSIGNED


This also deals with memory allocation only but in a different way. In case of signed int, it takes into
account both negative and positive numbers. But in unsigned int, we can only represent positive
numbers. Now since the range of values gets decreased in unsigned, thus it is able to represent higher
values in the same memory prospect

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

LONG AND LONG DOUBLE

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.

For example, float takes 4 bytes, that is, 32 bits(4*8)

Therefore the length of number will be: 2^(32)= 4,29,49,67,296.

In case of double, it takes 8 bytes, 64 bits(8*8)

Therefore the length of number will be: 2^(64)= 1,84,46,74,40,73,70,95,51,616.

Data Memory Range Format Specifier


Type (bytes)

short int 2 -32,768 to 32,767 %hd

unsigned 2 0 to 65,535 %hu


short int

unsigned 4 0 to 4,294,967,295 %u
int

int 4 -2,147,483,648 to %d
2,147,483,647

long int 4 -2,147,483,648 to %ld


2,147,483,647

unsigned 4 0 to 4,294,967,295 %lu


long int

long long 8 -(2^63) to (2^63)-1 %lld


int

unsigned 8 0 to %llu
long long 18,446,744,073,709,551,615
int

signed 1 -128 to 127 %c


char

unsigned 1 0 to 255 %c
char

float 4 1.2E-38 to 3.4E+38 %f

double 8 1.7E-308 to 1.7E+308 %lf

long 16 3.4E-4932 to 1.1E+4932 %Lf


double

B. Secondary data types


Secondary data types are formed by combining two or more primary data types in C.
They are mainly of two types:

 USER-DEFINED DATA TYPES


 DERIVED DATA TYPE

1. USER-DEFINED DATA TYPES IN C

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

The C program consists of the following types of UDT:

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;
};

Defining structure in two ways


struct Student
{
char stud_name[30];
int roll_number;
float percentage;
} stud_1 ; // while defining structure
void main(){
struct Student stud_2; // using struct keyword

printf("Enter details of stud_1 : \n");


printf("Name : ");
scanf("%s", stud_1.stud_name);
printf("Roll Number : ");
scanf("%d", &stud_1.roll_number);
printf("Percentage : ");
scanf("%f", &stud_1.percentage);

printf("***** Student 1 Details *****\n);


printf("Name of the Student : %s\n", stud_1.stud_name);
printf("Roll Number of the Student : %i\n", stud_1.roll_number);
printf("Percentage of the Student : %f\n", stud_1.percentage);
}

Accessing Structure member


There are two ways to access the members structure
 Using the help of Dot operator [.]

struct employee
{
char name[100];
int age;
float salary;
char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};

int age = employee_one.age;

 Using Member Structure Pointer Operator or Arrow Operator(->)

struct employee
{
char name[100];
int age;
float salary;
char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};

struct employee *ptr = &employee_one;


int age = ptr->age;

C Program to print the members of a structure using dot and


arrow operators
#include <stdio.h>

struct employee {
char name[100];
int age;
float salary;
char department[50];
};

int main(){
struct employee employee_one, *ptr;

printf("Enter Name, Age, Salary and Department of Employee\n");


scanf("%s %d %f %s", &employee_one.name, &employee_one.age,
&employee_one.salary, &employee_one.department);

/* Printing structure members using dot operator */


printf("Employee Details\n");
printf(" Name : %s\n Age : %d\n Salary = %f\n Dept : %s\n",
employee_one.name, employee_one.age, employee_one.salary,
employee_one.department);

/* Printing structure members using arrow operator */


ptr = &employee_one;
printf("\nEmployee Details\n");
printf(" Name : %s\n Age : %d\n Salary = %f\n Dept : %s\n",
ptr->name, ptr->age, ptr->salary, ptr->department);

return 0;
}

Array of Structure in C Programming


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.

Declaration of Structure Array in C


struct Employee {
char name[50];
int age;
float salary;
}employees[1000];

Accessing Structure Fields in Array

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.

There are two ways to define nested structure in C language.


a. Declaring a Structure Variable as Member of Another
Structure

b. Declaring a 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;

The normal data members of a structure is accessed by a


single dot(.)operator but to access the member of inner
structure we have to use dot operator twice.

Outer_Structure_variable.Inner_Structure_variable.Member
employee.address.zipCode

C Program to Show Nesting of Structure

#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("Enter Name, Age, Salary of Employee\n");


scanf("%s %d %f", &employee_one.name, &employee_one.age,
&employee_one.salary);

printf("Enter House Number and Street of Employee\n");


scanf("%d %s", &employee_one.location.houseNumber,
&employee_one.location.street);

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;
}

Passing Structure to Function


You can pass a structure variable to a function as argument
like we pass any other variable to a function.
Passing Structure Members to Functions
When you pass a member of a structure to a function, you are passing the value of that member to the
function
structures can be passed as arguments to functions just like any other data type. When a structure
is passed as an argument to a function, a copy of the structure is created and passed to the
function. This means that any changes made to the structure within the function will not be
reflected in the original structure outside of the function.
#include <stdio.h>
struct Student {
int roll_no;
char name[50];
};
void print_student(struct Student s) {
printf("Roll Number: %d\n", s.roll_no);
printf("Name: %s\n", s.name);
}
int main() {
struct Student s = {1, "John Doe"};
print_student(s);
return 0;
}
If you wish to pass the address of an individual structure member, put the & operator before the
structure name
#include<stdio.h>
/* Define a structure type. */
struct struct_type {
int p;
char q;
} ;

void f1(int *item);


int main(void)
{
struct struct_type record1;
record1.p = 10;
f1(&record1.p); /* passes address of character p */
return 0;
}
void f1(int *item)
{
printf("%d \n",*item);}
Assign structure to a function by value
#include<stdio.h>
#include<conion.h>

struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student stu1);

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;
};

void func(struct student *stu1);

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 Entire Structures to Functions
When a structure is used as an argument to a function, the entire structure is passed using the normal
call-by-value method. Of course, this means that any changes made to the contents of the parameter
inside the function do not affect the structure passed as the argument.
#include<stdio.h>
/* Define a structure type. */
struct struct_type {
int a, b;
char ch;
} ;
void f1(struct struct_type record1);

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

A union is declared using the union keyword 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;

} stud_1 ; // while defining union


void main(){
union Student stud_2; // using union keyword

printf("Enter details of stud_1 : \n");


printf("Name : ");
scanf("%s", stud_1.stud_name);
printf("Roll Number : ");
scanf("%d", &stud_1.roll_number);
printf("Percentage : ");
scanf("%f", &stud_1.percentage);

printf("***** Student 1 Details *****\n);


printf("Name of the Student : %s\n", stud_1.stud_name);
printf("Roll Number of the Student : %i\n", stud_1.roll_number);
printf("Percentage of the Student : %f\n", stud_1.percentage);
}

Accessing a Union Members

There are two ways to access the members structure

 Using the help of Dot operator [.]

Union employee
{
char name[100];
int age;
float salary;
char department[50];
} employee_one = {"Jack", 30, 1234.5, "Sales"};

int age = employee_one.age;

 Using Member Structure Pointer Operator or Arrow Operator[-->]


Union employee
{
char name[100];
int age;
float salary;
char department[50];
}
employee_one = {"Jack", 30, 1234.5, "Sales"};

Union employee *ptr = &employee_one;


int age = ptr->age;

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;

// assigning values to record1 union variable


strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;

printf("Union record1 values example\n");


printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);

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.

 In a structure, we can access individual members simultaneously while in a union, we can


only access one member at a time.

 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:

 Reduces memory consumption.


 To make our program more efficient and flexible.
 Easy to Implement.

Bit Field Declaration


The declaration of a bit-field has the following form inside a structure −
struct {
type [member_name] : width ;
};
The variables defined with a predefined width are called bit fields. A bit field can hold more
than a single bit; for example, if you need a variable to store a value from 0 to 7, then you can
define a bit field with a width of 3 bits as follows −
struct {
unsigned int age : 3;
} Age;
The above structure definition instructs the C compiler that the age variable is going to use only
3 bits to store the value. If you try to use more than 3 bits, then it will not allow you to do so
 Note: If we give the width to a data member more than its actual range, then it
will give the compilation error.
 We cannot use the bit field concept in the array.
 We cannot get the address of the data member if we use bit fields

Typedef

typedef is a keyword used in C language to assign alternative[symbolic name] names to


existing datatypes. Its mostly used with user defined datatypes, when names of the datatypes
become slightly complicated to use in programs. Following is the general syntax for
using 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.

The general syntax of typedef is as follows...

typedef <existing-datatype> <alias-name>

Typedef with primitive datatypes


#include<stdio.h>
#include<conio.h>

typedef int Number;


void main(){
Number a,b,c; // Here a,b,&c are integer type of variables.
clrscr() ;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &a,&b) ;
c = a + b;
printf("Sum = %d", c) ;
}

Typedef with Arrays


#include<stdio.h>
#include<conio.h>
void main(){

typedef int Array[5]; // Here Array acts like an integer array type of size 5.

Array list = {10,20,30,40,50}; // List is an array of integer type with size 5.


int i;
clrscr() ;
printf("List elements are : \n") ;
for(i=0; i<5; i++)
printf("%d\t", list[i]) ;
}

Typedef with user defined datatypes


Structure
include<stdio.h>
#include<conio.h>

typedef struct student


{
char stud_name[50];
int stud_rollNo;
}stud;

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(){

typedef int* intPointer;

intPointer ptr; // Here ptr is a pointer of integer datatype.


int a = 10;

clrscr() ;

ptr = &a;

printf("Address of a = %u ",ptr) ;
printf("\nValue of a = %d ",*ptr);
}

Enumerated Types (enum)


Enumeration is the process of creating user defined datatype by assigning names to integral
constants

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.

syntax of enum declaration in c.


enum enum_name{int_const1, int_const2, int_const3, …. int_constN};

simple program of an enum


#include <stdio.h>

enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};


int main()
{
enum weekdays w; // variable declaration of weekdays type
w=Monday; // assigning value of Monday to w.

printf("The value of w is %d",w);

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++….

2. DERIVED DATA TYPE IN C


The derived data types are basically derived out of the fundamental data types. A derived data type won’t
typically create a new data type – but would add various new functionalities to the existing ones instead.

Given below are the various derived data types used 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

Arrays in C are classified into two types:

 One-dimensional arrays
 Multi-dimensional arrays
1. Two dimensional
2. Three dimensional

Array Initialization
1. General syntax to create an array...

<Datatype> <arrayName> [ size ] ;


2. Syntax for creating an array with size and initial values
<data_type> <arr_name> [arr_size]={value1, value2, value3,…};
3. Syntax for creating an array without size and with initial values

datatype arrayName [ ] = {value1, value2, ...} ;


4. Universal Initialization

Datatype arrayName[ ] {1,2,3}

Accessing Individual Elements of an Array


general syntax to access individual elements of an array..

arrayName [ indexValue ] ;

Single Dimensional Array

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.

Initialization of One-Dimensional Array in C

One-Dimensional arrays in C are initialized either at Compile Time or Run Time.

Compile-Time Initialization
Compile-Time initialization is also known as static-initialization. In this, array elements are
initialized when we declare the array implicitly

int numbers[5] = {1, 2, 3, 4, 5};

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 ARRAY IN C:


Two dimensional array is nothing but array of array.

Two Dimensional Arrays can be thought of as an array of arrays or as a matrix consisting of rows and columns

Array declaration syntax:


data_type arr_name [num_of_rows][num_of_column];

Array initialization syntax:


data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};

Array accessing syntax:


arr_name[index];

THREE DIMENSIONAL ARRAY IN C:


A 3d array contains three dimensions, so it can be thought of as an array of 2d arrays. The three dimensions are
stated as follows:

 Block Size (k)


 Row (i)
 Column (j)

Array declaration syntax:


data_type array_name[i][j][k]

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.

Syntax to declare a pointer array

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];

// Initialize the first Person in the array


strcpy(people[0].name, "John");
people[0].age = 30;

// Access the first Person's name and age


printf("Name: %s\n", people[0].name);
printf("Age: %d\n", people[0].age);
return 0;
}

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:

char *array_of_strings[] = { "hello", "world", "how", "are", "you" };

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]);

for (int i = 0; i < size; i++) {


printf("%s\n", array_of_strings[i]);
}
return 0;
}
You can access individual strings in the array using the index operator []. For example

char *string = array_of_strings[2];


In this example, string points to the third string in the array_of_strings,

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.

to declare an array of characters in C:

char character_array[] = { 'h', 'e', 'l', 'l', 'o', '\0' };

Passing array to a function

You might also like