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

Programming For Problem Solving Using C and C++

The document provides information on the basic organization of digital computers. It discusses the main components of a computer including the input unit, storage unit, output unit, arithmetic logical unit, control unit, and central processing unit. It also describes the different types of computer memory including primary storage, secondary storage, RAM, ROM, and flash memory. Finally, it summarizes the five generations of computers from the first generation which used vacuum tubes to the current fifth generation utilizing microprocessors and semiconductor memories.

Uploaded by

mallikarjuna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Programming For Problem Solving Using C and C++

The document provides information on the basic organization of digital computers. It discusses the main components of a computer including the input unit, storage unit, output unit, arithmetic logical unit, control unit, and central processing unit. It also describes the different types of computer memory including primary storage, secondary storage, RAM, ROM, and flash memory. Finally, it summarizes the five generations of computers from the first generation which used vacuum tubes to the current fifth generation utilizing microprocessors and semiconductor memories.

Uploaded by

mallikarjuna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

PROGRAMMING FOR PROBLEM SOLVING USING C and C++

1Q. Explain about Basic Organization of digital computer.

Ans. A computer can process data, pictures, sound and graphics. They can solve highly
complicated problems quickly and accurately.
Input Unit:
Computers need to receive data and instruction in order to solve any problem. Therefore
we need to input the data and instructions into the computers. The input unit consists of
one or more input devices. Keyboard is the one of the most commonly used input device.
Other commonly used input devices are the mouse, floppy disk drive, magnetic tape, etc.
All the input devices perform the following functions.
· Accept the data and instructions from the outside world.
· Convert it to a form that the computer can understand.
· Supply the converted data to the computer system for further processing.

Storage Unit:
Block Diagram of Computer

The storage unit of the computer holds data and instructions that are entered through the
input unit, before they are processed. It preserves the intermediate and final results before
these are sent to the output devices. It also saves the data for the later use.

Types of Storage Devices:

1. Primary Storage:

1. Stores and provides very fast.


2. This memory is generally used to hold the program being currently executed in the
computer, the data being received from the input unit, the intermediate and final results of
the program.
3. The primary memory is temporary in nature. The data is lost, when the computer is
switched off.
4. In order to store the data permanently, the data has to be transferred to the secondary
memory.
The cost of the primary storage is more compared to the secondary storage.

2. Secondary Storage:

1. It stores several programs, documents, data bases etc.


2. The programs that run on the computer are first transferred to the primary memory
before it is actually run.
3. Whenever the results are saved, again they get stored in the secondary memory.
4. The secondary memory is slower and cheaper than the primary memory. Some of the
commonly used secondary memory devices are Hard disk, CD, etc.,

Memory Size:

All digital computers use the binary system, i.e. 0 s and 1 s. Each character or a number is
represented by an 8 bit code. The set of 8 bits is called a byte. A Character occupies 1 byte
space.
A numeric occupies 2 byte space. Byte is the space occupied in the memory. The size of the
primary storage is specified in KB (Kilobytes) or MB (Megabyte). One KB is equal to 1024
bytes and one MB is equal to 1000KB. The size of the primary storage in a typical PC usually
starts at 16MB. PCs having 32 MB, 48MB, 128 MB, 256MB memory are quite common.

Output Unit:

The output unit of a computer provides the information and results of a computation to
outside world. Printers, Visual Display Unit (VDU) are the commonly used output devices.
Other commonly used output devices are floppy disk drive, hard disk drive, and magnetic
tape drive.

Arithmetic Logical Unit:


All calculations are performed in the Arithmetic Logic Unit (ALU) of the computer. It also
does comparison and takes decision. The ALU can perform basic operations such as
addition, subtraction, multiplication, division, etc and does logic operations viz, >, <, =, „etc.
Whenever calculations are required, the control unit transfers the data from storage unit to
ALU once the computations are done, the results are transferred to the storage unit by the
control unit and then it is send to the output unit for displaying results.

Control Unit:
It controls all other units in the computer. The control unit instructs the input unit, where
to store the data after receiving it from the user. It controls the flow of data and
instructions from the storage unit to ALU. It also controls the flow of results from the ALU
to the storage unit. The control unit is generally referred as the central nervous system of
the computer that control and synchronizes it's working.

