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

Unit-1

The document provides an overview of computer system components, focusing on assemblers, algorithms, flowcharts, and pseudocode. It explains the function and types of assemblers, the characteristics and uses of algorithms, and the importance of flowcharts in programming. Additionally, it discusses pseudocode as a tool for bridging the gap between algorithm design and programming implementation.

Uploaded by

pragati8333
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit-1

The document provides an overview of computer system components, focusing on assemblers, algorithms, flowcharts, and pseudocode. It explains the function and types of assemblers, the characteristics and uses of algorithms, and the importance of flowcharts in programming. Additionally, it discusses pseudocode as a tool for bridging the gap between algorithm design and programming implementation.

Uploaded by

pragati8333
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Unit-1

Introduction to Components of a Computer System

Concept of Assembler

Assembler is a program for converting instructions written in low-level assembly code into
relocatable machine code and generating along information for the loader. It is necessary to
convert user-written programs into machinery code. This is called a translation of a high-
level language to a low-level that is machinery language. This type of translation is
performed with the help of system software. An Assembler can be defined as a program
that translates an assembly language program into a machine language program. Self-
assembler is a program that runs on a computer and produces the machine codes for the
same computer or same machine. It is also known as a resident assembler. A cross-
assembler is an assembler that runs on a computer and produces machine codes for other
computers.

Types of Assembler

The assembler generates instructions by evaluating the mnemonics (symbols) in the


operation field and finding the value of symbols and literals to produce machine code. On
the basis of this functionality, assembler has two types:

 Single-Pass Assembler: If an assembler does all this work in one scan then it is called
a single-pass assembler.
 Multiple-Pass Assembler: If it does it in multiple scans then called a multiple-pass
assembler.

Working of Assembler

Assembler divides tasks into two passes:


Pass-1
 Define symbols and literals and remember them in the symbol table and literal table
respectively.
 Keep track of the location counter.
 Process pseudo-operations.
 Defines a program that assigns the memory addresses to the variables and translates the
source code into machine code.
Pass-2
 Generate object code by converting symbolic op-code into respective numeric op-code.
 Generate data for literals and look for values of symbols.
 Defines a program that reads the source code two times.
 It reads the source code and translates the code into object code.
Idea of Algorithm / Representation of Algorithms

The word Algorithm means ” A set of finite rules or instructions to be followed in


calculations or other problem-solving operations ”
Or
” A procedure for solving a mathematical problem in a finite number of steps that
frequently involves recursive operations”.
Therefore Algorithm refers to a sequence of finite steps to solve a particular problem.

Use of the Algorithms:

Algorithms play a crucial role in various fields and have many applications. Some of the
key areas where algorithms are used include:

1. Computer Science: Algorithms form the basis of computer programming and are used
to solve problems ranging from simple sorting and searching to complex tasks such as
artificial intelligence and machine learning.
2. Mathematics: Algorithms are used to solve mathematical problems, such as finding the
optimal solution to a system of linear equations or finding the shortest path in a graph.
3. Operations Research: Algorithms are used to optimize and make decisions in fields
such as transportation, logistics, and resource allocation.
4. Artificial Intelligence: Algorithms are the foundation of artificial intelligence and
machine learning, and are used to develop intelligent systems that can perform tasks
such as image recognition, natural language processing, and decision-making.
5. Data Science: Algorithms are used to analyze, process, and extract insights from large
amounts of data in fields such as marketing, finance, and healthcare.

What is the need for algorithms?

1. Algorithms are necessary for solving complex problems efficiently and effectively.
2. They help to automate processes and make them more reliable, faster, and easier to
perform.
3. Algorithms also enable computers to perform tasks that would be difficult or impossible
for humans to do manually.
4. They are used in various fields such as mathematics, computer science, engineering,
finance, and many others to optimize processes, analyze data, make predictions, and
provide solutions to problems.
What are the Characteristics of an Algorithm?

As one would not follow any written instructions to cook the recipe, but only the standard
one. Similarly, not all written instructions for programming are an algorithm. For some
instructions to be an algorithm, it must have the following characteristics:

 Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps
should be clear in all aspects and must lead to only one meaning.
 Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined
inputs. It may or may not take input.
 Well-Defined Outputs: The algorithm must clearly define what output will be yielded
and it should be well-defined as well. It should produce at least 1 output.
 Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
 Feasible: The algorithm must be simple, generic, and practical, such that it can be
executed with the available resources. It must not contain some future technology or
anything.
 Language Independent: The Algorithm designed must be language-independent, i.e. it
must be just plain instructions that can be implemented in any language, and yet the
output will be the same, as expected.
 Input: An algorithm has zero or more inputs. Each that contains a fundamental operator
must accept zero or more inputs.
 Output: An algorithm produces at least one output. Every instruction that contains a
fundamental operator must accept zero or more inputs.
 Definiteness: All instructions in an algorithm must be unambiguous, precise, and easy
to interpret. By referring to any of the instructions in an algorithm one can clearly
understand what is to be done. Every fundamental operator in instruction must be
defined without any ambiguity.
 Finiteness: An algorithm must terminate after a finite number of steps in all test cases.
Every instruction which contains a fundamental operator must be terminated within a
finite amount of time. Infinite loops or recursive functions without base conditions do
not possess finiteness.
 Effectiveness: An algorithm must be developed by using very basic, simple, and
feasible operations so that one can trace it out by using just paper and pencil.

Properties of Algorithm:
 It should terminate after a finite time.
 It should produce at least one output.
 It should take zero or more input.
 It should be deterministic means giving the same output for the same input case.
 Every step in the algorithm must be effective i.e. every step should do some work.

Concept of Flowchart

Flowcharts are nothing but the graphical representation of the data or the algorithm for a
better understanding of the code visually. It displays step-by-step solutions to a problem,
algorithm, or process. It is a pictorial way of representing steps that are preferred by most
beginner-level programmers to understand algorithms of computer science, thus it
contributes to troubleshooting the issues in the algorithm. A flowchart is a picture of boxes
that indicates the process flow sequentially. Since a flowchart is a pictorial representation
of a process or algorithm, it’s easy to interpret and understand the process. To draw a
flowchart, certain rules need to be followed which are followed by all professionals to draw
a flowchart and are widely accepted all over the countries.

What is FlowChart?

A flowchart is a type of diagram that represents a workflow or process. A flowchart can


also be defined as a diagrammatic representation of an algorithm, a step-by-step approach
to solving a task.
Flowchart symbols
Different types of boxes are used to make flowcharts flowchart Symbols. All the different
kinds of boxes are connected by arrow lines. Arrow lines are used to display the flow of
control.

Symbol Representation
Symbol Name

Terminal/Terminator

Process
Symbol Representation
Symbol Name

Decision

Document

Data or
Input/Output

Stored Data

Flow Arrow
Comment or
Annotation

Predefined process

On-page
connector/reference

Off-page
connector/reference

Uses of Flowcharts in Computer Programming/Algorithms


The following are the uses of a flowchart:
 It is a pictorial representation of an algorithm that increases the readability of the
program.
 Complex programs can be drawn in a simple way using a flowchart.
 It helps team members get an insight into the process and use this knowledge to collect
data, detect problems, develop software, etc.
 A flowchart is a basic step for designing a new process or adding extra features.
 Communication with other people becomes easy by drawing flowcharts and sharing
them.

When to Use Flowchart?

Flowcharts are mainly used in the below scenarios:


 It is most importantly used when programmers make projects. As a flowchart is a basic
step to make the design of projects pictorially, it is preferred by many.
 When the flowcharts of a process are drawn, the programmer understands the non-
useful parts of the process. So flowcharts are used to separate sound logic from the
unwanted parts.
 Since the rules and procedures of drawing a flowchart are universal, a flowchart serves
as a communication channel to the people who are working on the same project for
better understanding.
 Optimizing a process becomes easier with flowcharts. The efficiency of the code is