Central Processing Unit:

The control unit and ALU of the computer are together known as the Central Processing
Unit (CPU). The CPU is like brain performs the following functions:
• It performs all calculations.
• It takes all decisions.
• It controls all units of the computer.
A PC may have CPU-IC such as Intel 8088, 80286, 80386, 80486, Celeron, Pentium, Pentium
Pro, Pentium II, Pentium III, Pentium IV, Dual Core, and AMD etc.

2Q. Explain the various types of Memory in Computer System?

Ans. The Role of Memory


The term "memory" applies to any electronic component capable of temporarily storing
data.
There are two main categories of memories:
Internal memory that temporarily memorizes data while programs are running. Internal
memory uses micro conductors, i.e. fast specialized electronic circuits. Internal memory
corresponds to what we call random access memory (RAM).
Auxiliary memory (also called physical memory or external memory) that stores
information over the long term, including after the computer is turned off. Auxiliary
memory corresponds to magnetic storage devices such as the hard drive, optical storage
devices such as CD-ROMs and DVD-ROMs, as well as read-only memories.

Technical Characteristics

(a) Capacity, representing the global volume of information (in bits) that the memory can
store

(b) Access time, corresponding to the time interval between the read/write request and
the availability of the data

(c) Cycle time, representing the minimum time interval between two successive accesses

(d) Throughput, which defines the volume of information exchanged per unit of time,
expressed in bits per second
(e) Non-volatility, which characterizes the ability of a memory to store data when it is not
being supplied with electricity
The ideal memory has a large capacity with restricted access time and cycle time, a high
throughput and is non-volatile.
However, fast memories are also the most expensive. This is why memories that use
different technologies are used in a computer, interfaced with each other and organised
hierarchically.
The fastest memories are located in small numbers close to the processor. Auxiliary
memories, which are not as fast, are used to store information permanently.
Types of Memories

Random Access Memory

Random access memory, generally called RAM is the system's main memory, i.e. it is a
space that allows you to temporarily store data when a program is running.
Unlike data storage on an auxiliary memory such as a hard drive, RAM is volatile, meaning
that it only stores data as long as it supplied with electricity. Thus, each time the computer
is turned off, all the data in the memory are irremediably erased.

Read-Only Memory
Read-only memory, called ROM, is a type of memory that allows you to keep the
information contained on it even when the memory is no longer receiving electricity.
Basically, this type of memory only has read-only access. However, it is possible to save
information in some types of ROM memory.

Flash Memory
Flash memory is a compromise between RAM-type memories and ROM memories. Flash
memory possesses the non-volatility of ROM memories while providing both read and
writes access However, the access times of flash memories are longer than the access times
of RAM.

3Q. Describe all the Generations of Computer

Ans. Generation of Computers


Each phase of computer development is known as a separate generation of computers. The
computer can be classified into four generations according to their type of electronic
circuits such as vacuum tube, transistor, IC etc.

(a) The First Generation Computers (1949-55)

Main Features:
1) The computers of this generation used vacuum tubes.
2) These computers used machine language for giving instructions.
3) They used the concept of stored program.
4) These computers were 5000 times faster than the MARK-I.
5) The first generation computers were welcomed by Government and Universities.

Limitations:
1) These computers were very big in size. The ENIAC machine was 30 x 50 feet in size and
30 tons in weight. So, these machines required very large space for their workings.
2) Their power consumption was very high.
3) These computers had slow operating speed and small computing capacity.
4) These computers had a very small memory.

(b) The Second Generation Computers (1956-65)

Main Features:
1) The computers of this generation replaced vacuum tubes with transistors.
2) Magnetic cores were invented for storage.
3) Different magnetic storage devices were developed in this generation.
4) Commercial applications were developed during this period. Eighty percent of these
computers were used in business and industries.

(c) Third Generation Computers (1966-75)

Main Features:
· The third generation computers replaced transistors with Integrated Circuits . These
Integrated Circuits are also known as chips.
· The size of main memory was increased and reached about 4 megabytes.
· Magnetic disk technology had been improved and drive having capacity upto 100
MBPS came into existence.
· The CPU becomes more powerful with the capacity of carrying out 1 million instructions
per second.
· This generation computers were relatively inexpensive and faster.
· The application area also increased in this generation. The computers were used in other
areas like education, small businesses survey, analysis along with their previous usage
areas.

(d) The Fourth Generation Computers (1976-Present)

Main Features:
i . The fourth generation computers replaced small scale integrated circuits and medium
scale integrated circuits with the microprocessors chip.
ii. Semiconductor memories replaced magnetic core memories.
iii. The hard-disks are available of the sizes upto 200 GB. The RAID technology
(Redundant Array of Inexpensive Disks) gives storage upto thousands of GB. iv. Computer
cost came down rapidly in this generation.
v. Application of computers is increased in various areas like visualization, parallel
computing, multimedia etc.

(e) The Fifth Generation Computers


Mankind along with the advancement in science and technology is working hard to bring
the V Generation of computer. These computers will have the capability of thinking on their
own like an man with the help of Artificial Intelligence (AI). the 21st century will be better,
faster, smaller and smarter computers.

4Q. Explain Data types in C language ?

Ans. DATA TYPES

All C compilers support a variety of data base . This enables the programmer to
select the appropriate data type as per data need of application.

Data types can be classified as given below:

a. Primary data type (Fundamental data type)(integer ,float ,character)

b. User defined data type (typedef , enum)

c. Derive data type (arrays , functions ,structures ,unions ,pointers)

d. Empty data type (void)

a. primary (or) Fundamental data type:-

There are three types of fundamental data types, they are :-

1. integer data type

2. floating point data type

3. Character data type


1. Integer data type :-

They are used to represent whole numbers which are having sequence of digits .

Integer data type can be classified as signed and unsigned integers.

Signed data types

* Signed Integer:- This data type is used to represent both positive and negative integer

numbers.

Keyword: signed int (or) int

Size : signed integer occupies 16 bits of memory.

Size : 16 bits (or) 2 bytes.

Range : -32768 to +32767

Format specifier (control string) : %d

* signed short int :- the data type is used to represent the values which are less than
signed integer.

Keyword : signed short int.

Size : 8 bits (or) 16 bytes depending on computer.

Range : If 8 bits -128 to +127


If 16 bits -32768 to +32767

Format specifier : %d

* signed long integer :- the data type is used to represent the longer values than integer.

Keyword : signed long int (or) long int (or) long

Size : 32 bits (or) 4 bytes.

Range : -2,147,483,648 to 2,147,483,647

Format specifier : % Id

Unsigned data types

* Unsigned datatypes:- This data type is used to represent unsigned integer values.

Eg:- Height , weight,volume,Age

* Unsigned integer :-

Keyword : unsigned integer.

Size : 16 bits (or) 2 bytes.

Range : 0 to 65535

Format specifier : %u

unsigned short int :- the data type is used to represent the values of small range without
sign.

Keyword : unsigned short int.

Size : 8 bits (or) 16 bytes depending on computer.

Range : 0 to 255 (or) to 65535

Format specifier : %u

* signed long integer :- It is used to represent the longer values than which are not having
any sign.

Keyword : unsigned long int (or) unsigned long

Size : 32 bits (or) 4 bytes.

Range : 0 to 4294967295
Format specifier : %u

2. Floating point data type

These data types are used to represent floating point values or real numbers.

There are 3 types :

* float :- this is used to represent floating point values

Keyword : float.

Size : This data type occupies 32 bits of memory or 4 bytes

Range : 1.2E-38 to 3.4E+38

Format specifier : %f

*double :- this is used to represent point values of more range than float data type.

Keyword : double.

Size : 64 bits (or) 8 bytes

Range : 2.3E-308 to 1.7E+308

Format specifier : %f

* long double :- the range of long double is more than the double.

Keyword : long double.

Size : 80 bits (or) 10 bytes.

Range : 3.4E-4932 to 3.4E+4932

Format specifier : % Lf

3.Character data type

This data type is used to represent single character.

*Signed Chartacter :- It is used to represent characters of both