improved with the flowchart drawing.
Types of Flowcharts
Three types of flowcharts are listed below:
1. Process flowchart: This type of flowchart shows all the activities that are involved in
making a product. It provides a pathway to analyze the product to be built. A process
flowchart is most commonly used in process engineering to illustrate the relation
between the major as well as minor components present in the product. It is used in
business product modeling to help understand employees about the project requirements
and gain some insight into the project.

2. Data flowchart: As the name suggests, the data flowchart is used to analyze the data,
specifically it helps in analyzing the structural details related to the project. Using this
flowchart, one can easily understand the data inflow and outflow from the system. It is
most commonly used to manage data or to analyze information to and fro from the
system.
3. Business Process Modeling Diagram: Using this flowchart or diagram, one can
analytically represent the business process and help simplify the concepts needed to
understand business activities and the flow of information. This flowchart illustrates the
business process and models graphically which paves the way for process improvement.

Types of boxes used to make a flowchart


There are different types of boxes that are used to make flowcharts. All the different kinds
of boxes are connected to one another by arrow lines. Arrow lines are used to display the
flow of control. Let’s learn about each box in detail.
1. Terminal
This box is of an oval shape which is used to indicate the start or end of the program. Every
flowchart diagram has an oval shape that depicts the start of an algorithm and another oval
shape that depicts the end of an algorithm. For example:

2. Data

This is a parallelogram-shaped box inside which the inputs or outputs are written. This
basically depicts the information that is entering the system or algorithm and the
information that is leaving the system or algorithm. For example: if the user wants to input
a from the user and display it, the flowchart for this would be:
3. Process

This is a rectangular box inside which a programmer writes the main course of action of the
algorithm or the main logic of the program. This is the crux of the flowchart as the main
processing codes is written inside this box. For example: if the programmer wants to add 1
to the input given by the user, he/she would make the following flowchart:

4. Decision

This is a rhombus-shaped box, control statements like if, condition like a > 0, etc are
written inside this box. There are 2 paths from this one which is “yes” and the other one is
“no”. Every decision has either yes or no as an option, similarly, this box has these as
options. For example: if the user wants to add 1 to an even number and subtract 1 if the
number is odd, the flowchart would be:
5. Flow

This arrow line represents the flow of the algorithm or process. It represents the direction of
the process flow. in all the previous examples, we included arrows in every step to display
the flow of the program. arrow increases the readability of the program.
6. On-Page Reference

This circular figure is used to depict that the flowchart is in continuation with the further
steps. This figure comes into use when the space is less and the flowchart is long. Any
numerical symbol is present inside this circle and that same numerical symbol will be
depicted before the continuation to make the user understand the continuation.

Pseudo Code

A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does


not use any programming language in its representation instead it uses the simple English
language text as it is intended for human understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its implementation(code) in a
high-level language.
What is the need for Pseudocode
Pseudocode is an important part of designing an algorithm, it helps the programmer in
planning the solution to the problem as well as the reader in understanding the approach to
the problem. Pseudocode is an intermediate state between algorithm and program that plays
supports the transition of the algorithm into the program.
Pseudocode is an intermediate state between algorithm and program

How to write Pseudocode?

Before writing the pseudocode of any algorithm the following points must be kept in mind.
 Organize the sequence of tasks and write the pseudocode accordingly.
 At first, establishes the main goal or the aim.

Example:

This program will print first N numbers of Fibonacci series.


 Use standard programming structures such as if-else, for, while, and cases the way we
use them in programming. Indent the statements if-else, for, while loops as they are
indented in a program, it helps to comprehend the decision control and execution
mechanism. It also improves readability to a great extent.
Example:
IF “1”
print response
“I AM CASE 1”
IF “2”
print response
“I AM CASE 2”
 Use appropriate naming conventions. The human tendency follows the approach of
following what we see. If a programmer goes through a pseudo code, his approach will
be the same as per that, so the naming must be simple and distinct.
 Reserved commands or keywords must be represented in capital letters.

Example: if you are writing IF…ELSE statements then make sure IF and ELSE be in
Capital letters.
 Check whether all the sections of a pseudo code are complete, finite, and clear to