Keyword : Signed char (or) char

Size : 8 bits (or) 1 bytes.

Range : -128 to +127

Format specifier : %c
* Unsigned Chartacter :- It is used to represent characters with unsigned numbers .
keyword : Unsigned char (or) char

Size : 8 bits (or) 1 bytes.

Range : 0 to 255

Format specifier : %c

Quick Reference of Data Types

Data Types Size(in Bytes) Range Control String


Char 1 -128 to 127 %c
Unsigned char 1 0 to 255 %c
Int 2 -32,768 to 32,767 % d or %i
Unsigned char 2 0 to 655655 %u
Long 4 -2147483648 to % Id
2147483647
Unsigned Long 4 0 to 4294967295 % Iu
Float 4 3.4e-38 to 3.4e3.08 %f or %g
Double 8 1.7e-308 to 1.7e+308 %If

5Q. What is Operator ? List various types of Operators available in C ? Explain any three
Operators with example ?

Ans. An Operator is a symbol that tells the compiler to perform specific mathematical or
logical functions .

Different types of Operators in C are

1)Arithmetic Operators
2)Relational Operators
3)Logical Operators
4)Assignment Operators
5)Conditional Operators
6)Bitwise Operators
7)Increment and decrement operator
8)Others Operators

Arithmetic Operators
C provides five arithmetic operators, they are
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Example
/*Program to demonstrate arithmetic operators*/
#include<stdio.h>
int main()
{
int a,b;
printf("Enter two numbers:");
scanf("%d %d", &a, &b);
printf("Sum =%d",(a+b));
printf("Difference=%d",(a-b));
printf("Product=%d",(a*b));
printf("Division=%d",(a/b));
printf("Modulus=%d",(a%b));
return0;
}
Output:
Entertwonumbers:2510
Sum =35Difference=15Product=250Division=2Modulus=5
Relational Operators
C supports following 6 relational operators
Operator Meaning

> Greater than


>= Greater than or equal
< Lesser than
<= Lesser than or equal
== Equal !
= Not Equal

Example

/*Program to demonstrate relational operators*/


#include<stdio.h>
int main()
{
printf(“5>2is%d”,5>2);
printf(“\n5>=2is%d”,5>=2);
printf(“\n5<2is%d”,5<2);
printf(“\n5<=2is%d”,5<=2);
printf(“\n5==2is%d”,5==2);
printf(“\n5!=2is%d”,5!=2);
}
Output
5>2is1
5>=2is1
5<2is0
5<=2is0
5==2is0
5!=2is1

4)Assignment Operator and short hand operation


Operator Meaning
= assign
+= add and assign
-= subtract and assign
*= multiply and assign
/= divide and assign

Example

/*Program to demonstrate usage of assignment operators*/


#include<stdio.h>
int main()
{
int a=7,b=5,c=2,d=3;
printf(“Before operation a=%d, b=%d, c=%d, d=%d” , a, b ,c ,d);
a=10;
b+=a;
c-=a;
d*=b;
printf(“\n After operation a=%d, b=%d, c=%d, d=%d”, a, b, c, d);
return0;
}
Output
Before operation a=7,b=5,c=2,d=3
After operation a=10,b=15,c=-8,d=45

6Q. Explain the various decision making statements in C?

Ans. a)Decision making(selection)Statements


A program is nothing but the execution of sequence of one or more instructions.

In the monolithic program the sequences of instructions are executed in the same order
as they appear in the program. In practical applications, there are a number of situations
where one has to change the order of the execution of statements based on the
conditions. This involves decision making condition to see whether a particular
condition is satisfied or not
.The conditions can be placed in the program using decision – making
statements. C Language supports the control statements as listed below
i) If statements
ii) Switch statements

i)If statements
It has 3 forms
I. The simple if Statement
II. The if–else Statement
III. The nested if Statement
I. Simple if

Simple if has only one option. The set of statements are executed when
the logical condition is true, Otherwise the if statement is skipped.

syntax:
if(condition)
{statements;}
Example:
1. /* Program to find discount */

#include<stdio
.h> int main()
{
float p,d = 0,t;
printf("Enter the purchased
amount:"); scanf("%f",&p);
if(p>=5000)
{
d = p*(10.0/100);
}
t = p - d;
printf("Discount =
%.2f",d); printf("\nTotal
amount = %.2f",t); return
0;
}
Output
Enter the purchased
amount:6000 Discount =
600.00
Total amount = 5400.00

If...Else Statement
If else is two way decision making statement. It has two options.
One choice will be selected out of two options. It has two blocks. One block
is for if and other block is for else. If the condition is true, the if block
statements are executed, and if the condition is false, else block statements
are executed

syntax:
if(condition)
{
Statements A;
}
else
{
Statements B }
1./*Program to verify whether given character is vowel or not*/
#include<stdio.h>
int main()
{
char ch;
printf("Enter an alphabet(a-z):");
scanf("%c",& ch);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
printf("Vowel");
else
printf("consonants");
}
Output
Enter an alphabet(a-z):e
Vowel

III. Nested if statement


In this kind of statements number of logical conditions is checked for executing
various statements .if…consists of another if…else.
Syntax:

if(condition1)
{
if(condition2)
{
statements;
}
else if(condition3)
{
statements;
}
}
else
{
statements;
}

//program to check whether the student is pass or failed


#include<stdio.h>
int main()
{
int x ,y ,t;
printf("Enter internal marks:");
scanf("%d" ,&x);
printf("Enter External marks:");
scanf("%d" ,&y);
t=x+y;
if(t>=40)
{
if(y>=26)
{
printf("Student is passed");
}
else
{
printf("Student is failed");
}
}
else
{
printf("Student is failed");
}
return0;

Switch case

Switch is a multi-way decision-making statement that tests whether an


expressionmatchesoneofanumberofalternatevaluesandbrachesaccordingly.
It has many options .Only one choice will be selected among different options.
Theswitchstatementrequiresonlyoneargumentexpressionwhichischecked
withnumberofcaseoptions.Thedatatypeoftheexpressionmustbeeitherintorchar.
Theswitchstatementevaluatesexpressionandthenlooksforitsvalueamongthecase
constants.Ifthevaluematcheswithcaseconstant,thisparticularcasestatementis
executed .If not, default is executed.
NOTE: Switch is alternative to else if ladder

Syntax:
switch(expression)
{
case constant_ value: statement;
break;
case constant_ value: statement;
break;
case constant _value: statement;
break;
default :statement;
}

1./*Program to check given alphabet is vowel or consonant*/


#include<stdio.h>
int main()
{
char ch;
printf("Enter a character(a-z or A-Z):");
scanf("%c" ,&ch);
switch( ch )
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U': printf("\n Vowel");
break;
default : printf("\n Consonant");
}
}
Output:
Enter a character(a-z or A–Z):Z
Consonant

7Q. Explain the switch case statement with suitable examples?


Ans. Switch case

Switch is a multi-way decision-making statement that tests whether an


expressionmatchesoneofanumberofalternatevaluesandbrachesaccordingly.
It has many options .Only one choice will be selected among different options.
Theswitchstatementrequiresonlyoneargumentexpressionwhichischecked
withnumberofcaseoptions.Thedatatypeoftheexpressionmustbeeitherintorchar.
Theswitchstatementevaluatesexpressionandthenlooksforitsvalueamongthecase
constants.Ifthevaluematcheswithcaseconstant,thisparticularcasestatementis
executed .If not, default is executed.
NOTE: Switch is alternative to else if ladder

Syntax:
switch(expression)
{
case constant_ value: statement;
break;
case constant_ value: statement;
break;
case constant _value: statement;
break;
default :statement;
}

2./*Program to provide arithmetic functions by using switch*/


#include<stdio.h>
int main()
{
int a, b, ch ;
printf("\nMENU\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n
5.Remainder");
printf("Enter two numbers:");
scanf("%d%d" ,&a ,&b);
printf("\nEnteryourchoice:");
scanf("%d",& ch);
switch(ch)
{
case1: printf("Addition=%d",(a+b));
break;
case2: printf("Subtraction=%d",(a-b));
break;
case3: printf("Multiplication=%d",(a*b));
break;
case4: printf("division=%d",(a/b));
break;
case5: printf("Remainder=%d",(a%b));
break;
default: printf("Selected Wrong Choice");
}
return0;
}
Output
Menu
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Remainder
Entertwonumbers:3310
Enteryourchoice:4
Remainder=3

8Q. What is loop? Differentiate between while and do..while loop ?Write a Simple
program to demonstrate the while Operation?

Ans. Loop:
Loop is used to execute the block of code several times according to the condition given in
the loop. It means it executes the same code multiple times so it saves code and also helps
to traverse the elements of an array.
There are 3 types of loop –

 while loop
 do – while loop
 for loop

WHILE DO-WHILE
Condition is checked first then statement(s) is Statement(s) is executed at least once,
executed thereafter condition is checked.
It might occur statement(s) is executed zero At least once the statement(s) is executed.
times, If condition is false.
No semicolon at the end of while. Semicolon at the end of while.
while(condition) while(condition);
If there is a single statement, brackets are not Brackets are always required.

required
Variable in condition is initialized before the variable may be initialized before or within
execution of loop. the loop.
while loop is entry controlled loop. do-while loop is exit controlled loop.
while(condition) do { statement(s); }
{ statement(s); } while(condition);
while Loop –
While loop execute the code until condition is false.
while(condition){
//code
}
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 20;
while( i <=20 ) {
printf ("%d " , i );
i++;
}
getch();
}
Output
20

9Q. Discuss various looping statements in C language ?

Ans.

There are 3 types of loop –

 while loop
 do – while loop
 for loop

1. while Loop –
While loop execute the code until condition is false.
while(condition){
//code
}
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 20;
while( i <=20 ) {
printf ("%d " , i );
i++;
}
getch();
}
Output
20

2. do – while loop
It also executes the code until condition is false. In this at least once, code is executed
whether condition is true or false but this is not the case with while. While loop is executed
only when the condition is true.

Syntax
do{
//code
}while(condition);
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 20;
do{
printf ("%d " , i );
i++;
}
while( i < =20 );
get ch();
}
Output
20
21
3. for Loop
It also executes the code until condition is false. In this three parameters are given that is

 Initialization
 Condition
 Increment/Decrement