understand and comprehend. Also, explain everything that is going to happen in the
actual code.
 Don’t write the pseudocode in a programming language. It is necessary that the
pseudocode is simple and easy to understand even for a layman or client, minimizing
the use of technical terms.
WHAT IS PSEUDO-CODE IN C?

The Pseudo-Code In C refers to an informal way of writing a program to improve human


understanding. The purpose of writing a pseudocode is to facilitate easy comprehension of the
program's logic by both programmers and non-programmers.
In other words, it is a false code that even a layman (with some basic programming language)
can understand easily.

To make it easier to understand the complex program, it is written in simple English, using
informative text and annotations.

Pseudocode does not adhere to the syntax of the C programming language and cannot be
directly interpreted or compiled.

Writing a concise, clear, and straightforward pseudocode can greatly aid in the transition from
ideation to the implementation of the program.

Here’s the source code example:

#include <stdio.h>

int main() {
int num = 5;

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


printf("%d\n", num);
}

return 0;
}
For better understanding, You can transform the source code into the following pseudo-
code.

Assign the value 5 to the variable num.


For each value of i from 0 to 4:
Display the value of num.

PSEUDOCODE IN C COMPILER (EXAMPLES)


Example-1:
Here’s the algorithm for a pseudocode in the C compiler that calculates the factorial of the input
number.
Step 1: Start
Step 2: Initialise f= 1
Step 3: Accept input from the user (n)
tep 4: for i=1 to i <= n iterate the process
Step 5: f = f * i
Step 6: i++ [increment i by one]
Step 7: print the value of f
Step 8: Stop
Check out the pseudo-code for the given algorithm
Start program
Declare variables f and n
Accept input for n from the user
Initialize f as 1
For i = 1 to i <= n
Perform f = f * i
Display the value of f
End program
Based on the above algorithm and pseudo-code, here is a C program to calculate the
factorial of the input number.
#include <stdio.h>
void main()
{
int n, f=1,i;
printf("Please enter a number: ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
f=f*i;
}
printf("\n The factorial of %d is %d", n, f);
}
Output:
Please enter a number: 4
The factorial of 4 is 24
The value of f is multiplied by i, and the value of i is incremented by 1. The process iterates until
i<=n. Once this condition is not satisfied, the loop ends and the value of f is displayed at the
output.

Algorithms to Programs

ADDITION OF TWO NUMBERS

To write a C Program for addition of two numbers.

Algorithm:

STEP 1: Start the program.


STEP 2: Read the values of ‘a’&’b’.
STEP 3: Compute the sum of the entered numbers ‘a’,’b’,c=a+b.
STEP 4: Print the value of ‘c’.
STEP 5: Stop the program

Pseudo code:

BEGIN
READ ‘a’&’b’
COMPUTE c=a+b
WRITE ‘c’
END

Flow chart:

Source Code

Source code is a group of instructions a programmer writes using computer programming


languages. Once a programmer writes a line or set of source code, they can later implement it
in a website, application or another type of computer program to give it instructions for
functioning. For example, a coder may write a line of source code that tells a website to
respond in a certain way when a user clicks on a specific part of a webpage, like a button or a
hyperlink.
Programmers typically write source code in a text-based program, like a word processor, and
then use a compiler to translate it into a format that computer programs can read. When
source code undergoes this translation, it then becomes object code. After translation, a
programmer can store source code on a computer for future reference, either in a database or
on its hard drive. Programmers can also print physical copies of their source code. They often
use management systems to track several projects at different stages in development.
Types of source code

The first type of source code is

Compiler source code, whereby a programmer writes the code that a compiler directly
converts into a machine or binary code that a computer can execute. This direct translation
leads to more efficient execution of the code. Every time a programmer wants to modify the
code, they need to rewrite the code with the modifications and run it through the compiler
again so the processor can execute it. C and C++ programming languages use this type of
source code.

The second type is

Interpreter source code, whereby a secondary program, known as an interpreter, analyzes


the code and then uploads it into the machine. Interpreters go through the code line by line to
execute each command. Java, Python and PHP use this type of source code.

Object and Executable Code

Source code to Executable code