Syntax
for(initialization ;condition ;increment/decrement)
{
//code
}
It is used when number of iterations are known where while is used when number of
iterations are not true.
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for( i = 20; i < 25; i++) {
printf ("%d " , i);
}
getch();
}
Output
20
21
22
23
24
10Q. what is Array? explain various typed of Array in C language ? with suitable example.

Ans. An array is defined as the collection of similar types of data items stored at
contiguous memory locations.

There are two types of array in C language. They are

* One dimensional array

* Multi dimensional array (two dimensional array ,three dimensional array, four
dimensional array ...etc).

ONE DIMENSIONAL ARRAY


Declaration of Array
Data-type array-variable[size];
Data type: It is the data type of array elements.
The size represents no. of elements in the array.
An array will stay this size throughout the execution of the program. In other words, we
can change the size of an array at compile time, but cannot change it at run-time.
To declare regular variables we just specify a data type and a unique name:
int number;
To declare an array, we just add an array size.
For example:
int a[5];
Creates an array of 5 integer elements.
For example:
double stock price[31];

creates an array of 31 doubles.


Ex: int a[5];
The example tells to the compiler that ‘a’ is an integer type of array and can store
5 integers .The compiler reserves 2bytesofmemory for each integer array element.
Total space of 10 bytes are allocated to variable ‘a’

Memory allocation for array a

a[0] a[0] a[0] a[0] a[0]

The elements are represented as a[0],a[1]…..a[4].