1. Instructions written by a programmer in C language is called program. Any program


is stored in a file (for example- rectangle.c) called source file and the code stored in it
is called source code.
2. Source code is in human readable form. For machine (i.e. computer) to understand, it
should be converted into machine readable form called machine code/object code.
This task is done by C compiler which first of all checks for any syntax error and if
there is no syntax error then convert source code into object code and creates new
object code file (for example- rectangle.obj) automatically. This is done by pressing
Alt + F9 key.
3. To execute any object code, it needs to be converted into executable code which is
stored in a separate file (for example- rectangle.exe). This is done by pressing Ctrl+
F9 key. A new executable file will be created automatically which gives output of the
program.
This is shown with the help of Figure 1 below-

Figure 1: Source Code to Executable Code

Object Code

Object code is code that computers and other devices can understand. It is generated from a
program's source code after a procedure known as compilation or translation. Consider it a
modified version of the original code that computers can run instantly.

You utilize source code, a human-readable language, to create computer programs. However,
this source code is not immediately understood by computers. The original code must instead
be transformed into a form that computers can understand and use. A specific program
known as a compiler or translator performs this conversion.

The result of this conversion is the object code. It is formatted so that the Central Processing
Unit (CPU) of the computer's processor can read and understand. The object code comprises
a series of instructions that specify to the CPU what steps or operations to take.
Object code is typically stored in a file known as an object file. Some examples of object file
formats are Common Object File Format (COFF), COM files, and ".exe" files. These files
contain the machine-readable instructions that the computer can execute.

Unlike source code, object code is not easily understandable by humans. It is written in
a binary format, consisting of ones and zeros, which is not readily readable as plain text.
While we can read and understand source code, object code is intended for the computer's
consumption rather than human comprehension.

Source Code?

The "original recipe" for a computer program is its source code. It is a software program
written by programmers in a human-readable language such as Python, Java, or C++.

Consider you want to make a robot. The set of instructions you write to inform the robot what
to do and how to accomplish it is similar to the source code. It is the computer code that
programmers create in a human-understandable programming language by combining words,
numbers, and special commands.
Object Code Source Code

Machine-readable format Human-readable format

Generated from source code after The original version of the program
compilation or translation

Consists of instructions in a format Consists of instructions written in a programming


that computers can directly execute language that humans can understand

Contains binary code (0s and 1s) Written in plain text format using words, numbers, and
special commands

Not easily understandable by Readable and comprehensible by humans


humans

Stored in object files, such Stored in source code files with extensions
as COFF, COM, or .exe files like .py, .java, or .cpp

Result of the transformation The starting point for developing and modifying a
process from source code to program
machine code

Requires an interpreter or linker to Does not require any additional processing to be


convert it into executable code understood

Used for execution and running of Used for understanding, modifying, and maintaining the
the program program

The magic is in the source code. It includes the rules, formulas, and instructions that specify
how the program works. Developers create this code to address certain issues or complete
particular tasks. It's similar to creating a comprehensive blueprint or plan for the robot.

The flexibility of source code allows for customization and modification. Developers can
alter the source code to add new features, correct faults, or improve the performance of a
program, as you can edit and modify the robot's instructions to carry out various jobs.

With the help of a text editor or an Integrated Development Environment (IDE), source
code is normally created in plain text format. It is made up of lines of code that
contain declarations, variables, functions, and other parts that make up the logic of the
program.

Although source code is understandable by humans, computers cannot directly execute it. It
needs to be translated into a machine-readable format called object code which the
computer's processor can execute.

Head-to-head comparison Object code and Source code:

Here's a comparison table explaining the difference between object code and source code in a
more accessible format:

Components of C Language

1. The Character Set Any alphabet, digit or special symbol, used to represent information
is denoted by character.
The character in C are grouped into four categories:
–Letter
–Digits
–Special Symbols
–White Spaces

2. The Data Types


–Character
–Integer
–Floating Point
3. Constants
Two Types
–Primary Constants
• Integer,Real, Character

–Secondary Constants
• Array, Structure, Union, Pointer etc.

4. Variables
–A variable is an entity whose value can change during program execution.
–Variable names are names given to location in memory.
–These memory locations can contain integer, real or character values.

5. Keywords
–Keywords are the words whose meaning has already been explained to the C compiler.
–The keywords cannot be used as variable names because if we do so we are trying to
assign a new meaning to the keyword, which is not allowed by the compiler.

Standard I/O in C

C language has standard libraries that allow input and output in a program.
The stdio.h or standard input output library in C that has methods for input and output.
scanf()
The scanf() method, in C, reads the value from the console as per the type specified and
store it in the given address.
Syntax:
scanf("%X", &variableOfXType);
where %X is the format specifier in C . It is a way to tell the compiler what type of data is
in a variable and & is the address operator in C, which tells the compiler to change the real
value of variableOfXType, stored at this address in the memory.

printf()
The printf() method, in C, prints the value passed as the parameter to it, on the console
screen.
Syntax:
printf("%X", variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is
in a variable and variableOfXType is the variable to be printed.

How to take input and output of basic types in C?

The basic type in C includes types like int, float, char, etc. Inorder to input or output the
specific type, the X in the above syntax is changed with the specific format specifier of that
type. The Syntax for input and output for these are:
 Integer:
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);
 Float:
Input: scanf("%f", &floatVariable);
Output: printf("%f", floatVariable);
 Character:
Input: scanf("%c", &charVariable);
Output: printf("%c", charVariable);

C program to show input and output


#include <stdio.h>

int main()
{

// Declare string variable


// as character array
char str[50];

// --- String ---


// To read a word

// Input the Word


printf("Enter the Word: ");
scanf("%s\n", str);

// Output the Word


printf("\nEntered Word is: %s", str);

// --- String ---


// To read a Sentence

// Input the Sentence


printf("\n\nEnter the Sentence: ");
scanf("%[^\n]s", str);

// Output the String


printf("\nEntered Sentence is: %s", str);

return 0;
}

Output
Enter the Word: GeeksForGeeks
Entered Word is: GeeksForGeeks

Enter the Sentence: Geeks For Geeks


Entered Sentence is: Geeks For Geeks

Data Types in C

A data type specifies the type of data that a variable can store such as
integer, floating, character, etc.

There are the following data types in C language.

Types Data Types


Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types


The basic data types are integer-based and floating-point based. C
language supports both signed and unsigned literals.

The memory size of the basic data types may change according to 32 or
64-bit operating system.

Int:
Integers are entire numbers without any fractional or decimal parts, and
the int data type is used to represent them.

It is frequently applied to variables that include values, such as counts,


indices, or other numerical numbers. The int data type may represent
both positive and negative numbers because it is signed by default.

An int takes up 4 bytes of memory on most devices, allowing it to store


values between around -2 billion and +2 billion.

Char:
Individual characters are represented by the char data type. Typically
used to hold ASCII or UTF-8 encoding scheme characters, such
as letters, numbers, symbols, or commas. There are 256
characters that can be represented by a single char, which takes up one
byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in
single quotes.

Float:
To represent integers, use the floating data type. Floating numbers can
be used to represent fractional units or numbers with decimal places.

The float type is usually used for variables that require very good
precision but may not be very precise. It can store values with an
accuracy of about 6 decimal places and a range of about 3.4 x
1038 in 4 bytes of memory.

Double:
Use two data types to represent two floating integers. When additional
precision is needed, such as in scientific calculations or financial
applications, it provides greater accuracy compared to float.

Double type, which uses 8 bytes of memory and has an accuracy of


about 15 decimal places, yields larger values. C treats floating point
numbers as doubles by default if no explicit type is supplied.

1. int age = 25;


2. char grade = 'A';
3. float temperature = 98.6;
4. double pi = 3.14159265359;

In the example above, we declare four variables: an int variable for the
person's age, a char variable for the student's grade, a float
variable for the temperature reading, and two variables for the number
pi.

Derived Data Type


Beyond the fundamental data types, C also supports derived data
types, including arrays, pointers, structures, and unions. These data
types give programmers the ability to handle heterogeneous data, directly
modify memory, and build complicated data structures.