Array Initialization
The array initialization is done is given below
int a[5]={12,14,16,17,18};
Here 5 elements are stored in an array ‘a’. The array elements are stored sequentially in
separate locations. Reading of array elements begins from ‘0’. Array elements are called
by array names followed by the element numbers. The 5elements are referred as
Subscripted variable a[0]refers to the first element of array a,12 i.e. a[0]=12
Subscripted variable a[1]refers to the first element of array a,14 i.e. a[1]=14
Subscripted variable a[2]refers to the first element of array a,16 i.e. a [2]=16
Subscripted variable a[3]refers to the first element of array a,17 i.e. a[3]=17
Subscripted variable a[5]refers to the first element of array a,18 i.e. a[4]=18
If the array size is declared as 5.The elements are stored from index 0 to 4.i.e.If a[5] has
been declared, then values are stored from a[0]to a[4].
The integer enclosed in brackets is the array subscript ,and its value must be in the range
from zero to one less than the number of memory cells in the array.
Option1Initializing all memory locations
If you know all the data at compile time ,you can specify all your data with in brackets:
int a[5]={12,14,16,17,18};

during compilation ,5 contiguous memory locations are reserved by the compiler for the
variable a and all these locations are initialized as shown in Fig.
a[0] a[1] a[2] a[3] a[4]
12 14 16 17 18
5000 5002 5004 5006 5008
If the size of integer is 2bytes,10bytes will be allocated for the variable a.
Option2initializationwithoutsize
If we omit the size of your array ,but specify an initial set of data ,the compiler
will automatically determine the size of your array. This way is referred as initialization
without size.
int a[]={75,79,82,70,68};
In this declaration, even though we have not specified exact number of elements to be
used in array a ,the array size will be set of the total number of initial values specified.
Here, the compiler creates an array of 5 elements.
Option 3 Partial Array Initialization
If the number of values to be initialized is less than the size of the array ,then the
elements are initialized in the order from 0th location. The remaining locations will be
initialized to zero automatically.
int a[5]={75,79,82}
a[0] a[1] a[2] a[3] a[4]
75 79 82 0 0
5000 5002 5004 5006 5008
Even though compiler allocates 5 memory locations ,using this declaration statement,
the compiler initializes first three locations with 75 ,70 and 82,the next set of memory
locations are automatically initialized to 0‟s by the compiler
Option4: initialize all elements to zero
If you do not know any data ahead of time ,but you want to initialize everything to 0, just
use 0 within{}.
For example: int a[5]={0};
This will initialize every element within the array to 0
a[0] a[1] a[2] a[3] a[4]
0 0 0 0 0
5000 5002 5004 5006 5008

Reading One Dimensional Array Elements From Input


for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
a[0] a[1] a[2] a[3] a[4]
22 12 34 15 30
5000 5002 5004 5006 5008
The above loop is used to read 5 elements into array from input
Writing elements of one dimensional array to output
for(i=0;i<5;i++)
{
printf("%d",a[i]);
}
The above loop is used to print 5 elements to output as shown below
22 12 34 15 30
TWO DIMENSIONAL ARRAYS
Two dimensional array is used to represent the elements of the matrix.Two-dimensional
array can be thought as a rectangular display of elements withrows and columns .The two
dimensional array is a collection of number of one dimensional arrays, which are placed
one after another.
Syntax:
Data type var [row size][col size];
Data type is the type of element so far matrix
Row size represents number of rows in the matrix.
col size represents number of cols in the matrix.
Declaration:
int a[3][2];
Here3indicatestheno.ofrowsand2indicatescolumns
Initialization:
int a[3][2]={21,22,23,24,25,26};
The values are stored in the following pattern
Col0 Col1
Row0 21 22
Row1 23 24
Row2 25 26
The values are represented as
a[0][0]=21;a[0][1]=22;
a[1][0]=23;a[1][0]=24;
a[2][0]=25;a[2][1]=26;

a[0][0] a[0][1] a[0][2]


21 22 23

a[1][0] a[1][1] a[1][1]


24 25 26

The total number of elements in two dimensional array is product of no. of rows and no. of
columns.
Example: int a[3][2];stores3x2=6valuesconceptuallystoredinmatrixform.
/*Program to read elements of two-dimensional array and print them in matrix format*/
void main()
{
int a[3][2],i ,j;
printf("Enterelementsof3x2matrix:");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
scanf("%d" ,&a[i][j]);
}
}
printf("Given Elements are:\n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
}
Output
Enterelementsof3x2matrix:
152637
Given elements
1 5
2 6
3 7

***** THE END *****

You might also like