Array:
An array, a derived data type, lets you store a sequence of fixed-size
elements of the same type. It provides a mechanism for joining multiple
targets of the same data under the same name.

The index is used to access the elements of the array, with a 0 index for
the first entry. The size of the array is fixed at declaration time and cannot
be changed during program execution. The array components are placed
in adjacent memory regions.

Here is an example of declaring and utilizing an array:


1. #include <stdio.h>
2.
3. int main() {
4. int numbers[5]; // Declares an integer array with a size of 5 elements
5.
6. // Assign values to the array elements
7. numbers[0] = 10;
8. numbers[1] = 20;
9. numbers[2] = 30;
10. numbers[3] = 40;
11. numbers[4] = 50;
12.
13. // Display the values stored in the array
14. printf("Values in the array: ");
15. for (int i = 0; i < 5; i++) {
16. printf("%d ", numbers[i]);
17. }
18. printf("\n");
19.
20. return 0;
21. }

Output:

Values in the array: 10 20 30 40 50

Pointer:
A pointer is a derived data type that keeps track of another data type's
memory address. When a pointer is declared, the data type it refers to
is stated first, and then the variable name is preceded by an asterisk
(*).

ADVERTISEMENT

You can have incorrect access and change the value of variable using
pointers by specifying the memory address of the variable. Pointers are
commonly used in tasks such as function pointers, data structures,
and dynamic memory allocation.

Here is an example of declaring and employing a pointer:


1. #include <stdio.h>
2.
3. int main() {
4. int num = 42; // An integer variable
5. int *ptr; // Declares a pointer to an integer
6.
7. ptr = # // Assigns the address of 'num' to the pointer
8.
9. // Accessing the value of 'num' using the pointer
10. printf("Value of num: %d\n", *ptr);
11.
12. return 0;
13. }

Output:

Value of num: 42

Structure:
A structure is a derived data type that enables the creation of composite
data types by allowing the grouping of many data types under a single
name. It gives you the ability to create your own unique data structures
by fusing together variables of various sorts.

1. A structure's members or fields are used to refer to each variable


within it.
2. Any data type, including different structures, can be a member of a
structure.
3. A structure's members can be accessed by using the dot (.)
operator.

A declaration and use of a structure is demonstrated here:

1. #include <stdio.h>
2. #include <string.h>
3. // Define a structure representing a person
4. struct Person {
5. char name[50];
6. int age;
7. float height;
8. };
9.
10. int main() {
11. // Declare a variable of type struct Person
12. struct Person person1;
13.
14. // Assign values to the structure members
15. strcpy(person1.name, "John Doe");
16. person1.age = 30;
17. person1.height = 1.8;
18.
19. // Accessing the structure members
20. printf("Name: %s\n", person1.name);
21. printf("Age: %d\n", person1.age);
22. printf("Height: %.2f\n", person1.height);
23.
24. return 0;
25. }

Output:

Name: John Doe


Age: 30
Height: 1.80

Union:
A derived data type called a union enables you to store various data
types in the same memory address. In contrast to structures, where each
member has a separate memory space, members of a union all share a
single memory space. A value can only be held by one member of a union
at any given moment. When you need to represent many data types
interchangeably, unions come in handy. Like structures, you can access
the members of a union by using the dot (.) operator.

Here is an example of a union being declared and used:

1. #include <stdio.h>
2. // Define a union representing a numeric value
3. union NumericValue {
4. int intValue;
5. float floatValue;
6. char stringValue[20];
7. };
8. int main() {
9. // Declare a variable of type union NumericValue
10. union NumericValue value;
11. // Assign a value to the union
12. value.intValue = 42;
13. // Accessing the union members
14. printf("Integer Value: %d\n", value.intValue);
15. // Assigning a different value to the union
16. value.floatValue = 3.14;
17. // Accessing the union members
18. printf("Float Value: %.2f\n", value.floatValue);
19.
20. return 0;
21. }

Output:

Integer Value: 42
Float Value: 3.14

Thanks………

You might also like