Sunteți pe pagina 1din 200

1.Question: Explain in details Memory hierarchy with examples.

1. Memory Hierarchy
Memory is categorized into volatile and nonvolatile memories, with the former requiring
constant power ON of the system to maintain data storage.
Furthermore, a typical computer system provides a hierarchy of different times of memories
for data storage.

Different levels of the memory


hierarchy
1. Cache (MB): Cache is the fastest accessible memory of a computer system. It's access
speed is in the order of a few nanoseconds. It is volatile and expensive, so the typical
cache size is in the order of megabytes.
2. Main memory (GB): Main memory is arguably the most used memory. When discussing
computer algorithms such as quick sort, balanced binary sorted trees, or fast Fourier
transform, one typically assumes that the algorithm operates on data stored in the main
memory. The main memory is reasonably fast, with access speed around 100
nanoseconds. It also offers larger capacity at a lower cost. Typical main memory is in the
order of 10 GB. However, the main memory is volatile.
3. Secondary storage (TB): Secondary storage refers to nonvolatile data storage units that
are external to the computer system. Hard drives and solid state drives are examples of
secondary storage. They offer very large storage capacity in the order of terabytes at very
low cost. Therefore, database servers typically have an array of secondary storage devices
with data stored distributedly and redundantly across these devices. Despite the
continuous improvements in access speed of hard drives, secondary storage devices are
several magnitudes slower than main memory. Modern hard drives have access speed in
the order of a few milliseconds.
4. Tertiary storage (PB): Teriary storage refers storage designed for the purpose data
backup. Examples of tertiary storage devices are tape drives are robotic driven disk
arrays. They are capable of petabyte range storage, but have very slow access speed with
data access latency in seconds or minutes.

In this course, we are mainly concerned with the main memory


and the secondary storage of the memory hierarchy.

2. Data movement
In order to perform computation, data must travel from the secondary storage to the CPU.
Due to the vast differences in access speed and storage capacity, the operating system
performs a series of sophisticated steps (both at the levels of hardware and the software).

2.1. Move data to and from secondary storage

 Disk cache
The hard drive has a local data cache. Because the hard drive access speed is so much slower,
disk access are normally done asynchronously at the hardware level. The hard drive will be
instructed to fetch or save data from a physical location of a certain size. The hard drive
controller will acknowledge the instruction right away, and will take sometime to populate the
disk cache with the requested data block, and then, at a later time, raise an interrupt to notify
the interested party that the data access is complete. This model of interrupt based data transfer
is asynchronous.
The data transfer speed (from memory to hard drive or vice versa) depends on:

1. contiguousness of the accessed physical locations on the disk


2. the size of the accessed data per request

2.2. Performance characteristics


The mechanical design of the hard drive naturally leds itself to superior sequential access.
A hard drive consists of an (array of) rotating disk. Each disk has a head driven by a
mechanical arm which performs the bitwise read and write. If a sequential data block is
accessed, all bits can be read or written during a single rotation.
However, random access of the hard drive data may require multiple rotations for the head to
reach all the regions on the disk.
Explain in details Memory hierarchy with examples.
 The memory system is a hierarchy of storage devices with different
capacities, costs, and access times.

 The idea centers on a fundamental property of computer programs known as


locality. Programs with good locality tend to access the same set of data items
over and over again, or they tend to access sets of nearby data items.
Programs with good locality tend to access more data items from the upper
levels of the memory hierarchy than programs with poor locality, and thus run
faster. Figure 1 shows a typical memory hierarchy with relationship between
the cost per bit, the access time and the hierarchy.

 Memory hierarchies work because well-written programs tend to access the


storage at any particular level more frequently than they access the storage at
the next lower level. So the storage at the next level can have a larger access
time, and thus will be larger in size and cheaper per bit.
 The overall effect is a large pool of memory that costs as much as the cheap
storage near the bottom of the hierarchy, but that serves data to programs at
almost the rate of the fast storage near the top of the hierarchy.

1. Registers

 CPU registers are at the top most level of this hierarchy, they hold the most
frequently used data. They are very limited in number and are the fastest.

 They are often used by the CPU and the ALU for performing arithmetic and
logical operations, for temporary storage of data.

2. Cache

 The very next level consists of small, fast cache memories near the CPU.
They act as
 staging areas for a subset of the data and instructions stored in the relatively
slow main memory.
 There are often two or more levels of cache as well. The cache at the top
most level after the registers is the primary cache. Others are secondary
caches.
 Many a times there is cache present on board with the CPU along with other
levels that are outside the chip.

3. Main Memory:

 The next level is the main memory, it stages data stored on large, slow disks
often called hard disks. These hard disks are also called secondary memory,
which are the last level in the hierarchy. The main memory is also called
primary memory.

 The secondary memory often serves as staging areas for data stored on the
disks or tapes of other machines connected by networks.

Performance Considerations: (Access Time vs cost vs size)

 A programmer needs to understand the memory hierarchy because it has a


big impact on the performance of his applications.
 For example:

If the data your program needs are stored in a CPU register, then they can be
accessed in zero cycles during the execution of the instruction. If stored in a
cache, 1 to 30 cycles. If stored in main memory, 50 to 200 cycles. And if
stored in disk tens of millions of cycles. This is obviously delay being
introduced.

 On the other hand, the cost per bit is the least for the secondary memory,
which is more at the primary memory level. This increases till at the register
level where it is the maximum.
 Similarly, memory sizes are smallest at the register level. This increases to a
few KBs in the cache, few hundreds of MBs or even GBs nowadays in the
main memory, to hundreds of GB’s in the secondary memory.
 Thus there is a tradeoff between cost, access time, size and all this needs to
be taken into account when designing the memory hierarchy for a computer
system.

2. What is the difference between an Assembler and a


Compiler?

Answer:

Assembler: Assembler is a software or a tool that translates Assembly language into machine code.

The difference between an Assembler and a Compiler is given below.

Assembler:

1. Assembler is a computer program that reads code written in one language which is called
Assembly language and translates into machine language.
2. Assembler is used in low-level Assembly language.
3. Assembler is less popular than compiler.

Compiler:

1. Compiler is a computer program that reads code (like C,C++ code )and translates into machine
language.
2. Compiler is used in high-level language.
3. Compiler is more popular than Assembler.

What is the difference between an Assembler and a Compiler?


Difference Between Compiler and
Assembler
January 27, 2017 Leave a Comment
Compiler and
Assembler plays an important role in the execution of a program. Some
compilers directly generate the executable code instead of assembly code.
The compiler takes the preprocessed source code and translates it into the
assembly code. The assembler takes the assembly code from the compiler
and translates it to the relocatable machine code. In this article, I have
discussed the differences between compiler and assembler with the help of
comparison chart shown below, just have a look.

Content: Compiler Vs Assembler


1. Comparison Chart
2. Definition
3. Key Differences
4. Conclusion

Comparison Chart

BASIS FOR
COMPILER ASSEMBLER
COMPARISON

Basic Generates the assembly language code or Generates the relocatable

directly the executable code. machine code.

Input Preprocessed source code. Assembly language code.

Phases/ Passes The compilation phases are lexical Assembler makes two passes

analyzer, syntax analyzer, semantic over the given input.

analyzer, intermediate code generation,

code optimization, code generation.


BASIS FOR
COMPILER ASSEMBLER
COMPARISON

Output The assembly code generated by the The relocatable machine code

compiler is a mnemonic version of generated by an assembler is

machine code. represented by binary code.

Definition of Compiler
The compiler is a computer program that reads the program written in a
source language, translates it into equivalent assembly language and
forwards the assembly language code to the Assembler. While the
translation of the source code to assembly code the compiler also reports
the error in the source code to its user.

Compilers are also classified as single-pass, multi-pass, load-and-go,


debugging and optimization. Classification is done on the basis of what
function does a compiler perform and how it has been constructed. Despite
these complexities, the basic task of compiler remains same.

The compilation is performed in two parts, analysis part and synthesis


part. The analysis part breaks the source code into constituent pieces and
forms the intermediate representation of the source code. The synthesis
part forms the target code from the intermediate representation.

The compilation is performed in the following phases:

Lexical analyzer, syntax analyzer, semantic analyzer, intermediate code


generator, code optimizer, code generator, Symbol table and error Handler.

The lexical analyzer reads the characters of source code and groups
them into the streams of tokens. Each token represents the logical
sequence of characters like keyword, identifiers, operators. The
sequence of character that forms a token is called lexeme.
 The syntax analyzer parses the token obtained from lexical analyzer
and groups tokens into a hierarchical structure.
 The semantic analyzer checks the source code for any semantic
error.
 Intermediate code generator generates the intermediate
representation of the source code
 The code Optimizer optimizes the intermediate code into faster
running machine code.
 The code generator finally generates the target code which is
a relocatable machine code or an assembly code.
 The symbol table is a data structure which contains the record for
each identifier in the source code.
 Error handler detects the error in each phase and handles those
errors.

Definition of Assembler
Some compilers perform the task of assembler and directly generate a
relocatable machine code instead of assembly code, which is further directly
passed to linker /loader. The assembler takes as input the assembly code
generated by the compiler and translates it into relocatable machine code.

Let us see how machine code is


different from assembly code. Assembly code is the mnemonic version of
machine code. It means it assembly code uses names for representing
operations and it even gives names to the memory addresses. On the other
hands, the machine code uses binary codes for representation of
operations and memory addresses.

Even the simplest form of assembler performs two passes over the input.
The first pass detects all the identifiers in the assembly code that denotes
storage location and store them in the symbol table (other than compilers
symbol table). The storage location is assigned to the identifier that is
encountered in the first pass.

In the second pass, the input is scanned again, and this time
the operation code are translated into a sequence of bits representing
that operation in the machine code. The second pass also
translates identifiers into the addresses defined in the symbol table. Thus
the second pass generates the relocatable machine code.

Key Differences Between Compiler and Assembler


1. The key difference between compiler and assembler is that
the compiler generates assembly code and some compilers can also
directly generate executable code whereas, the assembler generates
relocatable machine code.
2. The compiler takes as input the preprocessed code generated by
preprocessor. On the other hands, the assembler takes assembly
code as input.
3. The compilation takes place in two phases that are analysis
phase and synthesis phase. In analysis phase, the input goes
through lexical analyzer, syntax analyzer, semantic
analyzer whereas, the synthesis analysis takes place via intermediate
code generator, code optimizer, code generator. On the other
hands, assembler passes the input through two phases. The first
phase detects the identifiers and allots addresses to them in the second
phase the assembly code is translated to binary code.
4. The assembly code generated by the compiler is a mnemonic
version of machine code. However, the relocatable machine code
generated by assembler is a binary relocatable code.
Conclusion:
The assembler may not be required as some compilers directly generate
executable code. If assembler is used it requires linker to link all the built-in
libraries to the library functions used in the source code.

What is the difference between an Assembler and a Compiler?


COMPILER VS ASSEMBLER
There are many languages present to use for the developing the software. These compilers are
made to do a simple work. In simple language, these are work on a very basic principle, They just
read a code or a program written for the developing of the software. These can change this code
written by the humans in the language of the humans to the language of the machine. This code
written by the humans is known as the source code. This code written by the humans is
considered as a high-profile language. These compilers convert this high-profile language to the
simplest language for the machine/computer which is the binary language.

COMPILER
The compiler works on a basic principle. It simply reads the whole program written on it. Then it
converts the whole program to the machine/computer language. For this process, the compiler
takes a lot of time to read the whole program or to analyze the whole program. The compilers are
generally the memory eaters. They need a lot of memory to complete their process. Because they
create the object code by analyzing the program written on them. They work fast as compared to
the interpreters. Because they have the very less execution time. In this process, the whole
program doesn’t require to be created/compiled every time. Languages like to C and the C++
commonly used the compilers.

ASSEMBLER
Assembler is also a compiler. But in the assembler, the source code is written in the Assembly
language. This assembly language is a simple language. And this language is understandable by
the humans as well. The work of an assembler is to convert the assembly language to the machine
language. The assembler works on the principle of the one to one mapping translation. There are
improvements coming in the assemblers day by day. They are becoming very easy and user-
friendly programs to use as well. The latest editions of the assemblers work very efficiently and
they help us in the debugging of the written code as well.

DIFFERENCE BETWEEN COMPILER AND


ASSEMBLER
 The compiler is a simple program which converts the source code written by the humans to a
machine language. While the assembler has a little bit different work, it converts the
assembly language to the machine language.
 Compilers work more directly than the assemblers. The compilers can convert the human
written code in the machine language directly. But the assembler can’t do this at once. It
converts a source code to an object code first then it converts the object code to the machine
language with the help of the linker programs.

3. Difference between Structure and Union in C


structures in C
A structure is a user-defined data type available in C that allows to combining data items of different
kinds. Structures are used to represent a record.
Defining a structure: To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than one member. The format of the struct statement is
as follows:
struct [structure name]

member definition;

member definition;

...

member definition;

};

union
A union is a special data type available in C that allows storing different data types in the same memory
location. You can define a union with many members, but only one member can contain a value at any
given time. Unions provide an efficient way of using the same memory location for multiple purposes.
Defining a Union: To define a union, you must use the union statement in the same way as you
did while defining a structure. The union statement defines a new data type with more than one member
for your program. The format of the union statement is as follows:
union [union name]

member definition;

member definition;

...

member definition;

};

Similarities between Structure and Union


1. Both are user-defined data types used to store data of different types as a single unit.
2. Their members can be objects of any type, including other structures and unions or arrays. A
member can also consist of a bit field.
3. Both structures and unions support only assignment = and sizeof operators. The two structures
or unions in the assignment must have the same members and member types.
4. A structure or a union can be passed by value to functions and returned by value by functions.
The argument must have the same type as the function parameter. A structure or union is passed
by value just like a scalar variable as a corresponding parameter.
5. ‘.’ operator is used for accessing members.
Differences

// C program to illustrate differences


// between structure and Union
#include <stdio.h>
#include <string.h>

// declaring structure
struct struct_example
{
int integer;
float decimal;
char name[20];
};

// declaraing union

union union_example
{
int integer;
float decimal;
char name[20];
};

void main()
{
// creating variable for structure
// and initializing values difference
// six
struct struct_example s={18,38,"geeksforgeeks"};

// creating variable for union


// and initializing values
union union_example u={18,38,"geeksforgeeks"};

printf("structure data:\n integer: %d\n"


"decimal: %.2f\n name: %s\n",
s.integer, s.decimal, s.name);
printf("\nunion data:\n integeer: %d\n"
"decimal: %.2f\n name: %s\n",
u.integer, u.decimal, u.name);

// difference two and three


printf("\nsizeof structure : %d\n", sizeof(s));
printf("sizeof union : %d\n", sizeof(u));

// difference five
printf("\n Accessing all members at a time:");
s.integer = 183;
s.decimal = 90;
strcpy(s.name, "geeksforgeeks");

printf("structure data:\n integer: %d\n "


"decimal: %.2f\n name: %s\n",
s.integer, s.decimal, s.name);

u.integer = 183;
u.decimal = 90;
strcpy(u.name, "geeksforgeeks");

printf("\nunion data:\n integeer: %d\n "


"decimal: %.2f\n name: %s\n",
u.integer, u.decimal, u.name);
printf("\n Accessing one member at time:");

printf("\nstructure data:");
s.integer = 240;
printf("\ninteger: %d", s.integer);

s.decimal = 120;
printf("\ndecimal: %f", s.decimal);

strcpy(s.name, "C programming");


printf("\nname: %s\n", s.name);

printf("\n union data:");


u.integer = 240;
printf("\ninteger: %d", u.integer);

u.decimal = 120;
printf("\ndecimal: %f", u.decimal);

strcpy(u.name, "C programming");


printf("\nname: %s\n", u.name);

//difference four
printf("\nAltering a member value:\n");
s.integer = 1218;
printf("structure data:\n integer: %d\n "
" decimal: %.2f\n name: %s\n",
s.integer, s.decimal, s.name);

u.integer = 1218;
printf("union data:\n integer: %d\n"
" decimal: %.2f\n name: %s\n",
u.integer, u.decimal, u.name);
}
Run on IDE
Output:

structure data:

integer: 18

decimal: 38.00

name: geeksforgeeks

union data:

integeer: 18

decimal: 0.00

name: ?

sizeof structure: 28

sizeof union: 20

Accessing all members at a time: structure data:


integer: 183

decimal: 90.00

name: geeksforgeeks

union data:

integeer: 1801807207

decimal: 277322871721159510000000000.00

name: geeksforgeeks

Accessing one member at a time:

structure data:

integer: 240

decimal: 120.000000

name: C programming

union data:

integer: 240

decimal: 120.000000

name: C programming

Altering a member value:

structure data:

integer: 1218

decimal: 120.00

name: C programming

union data:

integer: 1218

decimal: 0.00

name: ?

4. What is ASCII Code?


ASCII Stands for American Standard Code for Information Interchange (pronounced
'as-key'). This is a standard set of characters understood by all computers, consisting
mostly of letters and numbers plus a few basic symbols such as $ and %. Which
employs the 128 possible 7-bit integers to encode the 52 uppercase and lowercase
letters and 10 numeric digits of the Roman alphabet, plus punctuation characters and
some other symbols. The fact that almost everyone agrees on ASCII makes it
relatively easy to exchange information between different programs,
different operating systems, and even different computers.
It also means you can easily print basic text and numbers on any printer, with the
notable exception of PostScript printers. If you are working in the MacWrite word
processing application on the Mac and you need to send your file to someone who
uses WordStar on the PC, you can save the document as an ASCII file (which is the
same as text-only). After you transfer the file to the PC (on a disk or via a cable or
modem),the other person will be able to open the file in WordStar.
In ASCII, each character has a number which the computer or printer uses to
represent that character. For instance, a capitalAis number 65 in the code. Although
there are 256 possible characters in the code, ASCII standardizes only 128 characters,
and the first 32 of these are "control characters," which are supposed to be used to
control the computer and don't appear on the screen. That leaves only enough code
numbers for all the capital and lowercase letters, the digits, and the most common
punctuation marks.
Another ASCII limitation is that the code doesn't include any information about the way
the text should look (its format). ASCIIonly tells you which characters the text contains.
If you save a formatted document asASCII,you will lose all the font formatting, such as
the typeface changes, the italics, the bolds, and even the special characters like ©,
TM, or ®. Usually carriage returns and tabs are saved.
Unlike some earlier character encodings that used fewer than 7 bits, ASCII does have
room for both the uppercase and lowercase letters and all normal punctuation
characters but, as it was designed to encode American English it does not include the
accented characters and ligatures required by many European languages (nor the UK
pound sign £). These characters are provided in some 8-bit EXTENDED ASCII
character sets, including ISO LATIN 1 or ANSI 1, but not all software can display 8-bit
characters, and some serial communications channels still remove the eighth bit from
each character. Despite its shortcomings, ASCII is still important as the 'lowest
common denominator' for representing textual data, which almost any computer in the
world can display.
The ASCII standard was certified by ANSI in 1977,and the ISO adopted an almost
identical code as ISO 646.

ASCII may refer to any of the following:


1. Short for American Standard Code for Information
Interexchange, ASCII is a standard that assigns letters, numbers,
and other characters within the 256 slots available in the 8-bit code.
The ASCII decimal (Dec) number is created from binary, which is the
language of all computers. As shown in the table below, the lower
case "h" character (Char) has a decimal value of 104, which is
"01101000" in binary.
ASCII was first developed and published in 1963 by the X3 committee, a
part of the American Standards Association (ASA). The ASCII standard
was first published as ASA X3.4-1963, with 10 revisions of the standard
being published between 1967 and 1986.
The ASCII table is divided into 3 different sections.
 Non printable, system codes between 0 and 31.
 Lower ASCII, between 32 and 127. This table originates from the older, American
systems, which worked on 7-bit character tables.
 Higher ASCII, between 128 and 255. This portion is programmable; characters are
based on the language of your operating system or program you are using. Foreign
letters are also placed in this section.
Standard or Lower ASCII characters and codes
Char Dec Binary Char Dec Binary Char De

! 033 00100001 A 065 01000001 a 09


" 034 00100010 B 066 01000010 b 09
# 035 00100011 C 067 01000011 c 09
$ 036 00100100 D 068 01000100 d 10
% 037 00100101 E 069 01000101 e 10
& 038 00100110 F 070 01000110 f 10
' 039 00100111 G 071 01000111 g 10
( 040 00101000 H 072 01001000 h 10
) 041 00101001 I 073 01001001 i 10
* 042 00101010 J 074 01001010 j 10
+ 043 00101011 K 075 01001011 k 10
, 044 00101100 L 076 01001100 l 10
- 045 00101101 M 077 01001101 m 10
. 046 00101110 N 078 01001110 n 11
/ 047 00101111 O 079 01001111 o 11
0 048 00110000 P 080 01010000 p 11
1 049 00110001 Q 081 01010001 q 11
2 050 00110010 R 082 01010010 r 11
3 051 00110011 S 083 01010011 s 11
4 052 00110100 T 084 01010100 t 11
5 053 00110101 U 085 01010101 u 11
6 054 00110110 V 086 01010110 v 11
7 055 00110111 W 087 01010111 w 11
8 056 00111000 X 088 01011000 x 12
9 057 00111001 Y 089 01011001 y 12
: 058 00111010 Z 090 01011010 z 12
; 059 00111011 [ 091 01011011 { 12
< 060 00111100 \ 092 01011100 | 12
= 061 00111101 ] 093 01011101 } 12
> 062 00111110 ^ 094 01011110 ~ 12
? 063 00111111 _ 095 01011111 _ 12
@ 064 01000000 ` 096 01100000
Extended ASCII uses eight instead of seven bits, which adds 128
additional characters. This gives extended ASCII the ability for extra
characters, such as special symbols, foreign language letters, and drawing
characters as shown below.
Extended or Higher ASCII characters and codes
What is ASCII?
This content has been archived, and is no longer maintained by
Indiana University. Resources linked from this page may no
longer be available or reliable.
ASCII is an acronym for American Standard Code for Information Interchange, a
widely used standard for encoding text documents on computers. Usually, a file
described as "ASCII" does not contain any special embedded control characters; you
can view the contents of the file, change it with an editor, or print it with a printer.
In ASCII, every letter, number, and punctuation symbol has a corresponding number,
or ASCII code. For example, the character for the number 1 has the code 49, capital
letter A has the code 65, and a blank space has the code 32. This encoding system
not only lets a computer store a document as a series of numbers, but also lets it
share such documents with other computers that use the ASCII system.

Documentation files or program source code files are usually stored as ASCII text. In
contrast, binary files, such as executable programs, graphical images, or word
processing documents, contain other characters that cannot be normally displayed
or printed, and are usually illegible to human beings.

The format of a file, whether ASCII or binary, becomes important when you are
transferring files between computers. For example, when using FTP, you can
transfer ASCII text files without any special consideration. To exchange binary files,
however, you may need to enter the command set binary or otherwise prepare the
client to transfer binary files, so that the computer will correctly transmit the special
characters in the file.

Note: Most current FTP software will automatically transfer ASCII and binary files
correctly.

5.explain binary addition subtraction multiplication and division


with example
Binary Arithmetic
Binary arithmetic is essential part of all the digital computers and many
other digital system.

Binary Addition
It is a key for binary subtraction, multiplication, division. There are four
rules of binary addition.

In fourth case, a binary addition is creating a sum of (1 + 1 = 10) i.e. 0 is


written in the given column and a carry of 1 over to the next column.
Example − Addition

Binary Subtraction
Subtraction and Borrow, these two words will be used very frequently
for the binary subtraction. There are four rules of binary subtraction.

Example − Subtraction

Binary Multiplication
Binary multiplication is similar to decimal multiplication. It is simpler than
decimal multiplication because only 0s and 1s are involved. There are four
rules of binary multiplication.

Example − Multiplication
Binary Division
Binary division is similar to decimal division. It is called as the long division
procedure.

Example − Division

6.write a c program to reverse the


given string
Reverse a string in C
Reverse a string in C: This program reverses a string that a user inputs.
For example, if a user enters a string "reverse me" then on reversing it
will be "em esrever". C program to reverse a string using strrev library
function of "string.h", without using strrev, recursion and pointers. A
string which remains the same on reversal is a palindrome string.
String reverse in C
#include <stdio.h>
#include <string.h>

int main()
{
char arr[100];

printf("Enter a string to reverse\n");


gets(arr);

strrev(arr);

printf("Reverse of the string is \n%s\n",


arr);

return 0;
}

C reverse string program output:

Download Reverse string program.

C program to reverse words in a string


Reverse string C program without using
strrev
First we calculate length of the string without using strlen function and
then copy its characters in reverse order (from end to beginning) to a
new string using a for loop.

#include <stdio.h>

int main()
{
char s[1000], r[1000];
int begin, end, count = 0;

printf("Input a string\n");
gets(s);

// Calculating string length

while (s[count] != '\0')


count++;

end = count - 1;

for (begin = 0; begin < count; begin++) {


r[begin] = s[end];
end--;
}

r[begin] = '\0';
printf("%s\n", r);

return 0;
}

C program to reverse a string using


recursion
#include <stdio.h>
#include <string.h>

void reverse(char*, int, int);

int main()
{
char a[100];

gets(a);

reverse(a, 0, strlen(a)-1);

printf("%s\n", a);

return 0;
}

void reverse(char *x, int begin, int end)


{
char c;

if (begin >= end)


return;

c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;

reverse(x, ++begin, --end);


}

In the recursive method, we swap characters at the beginning and the


end of the string and then move towards the middle of the string. This
way is inefficient due to repeated function calls but useful in practicing
recursion.

C program to reverse a string using


pointers
Now we will invert a string using pointers or without using the library
function strrev.

#include<stdio.h>

int string_length(char*);
void reverse(char*);

main()
{
char s[100];

printf("Enter a string\n");
gets(s);

reverse(s);

printf("Reverse of the string is \"%s\".\n",


s);

return 0;
}

void reverse(char *s)


{
int length, c;
char *begin, *end, temp;

length = string_length(s);
begin = s;
end = s;

for (c = 0; c < length - 1; c++)


end++;

for (c = 0; c < length/2; c++)


{
temp = *end;
*end = *begin;
*begin = temp;

begin++;
end--;
}
}

int string_length(char *pointer)


{
int c = 0;

while( *(pointer + c) != '\0' )


c++;

return c;
}

6. distinguish between dos and windows operating


system
Distinguish, differentiate, compare and explain what is the main difference between DOS and
WINDOWS Operating System

Difference between DOS and WINDOWS


Operating System
1. Dos is a Single user operatIng system. Windows is a multi-user operating system.
2. In DOS, all commands are text based. In Windows, commands can be given by clicking on
the icons.
3. Dos uses Command-line Interface. Windows used graphical user Interface.
4. Dos does not support networking. Windows support networking.
5. Server administration Is not possible in Dos. Server administration is possible in
Windows.
6. While working in DOS, all the commands need to be remembered. In Windows,
commands are readily available.
7. DOS can open only one window at a time. Multiple windows can be opened at a time
in windows operating system.

Difference between DOS and WINDOWS


Operating System
DOS is command line while windows is graphical user interface
DOS handles file names up to 8 characters while windows allows long file names up to
255 characters
DOS is single user while windows is multi user
DOS allows single tasking while windows allows multi tasking
DOS is not user friendly while windows is user friendly

Difference between DOS and Windows


Key Difference: DOS or Disk Operating Systems are operating systems that were most
commonly found the IBM PCs and were popular between 1981 and 1995. Windows is a
range of graphical interface operating systems that are developed and sold by
Microsoft.
Before the Windows vs. Apple war and when times were simpler, there was a computing
system known as DOS (Disk Operating System) which dominated the IBM PC. Back then
when you bought a computer, it was most commonly an IBM that had a DOS operating
system. DOS and Windows differ from each other in many aspects.

DOS or Disk Operating Systems are operating systems


that were most commonly found the IBM PCs and were popular between 1981 and 1995.
Many DOS versions have been released by different companies, the most popular being the
MS-DOS, also by Microsoft. Related systems include MS-DOS, PC-DOS, DR-DOS,
FreeDOS, PTS-DOS, ROM-DOS, Novell DOS, OpenDOS and 86-DOS. The 86-DOS or
QDOS (Quick and Dirty Operating System) was bought by Microsoft for the IBM PC.

Windows is a range of graphical interface operating systems that are developed and sold by
Microsoft. Early versions of Microsoft Windows ran on top of a separate version of DOS and
it ceased to be used when Windows 95 was launched as a stand-along operating system that
did not require a separate DOS license. With Windows 95 and 98, but not ME, the MS-DOS
component could be run without starting Windows. When DOS was no longer required to run
the system, it was completely stopped being used in PCs. The DOS is now obsolete and is
very rarely used in the real world. DOS and Windows differ from each other greatly even
though Windows is believed to be derived from DOS.

DOS and Windows differ in GUI (graphical user


interface), where DOS uses a full text command input, Windows uses images, icons and text
in their interface. The full text command input in DOS required users to input commands and
work on the computer using text codes; making it harder to understand for first-time users or
less tech savvy people. Windows simplified the graphical user interface, by using the help of
icons, images and text; eliminated the need for remembering the codes and the actions that go
with the codes.

DOS also offered less storage space compared to Windows. The highest storage space that
DOS offered came around 2 gigabyte, while the latest Windows offers storage space in
terabytes. Windows can also accommodate much larger hard drives, while DOS cannot due
to its dependence on FAT16 file system.

DOS and Windows also differ in terms of registry systems and swap files. While DOS uses a
directory system, where all the files are contained within a particular directory or a
subdirectory, Windows uses a much complicated registry system making it difficult to
manually delete files from the system and excessive files can cause the system to slow down
or crash.

DOS Windows

DOS (Disk Operating System) Windows is a range of graphical


are simple text command interface operating systems that
Definition
operating systems that were are developed and sold by
popular from 1981 to 1995. Microsoft.
DOS used a text based interface
Windows uses graphics, images
GUI that required text and codes to
and text.
operate

Text is used as the basic input Uses a mouse for all operating
Input System
system commands. system input.

Windows is a multitasking
DOS is unable to run multiple operating system; allowing more
Multitasking
processes at the same time. than one process to work
simultaneously.

The highest amount of storage Window systems offer storage


Storage Size
size available is 2GB. space up to 2 terabyte.

Booting up system is DOS is Booting up Windows is more


Demands on System Resources
less demanding on the CPU. demanding on the CPU.

Windows uses a different


registry compared to DOS,
DOS uses a directory system,
making it difficult to manually
where all the files are contained
Registry and Swap Files delete programs. An excessive
within a particular directory or a
number of temporary files and
subdirectory.
file fragments can cause the
system to slow down or crash.

More ideally used for


Used worldwide as the most
Current Uses prototyping, testing, and making
popular operating system.
automated systems.

Price DOS is free Windows is costly

Due to the decline of usage for DOS, most versions of DOS are now available for free in the
market. It is also simple to use and does not require gigabytes of memory in order to work
compared to Windows. DOS has become ideal for prototyping, testing, and making
automated systems that only require checking if and when something goes wrong. Due to its
simplicity in usage and lack of fancy GUIs, the system is also much cheaper to operate.
What is the difference between a DOS laptop and
Windows 8 laptop?
Well in a DOS laptop you get the default OS as FreeDOS. If you are interested to
know more then just google it up. In a windows laptop the original windows OS
comes preinstalled along with some softwares like antivirus,office and so on. Buying
a DOS laptop can save you a lot of bucks,probably around 2k to 3k but you will have
to go about installing windows OS and all the required drivers for your laptop. You
will not get any preinstalled softwares aslike a windows laptop. I bought a DOS laptop
6 months ago intending to save some money and I have never regretted my decision.
In fact I installed windows 8 after removing FreeDOS and it works like a charm. I
installed all the required drivers and softwares and I am very much satisfied. I also
got to learn some new things down the line and I am really very proud of the decision
that I took that day. So in short I would say 'No Pain No Gain'. So go for a DOS laptop
and also if you are not aware there are better options than windows like linux out
there which are completely free and powerful unlike windows. So just try to get some
hands on experience because it is better not to be spoonfed all the time.

C program to multiply two


8.

matrices
Write a C program to read elements in two matrices and multiply them. Matrix
multiplication program in C. How to multiply matrices in C. Logic to multiply two
matrices in C programming.

Example

Input

Input elements of matrix1:


1 2 3
4 5 6
7 8 9
Input elements of matrix2:
9 8 7
6 5 4
3 2 1

Output

Product of matrices =
30 24 18
84 69 54
138 114 90
Matrix Multiplication
Two matrices can be multiplied only and only if number of columns in the first matrix
is same as number of rows in second matrix. Multiplication of two matrices is defined
as -

Program to multiply two matrices


/**
* C program to multiply two matrices
*/

#include <stdio.h>

#define SIZE 3 // Size of the matrix

int main()
{
int A[SIZE][SIZE]; // Matrix 1
int B[SIZE][SIZE]; // Matrix 2
int C[SIZE][SIZE]; // Resultant matrix

int row, col, i, sum;

/* Input elements in first matrix from user */


printf("Enter elements in matrix A of size %dx%d: \n", SIZE, SIZE);
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
scanf("%d", &A[row][col]);
}
}

/* Input elements in second matrix from user */


printf("\nEnter elements in matrix B of size %dx%d: \n", SIZE, SIZE);
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
scanf("%d", &B[row][col]);
}
}

/*
* Multiply both matrices A*B
*/
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
sum = 0;
/*
* Multiply row of first matrix to column of second matrix
* and store sum of product of elements in sum.
*/
for(i=0; i<SIZE; i++)
{
sum += A[row][i] * B[i][col];
}

C[row][col] = sum;
}
}

/* Print product of the matrices */


printf("\nProduct of matrix A * B = \n");
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
printf("%d ", C[row][col]);
}
printf("\n");
}

return 0;
}
Output
Enter elements in matrix A of size 3x3:
Enter elements in matrix A of size 3x3:
1 2 3
4 5 6
7 8 9

Enter elements in matrix B of size 3x3:


9 8 7
6 5 4
3 2 1

Product of matrix A * B =
30 24 18
84 69 54
138 114 90
9. Difference Between Recursion and
Iteration
May 30, 2016 Leave a Comment

Recursion and iteration


both repeatedly executes the set of instructions. Recursion is when a
statement in a function calls itself repeatedly. The iteration is when a loop
repeatedly executes till the controlling condition becomes false. The primary
difference between recursion and iteration is that is a recursion is a process,
always applied to a function. The iteration is applied to the set of
instructions which we want to get repeatedly executed.

Content: Recursion Vs Iteration


1. Comparison Chart
2. Definition
3. Key Differences
4. Conclusion

Comparison Chart

BASIS FOR
RECURSION ITERATION
COMPARISON

Basic The statement in a body of function Allows the set of instructions to be

calls the function itself. repeatedly executed.


BASIS FOR
RECURSION ITERATION
COMPARISON

Format In recursive function, only Iteration includes initialization,

termination condition (base case) is condition, execution of statement

specified. within loop and update (increments

and decrements) the control

variable.

Termination A conditional statement is included The iteration statement is repeatedly

in the body of the function to force executed until a certain condition is

the function to return without reached.

recursion call being executed.

Condition If the function does not converge to If the control condition in the

some condition called (base case), iteration statement never become

it leads to infinite recursion. false, it leads to infinite iteration.

Infinite Repetition Infinite recursion can crash the Infinite loop uses CPU cycles

system. repeatedly.

Applied Recursion is always applied to Iteration is applied to iteration

functions. statements or "loops".


BASIS FOR
RECURSION ITERATION
COMPARISON

Stack The stack is used to store the set of Does not uses stack.

new local variables and parameters

each time the function is called.

Overhead Recursion possesses the overhead No overhead of repeated function

of repeated function calls. call.

Speed Slow in execution. Fast in execution.

Size of Code Recursion reduces the size of the Iteration makes the code longer.

code.

Definition of Recursion
C++ allows a function to call itself within its code. That means the definition
of the function possesses a function call to itself. Sometimes it is also called
“circular definition“. The set of local variables and parameters used by the
function are newly created each time the function calls itself and are stored
at the top of the stack. But, each time when a function calls itself, it does not
create a new copy of that function. The recursive function does not
significantly reduce the size of the code and does not even improve the
memory utilization, but it does some when compared to the iteration.

To terminate the recursion, you must include a select statement in the


definition of the function to force the function to return without giving a
recursive call to itself. The absence of the select statement in the definition
of a recursive function will let the function in infinite recursion once called.

Let us understand recursion with a function which will return the factorial of
the number.
1. int factorial(int num){
2. int answer;
3. if (num==1) {
4. return 1;
5. }else{
6. answer = factorial(num-1) * num; //recursive calling
7. }
8. return (answer);
9. }

In above code, the statement in else part shows the recursion, as the
statement calls the function factorial( ) in which it resides.

Definition of Iteration
Iteration is a process of executing the set of instructions repeatedly till the
condition in iteration statement becomes false. The iteration statement
includes the initialization, comparison, execution of the statements inside the
iteration statement and finally the updating of the control variable. After the
control variable is updated it is compared again, and the process repeats
itself, till the condition in iteration statement turns out to be false. The
iteration statements are “for” loop, “while” loop, “do-while” loop.

The iteration statement does not use a stack to store the variables. Hence,
the execution of the iteration statement is faster as compared to recursive
function. Even the iteration function do not have the overhead of repeated
function calling which also make its execution faster than recursive function.
The iteration is terminated when the control condition becomes false. The
absence of control condition in iteration statement may result in an infinite
loop, or it may cause a compilation error.

Let’s understand iteration regarding above example.

1. int factorial(int num){


2. int answer=1; //needs initialization because it may contain a garbage value before its initialization
3. for(int t =1; t>num; t++) //iteration
4. {
5. answer=answer * (t);
6. return (answer);
7. }

In above code, the function returns the factorial of the number using
iteration statement.

Key Differences Between Recursion and Iteration


1. Recursion is when a method in a program repeatedly calls itself
whereas, iteration is when a set of instructions in a program are
repeatedly executed.
2. A recursive method contains set of instructions, statement calling itself,
and a termination condition whereas iteration statements contain
initialization, increment, condition, set of instruction within a loop and a
control variable.
3. A conditional statement decides the termination of recursion and control
variable’s value decide the termination of the iteration statement.
4. If the method does not lead to the termination condition it enters to
infinite recursion. On the other hand, if the control variable never leads
to the termination value the iteration statement iterates infinitely.
5. Infinite recursion can lead to system crash whereas, infinite iteration
consumes CPU cycles.
6. Recursion is always applied to method whereas, iteration is applied to
set of instruction.
7. Variables created during recursion are stored on stack whereas,
iteration doesn’t require a stack.
8. Recursion causes the overhead of repeated function calling whereas,
iteration does not have a function calling overhead.
9. Due to function calling overhead execution of recursion is slower
whereas, execution of iteration is faster.
10. Recursion reduces the size of code whereas, iterations make a code
longer.
Conclusion:
The recursive function is easy to write, but they do not perform well as
compared to iteration whereas, the iteration is hard to write but their
performance is good as compared to recursion.

What is the difference between recursion and iterations


briefly?

Recursion vs Iteration

i) In recursion, function call itself until the base condition is reached.

On another hand, iteration means repetition of the process until the condition fails.
For example – when you use loop (for, while etc.) in your programs.

ii) The iterative approach involves four steps, initialization, condition, execution and
updation.

In recursive function, only base condition (terminate condition) is specified.


iii) Recursion keeps your code short and simple Whereas iterative approach makes
your code longer.

iv) Recursion is slower than iteration due to the overhead of maintaining stack
whereas iteration is faster.

v) Recursion takes more memory than iteration due to the overhead of maintaining
the stack .

vi) If recursion is not terminated (or base condition is not specified) then it creates
stack overflow (where your system runs out of memory).

vii) Any recursive problem can be solved iteratively. But you can’t solve all problems
using recursion.

Difference between Recursion and Iteration


In this tutorial you will learn about difference between recursion and iteration with
example.

Both recursion and iteration are used for executing some instructions repeatedly
until some condition is true. A same problem can be solved with recursion as well as
iteration but still there are several differences in their working and performance that
I have mentioned below.

Difference between Recursion and Iteration

Recursion Iteration

Recursion refers to a situation where Iteration refers to a situation where

a function calls itself again and again some statements are executed again

until some base condition is not and again using loops until some

Definition reached. condition is true.

It is comparatively slower because

before each function call the current


Its execution is faster because it
state of function is stored in stack.
Performance doesn’t use stack.
After the return statement the
previous function state is again

restored from stack.

Memory usage is more as stack is

used to store the current function Memory usage is less as it doesn’t use

Memory state. stack.

Size of code is comparatively smaller

Code Size in recursion. Iteration makes the code size bigger.

Lets write the implementation of finding factorial of number using recursion as well
as iteration.

Recursion Example

Below is the C program to find factorial of a number using recursion.

1 #include <stdio.h>

3 int factorial(int n){

4 if(n == 0)

5 return 1;

6 else

7 return n * factorial(n-1);

8 }
9

10 int main() {

11 printf("Factorial for 5 is %d", factorial(5));

12

13 return 0;

14 }

Iteration Example

Below is the C program to find factorial of a number using iteration.

1 #include <stdio.h>

3 int main() {

4 int i, n = 5, fac = 1;

6 for(i = 1; i <= n; ++i)

7 fac = fac * i;

9 printf("Factorial for 5 is %d", fac);

10
11 return 0;

12 }

Difference between Recursion and Iteration


Key Difference: In programming, recursion can be explained by considering a recursive
function. A recursive function is one which calls itself again to repeat the code. On
the other hand, iteration is achieved by an iterative function which loops to repeat
some section of the code.
In programming, recursion and iteration are both used to achieve repetitions. They refer to a
process that is repeated numerous times. Recursion is based on an approach in which
something refers to itself until a condition is met. A method is said to be recursive if it can
call itself either directly or indirectly like –

void name()

... name() ...

or

void name()
{

... game() ...

void game() {

... name() ...

For a successful recursion, one must keep in mind that every call made in the recursion
process must simplify the computation. Recursion is achieved by defining a base case.

int factorial (int N)

if (N == 0) return 1;

else return (N*factorial(N-1));

In this example, recursion can easily be seen in the statement (N*factorial(N-1)), where it is
calling the factorial function again. Recursion is very helpful as it helps in shortening of the
code. However, the recursion is a little slow in performance.

Iteration is based on loops.


These loops refer to explicit iteration processes. For meeting the requirement of a loop, it
must have some type of criteria that stops further iteration. However, if the loop-condition
test never becomes false, then in that condition the occurrence of an infinite loop is
inevitable. In this example, factorial is being determined by using the iteration process –

function factorial(n)

var loop, result;

result = 1;

for(loop=1;loop<=n;loop++)

{
result = result * loop;

return result;

In this example, looping is achieved by using integers from 1 to n, and loop<=n statement is
used as a criteria to stop further looping. Thus, we can conclude that the same results can be
achieved by using a recursion and iteration. However, they both are based on approaches that
are a little different. Any recursive algorithm can also be written using iterations (loops).
Comparison between Recursion and Iteration:

Recursion Iteration

Iteration is achieved by an
Recursion refers to a iterative function which
recursive function in loops to repeat some
Definition
which it calls itself again section of the code.
to repeat the code.

A base case needs to be A termination condition


Important point
determined needs to be determined

Performance Comparatively slow Comparatively fast

Memory Usage Comparatively more Comparatively less

Code Smaller Longer

Infinite recursion is
Infinite looping consumes
Infinite repetition capable of crashing the
CPU cycles repeatedly
system

Structure Selection Repetition

Local variables Not required Required


10. What is the difference between the while and
do while loop in C?
The most important difference between While and Do-While is that in Do-While,
the block of code is executed at least once.
i.e., the Do-While loop runs at least once, even though the condition
given is false

To put it in a different way :


While- your condition is at the begin of the loop block, and makes possible to never
enter the loop.
In While loop, the condition is first tested and then the block of code is executed if
the test result is true.

----------------------------------------------------------------
Do While- your condition is at the end of the loop block, and makes obligatory to
enter the loop at least one time.
In D0-While, the code is first executed and then the condition is checked. The next
iteration is executed if the test result is true.

------------------------------------------------------------------

While is Entry Controlled and Do-While is Exit Controlled.


Syntax:

1. //while
2. while(condition is true)
3. {
4. something
5. }
6.
7.
8. //do-while
9. do
10. {
11. something
12. }while(condition is true)
13.

EXAMPLE :-
[code]
do
{
scan inputs
print "do you want to continue[y/n]?"
scan choice
}while(ch == 'y')
[/code]
This is not possible in While because it is an entry controlled loop.
But you can execute the same code in While in the following way.
1234567

1. ch = 'y'
2. while(ch == 'y')
3. {
4. do something
5. print "do you want to continue[y/n]?"
6. scan choice
7. }

11. C Program To Arrange Numbers In


Descending Order
C Program To Arrange Numbers In Descending Order. If you are looking for
sort the array in descending order program in C, here in this tutorial we will help you
to learn how to write a c program to C program to arrange the given numbers in
descending order.

C Program To Arrange Numbers In Descending Order

Learn how to write a c Program to arrange array elements in descending order.


Writing descending order program in C can be done using various techniques
but here in this program, we show how to write a c program to arrange numbers in
descending order in a proper way. Happy coding.

C Program to Arrange Numbers in Descending Order Source


Code

Just copy paste the below source code to arrange numbers in descending order in C
compiler to test, how the source code works. Happy Learning.

/* C program to arrange numbers in descending order DescOrder.C */

#include <stdio.h>

void main ()
{

//variable declaration

int number[30];

int i, j, a, n;

//asking user to enter size of array

printf("Enter the value of N\n");

scanf("%d", &n); //reading array size

//asking user to enter array elements

printf("Enter the numbers \n");

for (i = 0; i < n; ++i)

scanf("%d", &number[i]); //reading array elements

/* Logic for sorting and checking */

for (i = 0; i < n; ++i)

for (j = i + 1; j < n; ++j)

if (number[i] < number[j])


{

a = number[i];

number[i] = number[j];

number[j] = a;

printf("The numbers arranged in descending order are given below\n");

for (i = 0; i < n; ++i)

printf("%d\n", number[i]); //printing numbers in descending order

C Program to Arrange Numbers in Descending Order Output

Enter the value of N

Enter the numbers

23
16

The numbers arranged in descending order are given below

23

16

C Program to Display
12.
Fibonacci Sequence
Example on how to display the Fibonacci sequence of first n numbers (entered by the
user) using loop. Also in different example, you learn to generate the Fibonacci
sequence up to a certain number.
The Fibonacci sequence is a series where the next term is the sum of pervious two
terms. The first two terms of the Fibonacci sequence is 0 followed by 1.

The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21

Example #1: Fibonacci Series up to n


number of terms
#include <stdio.h>
int main()
{
int i, n, t1 = 0, t2 = 1, nextTerm;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Fibonacci Series: ");

for (i = 1; i <= n; ++i)


{
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}

Output

Enter the number of terms: 10

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,


Example #2: Fibonacci Sequence Up to a
Certain Number
#include <stdio.h>
int main()
{
int t1 = 0, t2 = 1, nextTerm = 0, n;

printf("Enter a positive number: ");


scanf("%d", &n);

// displays the first two terms which is always 0 and 1


printf("Fibonacci Series: %d, %d, ", t1, t2);

nextTerm = t1 + t2;

while(nextTerm <= n)
{
printf("%d, ",nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}

return 0;
}

Output

Enter a positive integer: 100

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,


14. define function in c ?
A function is a group of statements that together perform a task. Every C
program has at least one function, which is main(), and all the most trivial
programs can define additional functions.

You can divide up your code into separate functions. How you divide up
your code among different functions is up to you, but logically the division
is such that each function performs a specific task.

A function declaration tells the compiler about a function's name, return


type, and parameters. A function definition provides the actual body of
the function.

The C standard library provides numerous built-in functions that your


program can call. For example, strcat() to concatenate two
strings, memcpy() to copy one memory location to another location, and
many more functions.

A function can also be referred as a method or a sub-routine or a


procedure, etc.

Defining a Function
The general form of a function definition in C programming language is as
follows −

return_type function_name( parameter list ) {

body of the function

A function definition in C programming consists of a function header and


a function body. Here are all the parts of a function −

 Return Type − A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.

 Function Name − This is the actual name of the function. The function name
and the parameter list together constitute the function signature.

 Parameters − A parameter is like a placeholder. When a function is invoked,


you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.

 Function Body − The function body contains a collection of statements that


define what the function does.

Example
Given below is the source code for a function called max(). This function
takes two parameters num1 and num2 and returns the maximum value
between the two −

/* function returning the max between two numbers */

int max(int num1, int num2) {

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

Function Declarations
A function declaration tells the compiler about a function name and how
to call the function. The actual body of the function can be defined
separately.

A function declaration has the following parts −


return_type function_name( parameter list );

For the above defined function max(), the function declaration is as follows

int max(int num1, int num2);

Parameter names are not important in function declaration only their type
is required, so the following is also a valid declaration −
int max(int, int);

Function declaration is required when you define a function in one source


file and you call that function in another file. In such case, you should
declare the function at the top of the file calling the function.

Calling a Function
While creating a C function, you give a definition of what the function has
to do. To use a function, you will have to call that function to perform the
defined task.

When a program calls a function, the program control is transferred to the


called function. A called function performs a defined task and when its
return statement is executed or when its function-ending closing brace is
reached, it returns the program control back to the main program.

To call a function, you simply need to pass the required parameters along
with the function name, and if the function returns a value, then you can
store the returned value. For example −
Live Demo

#include <stdio.h>

/* function declaration */

int max(int num1, int num2);

int main () {

/* local variable definition */

int a = 100;

int b = 200;

int ret;
/* calling a function to get max value */

ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;

/* function returning the max between two numbers */

int max(int num1, int num2) {

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

We have kept max() along with main() and compiled the source code.
While running the final executable, it would produce the following result −
Max value is : 200

Function Arguments
If a function is to use arguments, it must declare variables that accept the
values of the arguments. These variables are called the formal
parameters of the function.

Formal parameters behave like other local variables inside the function and
are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be
passed to a function −

Sr.No. Call Type & Description

1 Call by value

This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.

2 Call by reference

This method copies the address of an argument into the formal parameter.
Inside the function, the address is used to access the actual argument
used in the call. This means that changes made to the parameter affect
the argument.

By default, C uses call by value to pass arguments. In general, it means


the code within a function cannot alter the arguments used to call the
function.

15. difference between function prototype and


function call ?
What is the purpose of a function prototype?
In computer programming, a function prototype or function interface is a
declaration of a function that specifies the function's name and type signature
(arity, data types of parameters, and return type), but omits the function body.

What is the function call?


A function call is an expression that passes control and arguments (if any) to a
function and has the form: expression (expression-listopt) where expression is a
function name or evaluates to a function address and expression-list is a list of
expressions (separated by commas).
16. Difference Between Function Prototype and Function
Definition in C
Key Difference – Function Prototype vs Function Definition in C

A function is a group of statements used to perform a specific task. In C programming, the


execution starts from main (). It is a function. Rather than writing all statements in the
same program, it can be divided into multiple functions. Each function will perform different
functionalities. The function prototype tells the compiler about the function name, return
types and parameters. It is also known as a function declaration. Each function has a
particular name to identify it. The function statements are written inside a pair of curly
braces. The functions can return a value. There are some functions that do not return a
value. The data is passed to the function using the parameter list. The function definition
has the actual functionality performed by the function. In C programming, there is function
prototype and function definition. The key difference between the function prototype and
function definition is that the function prototype only contains the declaration of the
function while the function definition contains the actual implementation of the
function. The function definition has the local variablesand the statements that determine
what the function does.

CONTENTS
1. Overview and Key Difference
2. What is Function Prototype in C
3. What is Function Definition in C
4. Similarities Between Function Prototype and Function Definition in C
5. Side by Side Comparison – Function Prototype vs Function Definition in C in Tabular
Form
6. Summary

What is Function Prototype in C?

Function Prototype provides the function declaration. It specifies the name of the function,
the return types, the parameters. The return types are the data type that returns from the
function. When a function is returning an integer, then the return type is int. When a
function is returning a float value, then the return type is a float. If the function is not
returning any value, it is a void function. The function name is used to identify it. C
keywords cannot be used as function names. The data is passed to the function using
parameters. The function prototype does not contain the real implementation of the
function. The function prototype has the following syntax.

<return type> <function name> (parameter list);

If there is a function to calculate the maximum of two numbers the declaration can be
written as int max (int num1, int num2); The maximum value should be found in num1 and
num2. Those are integers, and they are passed to the function. The return type, in the
beginning, is also int. So, the function returns an integer value. It t is not necessary to write
the parameter names in the function prototype. But it is necessary to write the data types.
Therefore, int max (int, int); is also a valid function prototype. If there are two integers as
num1, num2, num3 and the prototype is written as int max(int num1, int num2, num3); it
is invalid. The num1, num2 have the data types, but num3 does not have a data type.
Therefore, it is invalid.

Refer the below program.

#include <stdio.h>

int CarMax(int x, int y);

int main(){

int p =10;

int q= 20;
int answer;

answer = calMax(p,q);

printf(“The maximum value is %d\n”, answer);

return 0;

int calMax(int p, int q){

int value;

if(p>q) {

value = p;

else {

value = q;

return value;

According to the above, the second statement shows the function prototype. It does not
have the implementation. The actual implementation is after the main program. The
function prototypes are more useful when defining a function in one source file and call
that function in another in another file.

What is Function Definition in C?

The function definition has the actual implementation of the function. It contains what the
function should do. When the program calls the function, the control is transferred to the
called function. After the execution of the function, the control returns back to the main
function. The required data is passed to the function as a parameter list. If there is a value
returning, then the return type is mentioned. If there are no returning values, the return
type is void. Refer the below function to calculate the area of a triangle.

#include <stdio.h>
float calArea(int x, int y);

int main () {

int p =10;

int q= 20;

flaot area;

area = calArea(p,q);

printf (“The maximum value is %f\n”, area);

return 0;

float calArea (int x, int y) {

float value;

value = 0.5 * x * y;

return value;

According to the above program, the second statement indicates the function prototype.
The actual implementation of what the function performs is written after the main program.
It is the function definition. The p and q values are passed to the calArea function. The
variable value is a local variable to the calArea function. The area is calculated and
assigned to the variable value. Then it is returned back to the main program.

What are the Similarities Between Function Prototype and Function Definition
in C?

 Both function prototype and function definition are related to functions.


 Both function prototype and function definition contain function name.
 Both function prototype and function definition contain return types.
 Both function prototype and function definition contain parameters.
What is the Difference Between Function Prototype and Function Definition in
C?

Function Prototype vs Function Definition in C


The function prototype specifies the function name, The function definition specifies the function nam
return type, parameters but omits the function body. return type; parameters include a function body.

Implementation

The function prototype does not have the function The function definition has the function
implementation. implementation.

Summary – Function Prototype vs Function Definition in C

Using functions in programs has advantages. Functions increase code reusability. It is not
necessary to write the same code again and again. Instead, the programmer can divide
the program and call the necessary function. In C there are library functions. These
functions are declared in the C header files. Some of them are printf (), scanf () etc. The
programmer can also write their own functions. There are two terms which are associated
with functions in C. They function prototype and function definition. The difference
between the function prototype and function definition in C is that the function prototype
only contains the declaration of the function while the function definition contains the actual
implementation of the function.

17. C program to swap two numbers


C program to swap two numbers with and without using third variable,
using pointers, functions (Call by reference) and using
bitwise XOR operator. Swapping means interchanging. For example, if in
your C program you have taken two variables a and b where a = 4 and b
= 5, then before swapping a = 4, b = 5 after swapping a = 5, b = 4. In the
first C program to swap numbers we will use a temporary variable to
swap two numbers.

Swapping of two numbers in C


#include <stdio.h>

int main()
{
int x, y, temp;
printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);

printf("Before Swapping\nx = %d\ny =


%d\n",x,y);

temp = x;
x = y;
y = temp;

printf("After Swapping\nx = %d\ny =


%d\n",x,y);

return 0;
}

Download Swap numbers program.

Output of program:

Swap function in C language


In this method we will make a function to swap numbers. We will use
call by reference.

#include <stdio.h>
void swap(int*, int*); //Swap function
declaration

int main()
{
int x, y;

printf("Enter the value of x and y\n");


scanf("%d%d",&x,&y);

printf("Before Swapping\nx = %d\ny = %d\n",


x, y);

swap(&x, &y);

printf("After Swapping\nx = %d\ny = %d\n", x,


y);

return 0;
}
//Swap function definition
void swap(int *a, int *b)
{
int t;

t = *b;
*b = *a;
*a = t;
}

Swapping of two numbers without third


variable
You can also swap two numbers without using temp or temporary or
third variable. In that case C program will be as shown :-

#include <stdio.h>

int main()
{
int a, b;

printf("Input two integers (a & b) to


swap\n");
scanf("%d%d", &a, &b);

a = a + b;
b = a - b;
a = a - b;

printf("a = %d\nb = %d\n",a,b);


return 0;
}

To understand the logic choose the variables 'a' and 'b' as '7' and '9'
respectively and then do what is being done by the program. You can
choose any other combination of numbers as well. Sometimes it's an
excellent way to understand a program.
Swap two numbers using pointers
#include <stdio.h>

int main()
{
int x, y, *a, *b, temp;

printf("Enter the value of x and y\n");


scanf("%d%d", &x, &y);

printf("Before Swapping\nx = %d\ny = %d\n",


x, y);

a = &x;
b = &y;

temp = *b;
*b = *a;
*a = temp;

printf("After Swapping\nx = %d\ny = %d\n", x,


y);

return 0;
}

C programming code to swap using bitwise


XOR
#include <stdio.h>

int main()
{
int x, y;

scanf("%d%d", &x, &y);

printf("x = %d\ny = %d\n", x, y);

x = x ^ y;
y = x ^ y;
x = x ^ y;

printf("x = %d\ny = %d\n", x, y);

return 0;
}

Swapping is used in sorting algorithms that is when we wish to arrange


numbers in a particular order either in ascending order or in descending
order.

Swapping numbers using call by


reference in C
1. Forget Code
2. C

3. Swapping numbers using call by reference

1. #include <stdio.h>
2.
3. void swap(int*, int*);
4.
5. int main()
6. {
7. int x, y;
8.
9. printf("Enter the value of x and y\n");
10. scanf("%d%d",&x,&y);
11.
12. printf("Before Swapping\nx = %d\ny = %d\n", x, y);
13.
14. swap(&x, &y);
15.
16. printf("After Swapping\nx = %d\ny = %d\n", x, y);
17.
18. return 0;
19. }
20.
21. void swap(int *a, int *b)
22. {
23. int temp;
24.
25. temp = *b;
26. *b = *a;
27. *a = temp;
28. }
29.

Swapping numbers using Call by


Value in C
1. Forget Code

2. C
3. Swapping numbers using Call by Value

1. //Call by Value Example - Swapping 2 numbers using Call by Value


2. #include <stdio.h>
3.
4.
5. void swap(int, int);
6.
7. int main()
8. {
9. int x, y;
10.
11. printf("Enter the value of x and y\n");
12. scanf("%d%d",&x,&y);
13.
14. printf("Before Swapping\nx = %d\ny = %d\n", x, y);
15.
16. swap(x, y);
17.
18. printf("After Swapping\nx = %d\ny = %d\n", x, y);
19.
20. return 0;
21. }
22.
23. void swap(int a, int b)
24. {
25. int temp;
26.
27. temp = b;
28. b = a;
29. a = temp;
30. printf("Values of a and b is %d %d\n",a,b);
31. }
32.

Output:

Enter the value of x and y

Before Swapping
Output:

x = 10

y=5

Values of a and b is 5 10

After Swapping

x = 10

y=5

18. What is preprocessor in c?


When we write a C program , we will use some of the header files and macros.

Like stdio.h , string.h etc.

Example :
1. #include<stdio.h>
2. #define size 5
3. int main()
4. {
5. int i;
6. for(i=0;i<size;i++)
7. printf(“Hello”);
8. }
Above program will print “Hello” five time.

But compiler won’t understand where printf actually defined and what is size.

So we need some one to process the code and replace header files and macros before
sending it to compiler which is named preprocessor .

Anything starts with # will be preprocessed before sending it to compiler.

“ A software program which process the c file and replace some of the things (header
file , macros etc) before sending the code to compiler called Preprocessor ”

So preprocessor convert the above file to something like this,


1. /*
2. Actual implementation of stdio.h will be placed here by preprocessor that
includes original implementation all IO functions say printf,scanf etc.
3. */
4. int main()
5. {
6. int i;
7. for(i=0;i<5;i++) // here size will be replaced by 5
8. printf(“Hello”);
9. }
This code will send to compiler for further actions.

Preprocessor
A software program that processes the source file before sending it to
actual compilation is called preprocessor.
Pictorial Explanation

While Processing the source file, the preprocessor replaces header files
and macros with defined files and values.
The line which starts with '#' will be processed before the actual
compilation starts.
Preprocessor Tasks

Source file inclusion


#include<stdio.h> will be replaced by the original implementation of
stdio.h file. Basically, it will remove the #include statement from source
code and includes stdio.h file content into the source program.

Macro expansion
#define size 5. Here size is a macro which holds the value 5. Before the
compilation starts, the preprocessor will replace size by 5 all over the
program.

Conditional compilation
With the help of preprocessor, we can decide which part of the source
code should compile and which part of the code should be ignored while
compilation. We will discuss conditional compilation in upcoming topics.
Source File - Before Preprocessing
Example

#include<stdio.h>
#define size 5

int main()
{
int i = 0;

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


printf("Hello");

return 0;
}

After Preprocessing
Example

/* origianl code of stdio.h */ //replaced by preprocessor

int main()
{
int i = 0;

for(i = 0; i < 5; i++) //size will be replaced by 5


printf("Hello");

return 0;
}

This preprocessed code will be sent to the compiler for further actions.

19. What are the functions of preprocessor


directives in C?
Use of the preprocessor is advantageous since it makes:
 programs easier to develop,
 easier to read,
 easier to modify
 C code more transportable between different machine architectures.

The C preprocessor modifies a source file before handing it over to the compiler, allowing
conditional compilation with #ifdef, defining constants with#define, including header files
with #include, and using builtin macros such as __FILE__. Here is lists of the preprocessor
directives, or commands to the preprocessor, that are available:

 #include
 #define
 #undef
 #if
 #ifdef
 #ifndef
 #error
 __FILE__
 __LINE__
 __DATE__
 __TIME__
 __TIMESTAMP__
 pragma
 # macro operator
 ## macro operator

20. write a c program that finds n! using the concept of


recursion

C Program to Find Factorial of a


Number Using Recursion
Example to find factorial of a non-negative integer (entered by the user) using
recursion.
To understand this example, you should have the knowledge of following C
programming topics:

 C Programming Functions
 C Programming User-defined functions
 C Programming Recursion

The factorial of a positive number n is given by:

factorial of n (n!) = 1*2*3*4....n

The factorial of a negative number doesn't exist. And the factorial of 0 is 1.

You will learn to find the factorial of a number using recursion in this example. Visit
this page to learn, how you can find the factorial of a number using loop.

Example: Factorial of a Number Using


Recursion
#include <stdio.h>
long int multiplyNumbers(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}

Output

Enter a positive integer: 6

Factorial of 6 = 720

Suppose the user entered 6.

Initially, the multiplyNumbers() is called from the main() function with 6 passed as an
argument.

Then, 5 is passed to the multiplyNumbers() function from the same function


(recursive call). In each recursive call, the value of argument n is decreased by 1.

When the value of n is less than 1, there is no recursive call.

21. notes : binary coded decimal system


0 = 0000
1 = 0001
2 = 00103 = 0011
4 = 0100
5 = 0101
6 = 0110
7 = 0111
8 = 1000
9 = 1001

Numbers larger than 9, having two or more digits in the decimal system,
are expressed digit by digit. For example, the BCD rendition of the base-10
number 1895 is

0001 1000 1001 0101

The binary equivalents of 1, 8, 9, and 5, always in a four-digit format, go


from left to right.

The BCD representation of a number is not the same, in general, as its


simple binary representation. In binary form, for example, the decimal
quantity 1895 appears as

11101100111

Other bit patterns are sometimes used in BCD format to represent special
characters relevant to a particular system, such as sign (positive or
negative), error condition, or overflow condition.

The BCD system offers relative ease of conversion between machine-


readable and human-readable numerals. As compared to the simple binary
system, however, BCD increases the circuit complexity. The BCD system is
not as widely used today as it was a few decades ago, although some
systems still employ BCD in financial applications.
uninterruptible power supply
22.
(UPS)
An uninterruptible power supply (UPS) is a device that allows a computer to
keep running for at least a short time when the primary power source is
lost. It also provides protection from power surges.
DEFINITION

uninterruptible power supply


(UPS)

Posted by: Margaret Rouse

WhatIs.com

Follow:

Contributor(s): Robert McFarlane, Toon Diegenant and Patrick Tierce






An uninterruptible power supply (UPS) is a device that allows a computer to


keep running for at least a short time when the primary power source is
lost. It also provides protection from power surges.

DOWNLOAD THIS FREE GUIDE


Experts agree: 5% load differential is key

But is that what you see in your


organization’s power balance? Does another
setup work better for you? Learn why our
experts say the goal for data center power
distribution is no more than a 5% load
differential among phases.
 Corporate E-mail Address:

o I agree to TechTarget’s Terms of Use, Privacy Policy, and the transfer


of my information to the United States for processing to provide me with
relevant information as described in our Privacy Policy.

o I agree to my information being processed by TechTarget and


its Partners to contact me via phone, email, or other means regarding
information relevant to my professional interests. I may unsubscribe at any
time.
Dow nload Now

A UPS contains a battery that "kicks in" when the device senses a loss of
power from the primary source. If you are using the computer when the
UPS notifies you of the power loss, you have time to save any data you are
working on and exit gracefully before the secondary power source (the
battery) runs out. When all power runs out, any data in your computer's
random access memory (RAM) is erased. When power surges occur, a
UPS intercepts the surge so that it doesn't damage the computer.

UPS in the data center

Every UPS converts incoming AC to DC through a rectifier, and converts it


back with an inverter. Batteries or flywheels store energy to use in a utility
failure. A bypass circuit routes power around the rectifier and inverter,
running the IT load on incoming utility or generator power.

While UPS systems are commonly called double-conversion, line-


interactive and standby designs, these terms have been used
inconsistently and manufacturers implement them differently: At least one
system allows any of the three modes. The International ElectroTechnical
Commission (IEC) adopted more technically descriptive terminology in IEC
Std. 62040.

Voltage and frequency independent (VFI) UPS systems are called dual
or double conversion because incoming AC is rectified to DC to keep
batteries charged and drive the inverter. The inverter re-creates steady AC
power to run the IT equipment.
Figure 1.

When power fails the batteries drive the inverter, which continues to run the
information technology (IT) load. When power is restored, either from the
utility or a generator, the rectifier delivers direct current (DC) to the inverter
and simultaneously recharges the batteries. The inverter runs full time.
Utility input is completely isolated from the output, and bypass is only used
for maintenance safety or if there's an internal electronics failure. Since
there is no break in the power delivered to the IT equipment, vacuum fault
interrupter (VFI) is generally considered the most robust form of UPS. Most
systems synchronize the output frequency with the input, but that's not
necessary, so it still qualifies as frequency independent.
Figure 2.

Every power conversion incurs a loss, so the wasted energy has historically
been considered the price of ultimate reliability. The newest VFI systems
claim better than 96% efficiency at nearly all loads.

Voltage independent (VI), or true line interactive UPSes have a controlled


output voltage, but the same output frequency as the input. Frequency
independence is rarely a concern with power in developed countries. Utility
power feeds directly to the output and IT equipment, and the rectifier keeps
the batteries charged. The inverter is paralleled with the output,
compensating for voltage dips and acting as an active filter for voltage
spikes and harmonics. Rectifier and inverter losses only occur when
incoming power fluctuates. Flywheels and motor/generator sets also qualify
as VI.
Figure 3.

When incoming power fails, or the voltage goes out of range, the bypass
quickly disconnects from the input and the battery drives the inverter. When
input power is restored, the bypass re-engages the input, re-charges the
batteries, and keeps output voltage constant. UPS vendors who use
paralleled power sources claim no loss of reliability. The result is around
98% energy efficiency.
Figure 4.

Voltage and frequency dependent (VFD), or standby UPS, is


operationally similar to VI and is sometimes mistakenly called line
interactive. In conventional VFD systems the inverter is turned off, so it can
take as long as 10 to 12 milliseconds (ms) to start creating power. That
break can crash servers, making legacy VFD UPSes a bad fit for data
centers.
Figure 5.

New VFD concepts have the inverter producing power within 2 ms after
being activated. The bypass is normally engaged, just as with VI, so
equipment operates directly from the utility or generator. Since the inverter
isn't working until power fails, there is no voltage control or power
consumed, enabling efficiencies as high as 99%. Power failure or voltage
outside of range opens the bypass switch, disengaging input from output;
the inverter starts operating from the batteries. The rectifier is only large
enough to keep the batteries charged.
UPS - Uninterruptible Power Supply
By Steven McFadyen on August 21st, 2013

Liebert NX Power UPS


Image Source: Emerson Network Power
A UPS is an uninterruptible power supply. It is a device which maintains a continuous supply of
electrical power, even in the event of failure of the mains (utility) supply. A UPS is installed between
the mains supply and the equipment to be protected.

UPS are used to safeguard various types of equipment. One of the common uses is computers,
particularly in data centres and the critical equipment of large organizations.

Contents [hide]

1. How a UPS Works


2. UPS Configurations
1. Standby UPS
2. On-line (Double Conversion) UPS
3. Other UPS Configurations
4. Configuration Comparison
3. See Also

How a UPS Works


A UPS works by converting the mains alternating current (a.c.) supply to a direct current (d.c.)
voltage. The part of the UPS which does this is called the rectifier. Output from the rectifier is then
used to charge batteries, which can supply power during a mains failure. The d.c. voltage from the
rectifier (or batteries during mains failure) is the converted back to a.c. by the UPS inverter and
supplies power to the equipment.

Note: the above UPS description is that of a static (electronic) UPS. While this is the most common type of
UPS, there are other technologies, for example, rotary UPS and the use of flywheels to store the energy.
In addition to protecting equipment in the event of mains failure, because the first convert the a.c. to
d.c, a UPS has the added benefit of being able to solve other problems related to power supply
quality. These include voltage dips, harmonics, frequency variations, etc. For more information, you
can see the note 9 power supply issues solved by using a UPS.

Operating principle of a UPS


UPS units and systems come in various sizes, from 1 or 2 kVA all they way to the MVA range. On of
the problems and limiting factors with how large a UPS can be is the amount of batteries
required. These can become substantial, costing a lot and taking up significant amounts of
space. For smaller UPS the batteries are normally internal to the device, while for larger systems the
batteries are mounted externally on racks or in cabinets.

Another element to batteries is the discharge time. Any battery backed UPS will only be rated for a
certain period (5 minutes, 15 minutes, 30 minutes, etc.). For this reason, most UPS applications are
centred around providing sufficient power for a limited time to enable any necessary actions - safely
shut down the equipment, change over to generator power, etc.

To ensure functioning, operational safety and Electromagnetic Compatibility (EMC) requirements are
achieved, UPS are manufactured to recognized standards, the most important of which is:

 IEC 62040 - Uninterruptible power systems (UPS)

UPS Configurations
The arrangement of rectifier, inverter, battery and other components can be carried out in different
ways. Each arrangement has advantages and disadvantages. Normally the more robust the
configuration, the more expensive the UPS.

UPS are classified in two basic ways - standby and on-line.

In a standby UPS, power is normally supplied directly from the mains and the inverter only switched in
if the mains fails. This can have the advantages of cheaper cost and higher efficiencies. On-line UPS
always supply the load via the inverter. These are more expensive, but because the inverter is
always used they can resolve many power quality issues.

Standby UPS
In a standby UPS, the static (electronic) transfer switch supplies the load directly with mains
power. In the event of power failure, the static transfer switch immediately changes over to power
from the inverter.

Static transfer switches when switching from mains to inverter power, will typically do this in less than
5 mS. The battery is always kept at full charge by the rectifier and immediately available for supplying
power. Often a filter provides some power conditioning when supply mains power to the load. A
surge arrestor protects the UPS and loads from over voltage conditions.

On-line (Double Conversion) UPS


In on-line mode, the load is always supplied via the inverter. The inverter normally takes it's input
from the mains, but will switch to the battery when the mains supply goes out of tolerance. The static
bypass will supply power directly from the mains in the event the inverter is turned off or develops a
fault.

A big advantage of on-line UPS is that the load is always supplied by the inverter and many power
quality issues on the mains are eliminated. For more information, you can see the 9 power supply issues
solved by using a UPS note.

Other UPS Configurations


In addition to pure standby and on-line systems (illustrated above), UPS are available in various other
arrangements.

Ferro-resonant [standby] - the load is supplied by a three winding transformer, with the mains on one input
winding and the inverter on the other. The transformer provides some level of Ferro-resonant power
conditioning and voltage regulation. During a mains failure, the switching from mains to inverter power is by a
static transfer switch.
Line Interactive [on-line] - in this configuration, the load is always supplied by the inverter. There is no
rectifier and the batteries are charged by running the inverter in reverse when the main power is normal. A
transfer switch changes the input of the inverter from main to battery on mains failure.
Delta Conversion [on-line] - is a relatively new and patented technology. This technology use converters cable
of both rectification and inverting, together with a delta transformer to supply the load. Some of the mains
power is directly used to supplement the load inverter output to create a better inverter efficiency.

Configuration Comparison

Standby On-Line

Standby Ferro- Double Line Interactive Delta


Resonant Conversion Conversion

Efficiency Very High Medium Medium Very High High

Cost Low High Medium Medium Medium


Mains Low High High Medium High
Conditioning

Typical Power 0.0-0.5 kVA 3-15 kVA 5-5000 kVA 0.5-5.0 kVA 5-5000 kVA

Typical Personal Limited Data Centres, Data Centres, Servers,


Application Computers Application Critical Facilities Critical Facilities Computer
Racks

23. The UNIX operating system

UNIX Introduction
What is UNIX?

UNIX is an operating system which was first developed in


the 1960s, and has been under constant development ever
since. By operating system, we mean the suite of programs
which make the computer work. It is a stable, multi-user,
multi-tasking system for servers, desktops and laptops.

UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windows
which provides an easy to use environment. However, knowledge of UNIX is required for
operations which aren't covered by a graphical program, or for when there is no windows
interface available, for example, in a telnet session.

Types of UNIX

There are many different versions of UNIX, although they share common
similarities. The most popular varieties of UNIX are Sun Solaris, GNU/Linux,
and MacOS X.

Here in the School, we use Solaris on our servers and workstations, and
Fedora Linux on the servers and desktop PCs.

The UNIX operating system

The UNIX operating system is made up of three parts; the kernel, the shell and the
programs.
The kernel

The kernel of UNIX is the hub of the operating system: it allocates time and memory to
programs and handles the filestore and communications in response to system calls.

As an illustration of the way that the shell and the kernel work together, suppose a user
types rm myfile (which has the effect of removing the file myfile). The shell searches
the filestore for the file containing the program rm, and then requests the kernel,
through system calls, to execute the program rm on myfile. When the process rm
myfile has finished running, the shell then returns the UNIX prompt % to the user,
indicating that it is waiting for further commands.

The shell

The shell acts as an interface between the user and the kernel. When a user logs in, the
login program checks the username and password, and then starts another program
called the shell. The shell is a command line interpreter (CLI). It interprets the
commands the user types in and arranges for them to be carried out. The commands are
themselves programs: when they terminate, the shell gives the user another prompt (%
on our systems).

The adept user can customise his/her own shell, and users can use different shells on
the same machine. Staff and students in the school have the tcsh shell by default.

The tcsh shell has certain features to help the user inputting commands.

Filename Completion - By typing part of the name of a command, filename or directory


and pressing the [Tab] key, the tcsh shell will complete the rest of the name
automatically. If the shell finds more than one name beginning with those letters you
have typed, it will beep, prompting you to type a few more letters before pressing the
tab key again.

History - The shell keeps a list of the commands you have typed in. If you need to
repeat a command, use the cursor keys to scroll up and down the list or type history for
a list of previous commands.

Files and processes

Everything in UNIX is either a file or a process.

A process is an executing program identified by a unique PID (process identifier).


A file is a collection of data. They are created by users using text editors, running
compilers etc.

Examples of files:

 a document (report, essay etc.)


 the text of a program written in some high-level programming language
 instructions comprehensible directly to the machine and incomprehensible to a
casual user, for example, a collection of binary digits (an executable or binary
file);
 a directory, containing information about its contents, which may be a mixture of
other directories (subdirectories) and ordinary files.

The Directory Structure

All the files are grouped together in the directory structure. The file-system is arranged
in a hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally
called root (written as a slash / )

In the diagram above, we see that the home directory of the undergraduate
student "ee51vn" contains two sub-directories (docs and pics) and a file
called report.doc.

The full path to the file report.doc is "/home/its/ug1/ee51vn/report.doc"

Starting an UNIX terminal


To open an UNIX terminal window, click on the "Terminal" icon from
Applications/Accessories menus.

An UNIX Terminal window will then appear with a % prompt, waiting for you to start
entering commands.

UNIX
By Vangie Beal

Related Terms
 C
 operating system - OS
 UUCP - Unix-to-Unix Copy
 z/OS
 OS/400
 cloud OS
 Linux OS (Operating System)
 Chromium OS
 Firefox OS
 OS/2

(Pronounced yoo-niks) UNIX is a popular multi-user, multitaskingoperating system (OS) developed at Bell Labs in

the early 1970s. Created by just a handful of programmers, UNIX was designed to be a small, flexible system

used exclusively by programmers.

Due to its portability, flexibility, and power, UNIX has become a leading operating system for workstations.

Historically, it has been less popular in the personal computer market.

UNIX History
UNIX was one of the first operating systems to be written in a high-level programming language, namely C. This

meant that it could be installed on virtually any computer for which a C compiler existed. This natural portability

combined with its low price made it a popular choice among universities. It was inexpensive because antitrust

regulations prohibited Bell Labs from marketing it as a full-scale product.

Bell Labs distributed the operating system in its source language form, so anyone who obtained a copy could

modify and customize it for his own purposes. By the end of the 1970s, dozens of different versions of UNIX were

running at various sites. After its breakup in 1982, AT&T began to market UNIX in earnest. It also began the long

and difficult process of defining a standard version of UNIX.

The UNIX Standard, Trademark


Today, the trademarked "UNIX" and the "Single UNIX Specification" interface are owned by The Open Group. An

operating system that is certified by The Open Group to use the UNIX trademark conforms to the Single UNIX

Specification. The latest version of the certification standard is UNIX V7, aligned with the Single UNIX

Specification Version 4, 2013 Edition.

According to The Open Group's Web site, "As the owner of the UNIX trademark, The Open Group has separated

the UNIX trademark from any actual code stream itself, thus allowing multiple implementations. Since the

introduction of the Single UNIX Specification, there has been a single, open, consensus specification that defines

the requirements for a conformant UNIX system. There is also a mark, or brand, that is used to identify those

products that have been certified as conforming to the Single UNIX Specification, initially UNIX 93, followed

subsequently by UNIX 95, UNIX 98 and now UNIX 03. Both the specification and the UNIX trade mark are

managed and held in trust for the industry by The Open Group."

Basic UNIX Commands


Examples of the basic UNIX commands include the following:
 ls (Lists files)
 ls -l (Lists files in long format)
 cd name (Change directory)
 cd .. (Go to directory above current)
 cp filename1 filename2 (Copies a file)
 chmod options filename (Change the read, write, and execute permissions on your files)
 mkdir name (Creates a directory)

Note: Not all commands are part of UNIX itself and may not work on all UNIX machines. This page lists more

UNIX commands and sources of information.

Unix / Linux - Getting Started


Advertisements

Previous Page
Next Page

What is Unix ?
The Unix operating system is a set of programs that act as a link between
the computer and the user.

The computer programs that allocate the system resources and coordinate
all the details of the computer's internals is called the operating
system or the kernel.

Users communicate with the kernel through a program known as


the shell. The shell is a command line interpreter; it translates commands
entered by the user and converts them into a language that is understood
by the kernel.

 Unix was originally developed in 1969 by a group of AT&T employees Ken


Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna at Bell Labs.

 There are various Unix variants available in the market. Solaris Unix, AIX, HP
Unix and BSD are a few examples. Linux is also a flavor of Unix which is freely
available.

 Several people can use a Unix computer at the same time; hence Unix is called
a multiuser system.

 A user can also run multiple programs at the same time; hence Unix is a
multitasking environment.

Unix Architecture
Here is a basic block diagram of a Unix system −

The main concept that unites all the versions of Unix is the following four
basics −

 Kernel − The kernel is the heart of the operating system. It interacts with the
hardware and most of the tasks like memory management, task scheduling
and file management.

 Shell − The shell is the utility that processes your requests. When you type in
a command at your terminal, the shell interprets the command and calls the
program that you want. The shell uses standard syntax for all commands. C
Shell, Bourne Shell and Korn Shell are the most famous shells which are
available with most of the Unix variants.

 Commands and Utilities − There are various commands and utilities which
you can make use of in your day to day activities. cp, mv, cat and grep, etc.
are few examples of commands and utilities. There are over 250 standard
commands plus numerous others provided through 3rd party software. All the
commands come along with various options.

 Files and Directories − All the data of Unix is organized into files. All files
are then organized into directories. These directories are further organized
into a tree-like structure called the filesystem.
System Bootup
If you have a computer which has the Unix operating system installed in
it, then you simply need to turn on the system to make it live.

As soon as you turn on the system, it starts booting up and finally it


prompts you to log into the system, which is an activity to log into the
system and use it for your day-to-day activities.

Login Unix
When you first connect to a Unix system, you usually see a prompt such
as the following −
login:

To log in
 Have your userid (user identification) and password ready. Contact your
system administrator if you don't have these yet.

 Type your userid at the login prompt, then press ENTER. Your userid is case-
sensitive, so be sure you type it exactly as your system administrator has
instructed.

 Type your password at the password prompt, then press ENTER. Your
password is also case-sensitive.

 If you provide the correct userid and password, then you will be allowed to
enter into the system. Read the information and messages that comes up on
the screen, which is as follows.

login : amrood
amrood's password:
Last login: Sun Jun 14 09:32:32 2009 from 62.61.164.73
$

You will be provided with a command prompt (sometime called


the $ prompt ) where you type all your commands. For example, to check
calendar, you need to type the cal command as follows −
$ cal
June 2009
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

Change Password
All Unix systems require passwords to help ensure that your files and data
remain your own and that the system itself is secure from hackers and
crackers. Following are the steps to change your password −

Step 1 − To start, type password at the command prompt as shown


below.

Step 2 − Enter your old password, the one you're currently using.

Step 3 − Type in your new password. Always keep your password complex
enough so that nobody can guess it. But make sure, you remember it.

Step 4 − You must verify the password by typing it again.


$ passwd
Changing password for amrood
(current) Unix password:******
New UNIX password:*******
Retype new UNIX password:*******
passwd: all authentication tokens updated successfully

Note − We have added asterisk (*) here just to show the location where
you need to enter the current and new passwords otherwise at your
system. It does not show you any character when you type.

Listing Directories and Files


All data in Unix is organized into files. All files are organized into
directories. These directories are organized into a tree-like structure called
the filesystem.

You can use the ls command to list out all the files or directories available
in a directory. Following is the example of using ls command with -
l option.
$ ls -l
total 19621
drwxrwxr-x 2 amrood amrood 4096 Dec 25 09:59 uml
-rw-rw-r-- 1 amrood amrood 5341 Dec 25 08:38 uml.jpg
drwxr-xr-x 2 amrood amrood 4096 Feb 15 2006 univ
drwxr-xr-x 2 root root 4096 Dec 9 2007 urlspedia
-rw-r--r-- 1 root root 276480 Dec 9 2007 urlspedia.tar
drwxr-xr-x 8 root root 4096 Nov 25 2007 usr
-rwxr-xr-x 1 root root 3192 Nov 25 2007 webthumb.php
-rw-rw-r-- 1 amrood amrood 20480 Nov 25 2007 webthumb.tar
-rw-rw-r-- 1 amrood amrood 5654 Aug 9 2007 yourfile.mid
-rw-rw-r-- 1 amrood amrood 166255 Aug 9 2007 yourfile.swf

Here entries starting with d..... represent directories. For example, uml,
univ and urlspedia are directories and rest of the entries are files.
Who Are You?
While you're logged into the system, you might be willing to know : Who
am I?

The easiest way to find out "who you are" is to enter


the whoami command −
$ whoami
amrood

Try it on your system. This command lists the account name associated
with the current login. You can try who am i command as well to get
information about yourself.

Who is Logged in?


Sometime you might be interested to know who is logged in to the
computer at the same time.

There are three commands available to get you this information, based on
how much you wish to know about the other users: users, who, and w.
$ users
amrood bablu qadir

$ who
amrood ttyp0 Oct 8 14:10 (limbo)
bablu ttyp2 Oct 4 09:08 (calliope)
qadir ttyp4 Oct 8 12:09 (dent)

Try the w command on your system to check the output. This lists down
information associated with the users logged in the system.

Logging Out
When you finish your session, you need to log out of the system. This is
to ensure that nobody else accesses your files.

To log out

 Just type the logout command at the command prompt, and the system will
clean up everything and break the connection.

System Shutdown
The most consistent way to shut down a Unix system properly via the
command line is to use one of the following commands −
Sr.No. Command & Description

1 halt

Brings the system down immediately

2 init 0

Powers off the system using predefined scripts to synchronize and clean
up the system prior to shutting down

3 init 6

Reboots the system by shutting it down completely and then restarting it

4 poweroff

Shuts down the system by powering off

5 reboot

Reboots the system

6 shutdown

Shuts down the system

You typically need to be the super user or root (the most privileged account
on a Unix system) to shut down the system. However, on some standalone
or personally-owned Unix boxes, an administrative user and sometimes
regular users can do so.

The UNIX brand has traditionally been applied to the family of multitasking, multiuser computer
operating systems that derive from the original AT&T UNIX operating system, developed in the
1970s at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and others --
[Source:Wikipedia link]

Today, The Open Group holds the definition of what a UNIX system is and its associated trademark
in trust for the industry. The latest version can be read online [link].

In 1994 Novell (who had acquired the UNIX systems business of AT&T/USL) decided to get out of
that business. Rather than sell the business as a single entity, Novell transferred the rights to the
UNIX trademark and the specification (that subsequently became the Single UNIX Specification) to
The Open Group (at the time X/Open Company). Subsequently, it sold the source code and the
product implementation (UNIXWARE) to SCO. The Open Group also owns the trademark
UNIXWARE.

Today, the definition of UNIX ® takes the form of the worldwide Single UNIX Specification
integrating X/Open Company's XPG4, IEEE's POSIX Standards and ISO C. Through continual
evolution, the Single UNIX Specification is the defacto and dejure standard definition for the UNIX
system application programming interfaces. As the owner of the UNIX trademark, The Open Group
has separated the UNIX trademark from any actual code stream itself, thus allowing multiple
implementations. Since the introduction of the Single UNIX Specification, there has been a single,
open, consensus specification that defines the requirements for a conformant UNIX system.

There is also a mark, or brand, that is used to identify those products that have been certified as
conforming to the Single UNIX Specification, initially UNIX 93, followed subsequently by UNIX 95,
UNIX 98, UNIX 03 and now UNIX V7.

The Open Group is committed to working with the community to further the development of
standards conformant systems by evolving and maintaining the Single UNIX Specification and
participation in other related standards efforts. Recent examples of this are making the
standard freely available on the web, permitting reuse of the standard in open source
documentation projects , providing test tools ,developing the POSIX and LSB certification
programs.

From this page you can read about the history of the UNIX system over the past 40 years or more.
You can learn about the Single UNIX Specification, and read or download online versions of the
specification. You can also get involved in the ongoing development and maintenance of the Single
UNIX Specification, by joining the Austin Group whose approach to specification development is
"write once, adopt everywhere", The Open Group's Base Working Group or get involved in
the UNIX Certification program.

C Programming break and


24.
continue Statement
In this tutorial, you will learn how to use break and continue statements to alter the
program flow of loops.
It is sometimes desirable to skip some statements inside the loop or terminate the
loop immediately without checking the test expression.

In such cases, break and continue statements are used.

break Statement
The break statement terminates the loop (for, while and do...while loop) immediately
when it is encountered. The break statement is used with decision making statement
such as if...else.

Syntax of break statement


break;

The simple code above is the syntax for break statement.

Flowchart of break statement

How break statement works?


Example #1: break statement
// Program to calculate the sum of maximum of 10 numbers
// Calculates sum until user enters positive number

# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;

for(i=1; i <= 10; ++i)


{
printf("Enter a n%d: ",i);
scanf("%lf",&number);

// If user enters negative number, loop is terminated


if(number < 0.0)
{
break;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf",sum);

return 0;
}

Output

Enter a n1: 2.4

Enter a n2: 4.5

Enter a n3: 3.4

Enter a n4: -3

Sum = 10.30

This program calculates the sum of maximum of 10 numbers. It's because, when the
user enters negative number, the break statement is executed and loop is
terminated.

In C programming, break statement is also used with switch...case statement.


continue Statement
The continue statement skips some statements inside the loop. The continue
statement is used with decision making statement such as if...else.

Syntax of continue Statement


continue;

Flowchart of continue Statement

How continue statement works?


Example #2: continue statement
// Program to calculate sum of maximum of 10 numbers
// Negative numbers are skipped from calculation

# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;

for(i=1; i <= 10; ++i)


{
printf("Enter a n%d: ",i);
scanf("%lf",&number);

// If user enters negative number, loop is terminated


if(number < 0.0)
{
continue;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf",sum);

return 0;
}

Output

Enter a n1: 1.1

Enter a n2: 2.2

Enter a n3: 5.5

Enter a n4: 4.4

Enter a n5: -3.4

Enter a n6: -45.5


Enter a n7: 34.5

Enter a n8: -4.2

Enter a n9: -1000

Enter a n10: 12

Sum = 59.70

In the program, when the user enters positive number, the sum is calculated
using sum += number; statement.

When the user enters negative number, the continue statement is executed and
skips the negative number from calculation.

25. C - File I/O

Advertisements

Previous Page
Next Page

The last chapter explained the standard input and output devices handled
by C programming language. This chapter cover how C programmers can
create, open, close text or binary files for their data storage.

A file represents a sequence of bytes, regardless of it being a text file or a


binary file. C programming language provides access on high level
functions as well as low level (OS level) calls to handle file on your storage
devices. This chapter will take you through the important calls for file
management.

Opening Files
You can use the fopen( ) function to create a new file or to open an
existing file. This call will initialize an object of the type FILE, which
contains all the information necessary to control the stream. The prototype
of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );

Here, filename is a string literal, which you will use to name your file, and
access mode can have one of the following values −

Sr.No. Mode & Description

1 r

Opens an existing text file for reading purpose.

2 w

Opens a text file for writing. If it does not exist, then a new file is created.
Here your program will start writing content from the beginning of the file.

3 a

Opens a text file for writing in appending mode. If it does not exist, then
a new file is created. Here your program will start appending content in
the existing file content.

4 r+

Opens a text file for both reading and writing.

5 w+

Opens a text file for both reading and writing. It first truncates the file to
zero length if it exists, otherwise creates a file if it does not exist.

6 a+

Opens a text file for both reading and writing. It creates the file if it does
not exist. The reading will start from the beginning but writing can only
be appended.

If you are going to handle binary files, then you will use following access
modes instead of the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is

int fclose( FILE *fp );

The fclose(-) function returns zero on success, or EOF if there is an error


in closing the file. This function actually flushes any data still pending in
the buffer to the file, closes the file, and releases any memory used for the
file. The EOF is a constant defined in the header file stdio.h.

There are various functions provided by C standard library to read and


write a file, character by character, or in the form of a fixed length string.

Writing a File
Following is the simplest function to write individual characters to a stream

int fputc( int c, FILE *fp );

The function fputc() writes the character value of the argument c to the
output stream referenced by fp. It returns the written character written on
success otherwise EOF if there is an error. You can use the following
functions to write a null-terminated string to a stream −
int fputs( const char *s, FILE *fp );

The function fputs() writes the string s to the output stream referenced
by fp. It returns a non-negative value on success, otherwise EOF is
returned in case of any error. You can use int fprintf(FILE *fp,const
char *format, ...) function as well to write a string into a file. Try the
following example.

Make sure you have /tmp directory available. If it is not, then before
proceeding, you must create this directory on your machine.

#include <stdio.h>

main() {

FILE *fp;

fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");

fputs("This is testing for fputs...\n", fp);

fclose(fp);

When the above code is compiled and executed, it creates a new


file test.txt in /tmp directory and writes two lines using two different
functions. Let us read this file in the next section.

Reading a File
Given below is the simplest function to read a single character from a file

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by
fp. The return value is the character read, or in case of any error, it
returns EOF. The following function allows to read a string from a stream

char *fgets( char *buf, int n, FILE *fp );

The functions fgets() reads up to n-1 characters from the input stream
referenced by fp. It copies the read string into the buffer buf, appending
a null character to terminate the string.

If this function encounters a newline character '\n' or the end of the file
EOF before they have read the maximum number of characters, then it
returns only the characters read up to that point including the new line
character. You can also use int fscanf(FILE *fp, const char *format,
...) function to read strings from a file, but it stops reading after
encountering the first space character.

#include <stdio.h>

main() {

FILE *fp;

char buff[255];
fp = fopen("/tmp/test.txt", "r");

fscanf(fp, "%s", buff);

printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("3: %s\n", buff );

fclose(fp);

When the above code is compiled and executed, it reads the file created
in the previous section and produces the following result −
1 : This
2: is testing for fprintf...

3: This is testing for fputs...

Let's see a little more in detail about what happened here.


First, fscanf() read just This because after that, it encountered a space,
second call is for fgets() which reads the remaining line till it encountered
end of line. Finally, the last call fgets() reads the second line completely.

Binary I/O Functions


There are two functions, that can be used for binary input and output −

size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE


*a_file);

size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements,


FILE *a_file);

Both of these functions should be used to read or write blocks of memories


- usually arrays or structures.
C Programming Files I/O
There are a large number of functions to handle file I/O (Input Output) in C. In this
tutorial, you will learn to handle standard I/O in C using fprintf(), fscanf(), fread(),
fwrite(), fseek.and more.

In C programming, file is a place on your physical disk where information is stored.

Why files are needed?


 When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents
of the file using few commands in C.
 You can easily move your data from one computer to another without any changes.

Types of Files
When dealing with files, there are two types of files you should know about:

1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.

When you open those files, you'll see all the contents within the file as plain text. You
can easily edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide least security
and takes bigger storage space.

2. Binary files
Binary files are mostly the .bin files in your computer.

Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold higher amount of data, are not readable easily and provides a better
security than text files.

File Operations
In C, you can perform four major operations on the file, either text or binary:

1. Creating a new file


2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file

Working with files


When working with files, you need to declare a pointer of type file. This declaration is
needed for communication between the file and program.

FILE *fptr;

Opening a file - for creation and edit


Opening a file is performed using the library function in the "stdio.h" header file:
fopen().

The syntax for opening a file in standard I/O is:


ptr = fopen("fileopen","mode")

For Example:

fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");

 Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The
first function creates a new file named newprogram.txt and opens it for writing as
per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.
 Now let's suppose the second binary file oldprogram.bin exists in the
location E:\cprogram. The second function opens the existing file for reading in
binary mode 'rb'.
The reading mode only allows you to read the file, you cannot write into the file.

Opening Modes in Standard I/O

File
Meaning of Mode During Inexistence of file
Mode

r Open for reading. If the file does not exist, fopen() returns NULL.

rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.

If the file exists, its contents are overwritten. If


w Open for writing.
the file does not exist, it will be created.

If the file exists, its contents are overwritten. If


wb Open for writing in binary mode.
the file does not exist, it will be created.

Open for append. i.e, Data is added


a If the file does not exists, it will be created.
to end of file.
Opening Modes in Standard I/O

File
Meaning of Mode During Inexistence of file
Mode

Open for append in binary mode.


ab If the file does not exists, it will be created.
i.e, Data is added to end of file.

r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.

Open for both reading and writing


rb+ If the file does not exist, fopen() returns NULL.
in binary mode.

If the file exists, its contents are overwritten. If


w+ Open for both reading and writing.
the file does not exist, it will be created.

Open for both reading and writing If the file exists, its contents are overwritten. If
wb+
in binary mode. the file does not exist, it will be created.

Open for both reading and


a+ If the file does not exists, it will be created.
appending.

Open for both reading and


ab+ If the file does not exists, it will be created.
appending in binary mode.

Closing a File
The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using library function fclose().

fclose(fptr); //fptr is the file pointer associated with file to be


closed.
Reading and writing to a text file
For reading and writing to a text file, we use the functions fprintf() and fscanf().

They are just the file versions of printf() and scanf(). The only difference is that,
fprint and fscanf expects a pointer to the structure FILE.

Writing to a text file


Example 1: Write to a text file using fprintf()

#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter num: ");


scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return 0;
}

This program takes a number from user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in
C drive of your computer. When you open the file, you can see the integer you
entered.

Reading from a text file


Example 2: Read from a text file using fscanf()

#include <stdio.h>
int main()
{
int num;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);

return 0;
}

This program reads the integer present in the program.txt file and prints it onto the
screen.

If you succesfully created the file from Example 1, running this program will get you
the integer you entered.

Other functions like fgetchar(), fputc() etc. can be used in similar way.
Reading and writing to a binary file
Functions fread() and fwrite() are used for reading from and writing to a file on the
disk respectively in case of binary files.

Writing to a binary file


To write into a binary file, you need to use the function fwrite(). The functions takes
four arguments: Address of data to be written in disk, Size of data to be written in
disk, number of such type of data and pointer to the file where you want to write.

fwrite(address_data,size_data,numbers_data,pointer_to_file);

Example 3: Writing to a binary file using fwrite()

#include <stdio.h>

struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","wb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);

return 0;
}

In this program, you create a new file program.bin in the C drive.

We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in
the main function as num.

Now, inside the for loop, we store the value into the file using fwrite.

The first parameter takes the address of num and the second parameter takes the
size of the structure threeNum.

Since, we're only inserting one instance of num, the third parameter is 1. And, the last
parameter *fptr points to the file we're storing the data.

Finally, we close the file.

Reading from a binary file


Function fread() also take 4 arguments similar to fwrite() function as above.

fread(address_data,size_data,numbers_data,pointer_to_file);

Example 4: Reading from a binary file using fread()

#include <stdio.h>

struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

for(n = 1; n < 5; ++n)


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);

return 0;
}

In this program, you read the same file program.bin and loop through the records
one by one.

In simple terms, you read one threeNum record of threeNum size from the file pointed
by *fptr into the structure num.

You'll get the same records you inserted in Example 3.


Getting data using fseek()
If you have many records inside a file and need to access a record at a specific
position, you need to loop through all the records before it to get the record.

This will waste a lot of memory and operation time. An easier way to get to the
required data can be achieved using fseek().

As the name suggests, fseek() seeks the cursor to the given record in the file.

Syntax of fseek()
fseek(FILE * stream, long int offset, int whence)

The first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location
where the offset starts.

Different Whence in fseek

Whence Meaning

SEKK_SET Starts the offset from the beginning of the file.

SEKK_END Starts the offset from the end of the file.

SEKK_CUR Starts the offset from the current location of the cursor in the file.

Example of fseek()
#include <stdio.h>

struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

// Moves the cursor to the end of the file


fseek(fptr, sizeof(struct threeNum), SEEK_END);

for(n = 1; n < 5; ++n)


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);

return 0;
}

This program will start reading the records from the file program.bin in the reverse
order (last to first) and prints it.

26. The memory which is programmed at the time it is


manufactured is
A. RAM
B. ROM
C. PROM
D. EPROM
E. None of these
Answer: Option B

27. The ALU of a computer normally contains a number of


high speed storage elements called
A. semiconductor memory
B. registers
C. hard disk
D. magnetic disk
E. None of the above
Answer: Option B

28. Bitwise Operators in C

The following table lists the Bitwise operators supported by C. Assume


variable 'A' holds 60 and variable 'B' holds 13, then −

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists (A & B) =
in both operands. 12, i.e.,
0000 1100

| Binary OR Operator copies a bit if it exists in either (A | B) =


operand. 61, i.e.,
0011 1101

^ Binary XOR Operator copies the bit if it is set in one (A ^ B) =


operand but not both. 49, i.e.,
0011 0001

~ Binary Ones Complement Operator is unary and has the (~A ) = -


effect of 'flipping' bits. 60, i.e,.
1100 0100
in 2's
complement
form.

<< Binary Left Shift Operator. The left operands value is A << 2 =
moved left by the number of bits specified by the right 240 i.e.,
operand. 1111 0000

>> Binary Right Shift Operator. The left operands value is A >> 2 =
moved right by the number of bits specified by the right 15 i.e.,
operand. 0000 1111

Example
Try the following example to understand all the bitwise operators available
in C −
Live Demo

#include <stdio.h>

main() {

unsigned int a = 60; /* 60 = 0011 1100 */

unsigned int b = 13; /* 13 = 0000 1101 */

int c = 0;

c = a & b; /* 12 = 0000 1100 */

printf("Line 1 - Value of c is %d\n", c );

c = a | b; /* 61 = 0011 1101 */

printf("Line 2 - Value of c is %d\n", c );

c = a ^ b; /* 49 = 0011 0001 */

printf("Line 3 - Value of c is %d\n", c );


c = ~a; /*-61 = 1100 0011 */

printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */

printf("Line 5 - Value of c is %d\n", c );

c = a >> 2; /* 15 = 0000 1111 */

printf("Line 6 - Value of c is %d\n", c );

When you compile and execute the above program, it produces the
following result −
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

BIT WISE OPERATORS IN C:


 These operators are used to perform bit operations. Decimal values are converted into binary values which
are the sequence of bits and bit wise operators work on these bits.
 Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise NOT), ^ (XOR), << (left
shift) and >> (right shift).
TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:

BELOW ARE THE BIT-WISE OPERATORS AND THEIR NAME IN C LANGUAGE.


1. & – Bitwise AND
2. | – Bitwise OR
3. ~ – Bitwise NOT
4. ^ – XOR
5. << – Left Shift
6. >> – Right Shift
Consider x=40 and y=80. Binary form of these values are given below.

x = 00101000
y= 01010000

All bit wise operations for x and y are given below.


1. x&y = 00000000 (binary) = 0 (decimal)
2. x|y = 01111000 (binary) = 120 (decimal)
3. ~x = 11111111111111111111111111 11111111111111111111111111111111010111 = -41 (decimal)
4. x^y = 01111000 (binary) = 120 (decimal)
5. x << 1 = 01010000 (binary) = 80 (decimal)
6. x >> 1 = 00010100 (binary) = 20 (decimal)
Note:
 Bit wise NOT : Value of 40 in binary is 00000000000000000000000000000000
00000000000000000010100000000000. So, all 0’s are converted into 1’s in bit wise NOT operation.
 Bit wise left shift and right shift : In left shift operation “x << 1 “, 1 means that the bits will be left shifted
by one place. If we use it as “x << 2 “, then, it means that the bits will be left shifted by 2 places.
EXAMPLE PROGRAM FOR BIT WISE OPERATORS IN C:
In this example program, bit wise operations are performed as shown above and output is displayed in decimal
format.

1 #include <stdio.h>
2
3 int main()
4 {
5 int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
6 AND_opr = (m&n);
7 OR_opr = (m|n);
8 NOT_opr = (~m);
9 XOR_opr = (m^n);
10 printf("AND_opr value = %d\n",AND_opr );
11 printf("OR_opr value = %d\n",OR_opr );
12 printf("NOT_opr value = %d\n",NOT_opr );
13 printf("XOR_opr value = %d\n",XOR_opr );
14 printf("left_shift value = %d\n", m << 1);
15 printf("right_shift value = %d\n", m >> 1);
16 }
COMPILE & RUN
OUTPUT:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
CONTINUE ON TYPES OF C OPERATORS:
Click on each operator name below for detailed description and example programs.

Types of Operators Description

These are used to perform mathematical calculations like


Arithmetic_operators addition, subtraction, multiplication, division and modulus

These are used to assign the values for the variables in C


Assignment_operators programs.
These operators are used to compare the value of two
Relational operators variables.

These operators are used to perform logical operations on


Logical operators the given two variables.

These operators are used to perform bit operations on given


Bit wise operators two variables.

Conditional (ternary) Conditional operators return one value if condition is true


operators and returns another value is condition is false.

Increment/decrement These operators are used to either increase or decrease the


operators value of the variable by one.

Special operators &, *, sizeof( ) and ternary operators

29. What is void datatype in c?


void data type:

it is actually refers to an object that does not have a value of any type.

when we have defined functions that return no value, i.e.

functions which only print a message and have no value to return. Such a function is
used for its side effect and not for its value. In the function declaration and
definition, we have indicated that the function does not return a value by using the
data type

void

to show an empty type, i.e. no value. Similarly, when a function has no formal
parameters, the keyword

void

is used in the function prototype and header to signify that there is no information
passed to the function.

Here is a simple program using a message printing function which takes a void

void parameter and returns type void

void prinmsg(void);

main()
{
void printmsg(void)
{
printf("****HOME IS WHERE THE HEART IS****\n");
}
Difference Between Unicode
30.
and ASCII
Unicode vs ASCII
ASCII and Unicode are two character encodings. Basically, they are
standards on how to represent difference characters in binary so that
they can be written, stored, transmitted, and read in digital media.
The main difference between the two is in the way they encode the
character and the number of bits that they use for each. ASCII
originally used seven bits to encode each character. This was later
increased to eight with Extended ASCII to address the apparent
inadequacy of the original. In contrast, Unicode uses a variable
bit encoding program where you can choose between 32, 16, and 8-
bit encodings. Using more bits lets you use more characters at the
expense of larger files while fewer bits give you a limited choice but
you save a lot of space. Using fewer bits (i.e. UTF-8 or
ASCII) would probably be best if you are encoding a large document
in English.
One of the main reasons why Unicode was the problem arose from
the many non-standard extended ASCII programs. Unless you are
using the prevalent page, which is used by Microsoft and most
other software companies, then you are likely to encounter problems
with your characters appearing as boxes. Unicode virtually
eliminates this problem as all the character code points were
standardized.
Another major advantage of Unicode is that at its maximum it can
accommodate a huge number of characters. Because of this, Unicode
currently contains most written languages and still has room for even
more. This includes typical left-to-right scripts like English and even
right-to-left scripts like Arabic. Chinese, Japanese, and the many
other variants are also represented within Unicode. So Unicode won’t
be replaced anytime soon.

In order to maintain compatibility with the older ASCII, which was


already in widespread use at the time, Unicode was designed in such
a way that the first eight bits matched that of the most popular ASCII
page. So if you open an ASCII encoded file with Unicode, you still get
the correct characters encoded in the file. This facilitated the
adoption of Unicode as it lessened the impact of adopting a new
encoding standard for those who were already using ASCII.

Summary:

1.ASCII uses an 8-bit encoding while Unicode uses a variable bit


encoding.
2.Unicode is standardized while ASCII isn’t.
3.Unicode represents most written languages in the world while
ASCII does not.
4.ASCII has its equivalent within Unicode.

What is the difference between ASCII and unicode


characters & difference between UTF-8 and UTF-
16?
American Standard Code for Information Interchange (ASCII) is a
character-encoding scheme and it was the first character encoding standard. It is a
code for representing English characters as numbers, with each letter assigned a
number from 0 to 127. Most modern character-encoding schemes are based on ASCII,
though they support many additional characters

Unicode is a standard which defines the internal text coding system in almost all
operating systems used in computers at present.Unicode assigns each character a
unique number, or code point. It defines two mapping methods, the UTF (Unicode
Transformation Format) encodings, and the UCS (Universal Character Set) encodings.
Unicode-based encodings implement the Unicode standard and include UTF-8, UTF-
16 and UTF-32/UCS-4.

UTF-8 - uses 1 byte to represent characters in the ASCII set, two bytes for characters
in several more alphabetic blocks, and three bytes for the rest of the BMP.
Supplementary characters use 4 bytes.

UTF-16 - uses 2 bytes for any character in the BMP, and 4 bytes for supplementary
characters.

31. Input and Output Devices


The devices which are used to input the data and the programs in the computer are
known as "Input Devices". or Input device can read data and convert them to a form
that a computer can use. Output Device can produce the final product of machine
processing into a form usable by humans. It provides man to machine communication.
Some of the I/O devices are explained below:
(1) Keyboard : Keyboard is used in the input phase of a computer-
based information system. Keyboard is most common input device is used today. The
data and instructions are input by typing on the keyboard. The message typed on the
keyboard reaches the memory unit of a computer. It’s connected to a computer via a
cable. Apart from alphabet and numeral keys, it has other function keys for performing
different functions.
(2) Mouse : It’s a pointing device. The mouse is rolled over the mouse pad, which in
turn controls the movement of the cursor in the screen. We can click, double click or
drag the mouse. Most of the mouse’s have a ball beneath them, which rotates when
the mouse in moved. The ball has 2 wheels of the sides, which in turn mousse with
the movement of the ball. The sensor notifies the speed of its movements to the
computer, which in turn moves the cursor/pointer on the screen.
(3) Scanner : Scanners are used to enter information directly in to the computers
memory. This device works like a Xerox machine. The scanner converts any type of
printed or written information including photographs into digital pulses, which can be
manipulated by the computer.
(4) Track Ball : Track ball is similar to the upside- down design of the mouse. The
user moves the ball directly, while the device itself remains stationary. The user spins
the ball in various directions to effect the screen movements.
(5) Light Pen : This is an input device which is used to draw lines or figures on a
computer screen. It’s touched to the CRT screen where it can detect raster on the
screen as it passes.
(6) Optical Character Rader : It’s a device which detects alpha numeric characters
printed or written on a paper. The text which is to be scanned is illuminated by a low
frequency light source. The light is absorbed by the dark areas but reflected from the
bright areas. The reflected light is received by the photocells.
(7) Bar Code Reader : This device reads bar codes and coverts them into electric
pulses to be processed by a computer. A bar code is nothing but data coded in form
of light and dark bars.
(8) Voice Input Systems : This devices converts spoken words to M/C language form.
A micro phone is used to convert human speech into electric signals. The signal
pattern is then transmitted to a computer when it’s compared to a dictionary of patterns
that have been previously placed in a storage unit of computer. When a close match
is found, the word is recognized.
(9) Plotter : Plotter is an O/P device that is used to produce graphical O/P on papers.
It uses single color or multi color pens to draw pictures as blue print etc.
(10) Digital Camera : It converts graphics directly into digital form. It looks like an
ordinary camera, but no film is used therein, instead a CCD (changed coupled Divide)
Electronic chip in used. When light falls, on the chip though the lens, it converts light
waves into electrical waves.
Input and Output Devices Links to topics on this page:
Before a computer can process your data, you need Input Devices
some method to input the data into the machine. The Keyboard
device you use will depend on what form this data Mouse
takes (be it text, sound, artwork, etc.). Touch pad
Track Ball
Similarly, after the computer has processed your data, Other
you often need to produce output of the results. This Output Devices
output could be a display on the computer CRT Monitor
screen, hardcopy on printed pages, or even the Flat Panel Display
audio playback of music you composed on the Ink Jet Printer
computer. Laster Printer
Other
The terms “input” and “output” are used both as verbs
to describe the process of entering or displaying the
data, and as nouns referring to the data itself entered
into or displayed by the computer.

Below we discuss the variety of peripheral devices


used for computer input and output.

Input Devices

Keyboard
The computer keyboard is used to enter text
information into the computer, as when you type the
contents of a report. The keyboard can also be used to
type commands directing the computer to perform
certain actions. Commands are typically chosen from
an on-screen menu using a mouse, but there are often
keyboard shortcuts for giving these same commands.
In addition to the keys of the main keyboard (used for PC Keyboard (you have one in
typing text), keyboards usually also have a numeric front of you that you can see for
keypad (for entering numerical data efficiently), a a closer look)
bank of editing keys (used in text editing operations),
and a row of function keys along the top (to easily
invoke certain program functions). Laptop
computers, which don’t have room for large
keyboards, often include a “fn” key so that other keys
can perform double duty (such as having a numeric
keypad function embedded within the main keyboard
keys).
Improper use or positioning of a keyboard can lead to
repetitive-stress injuries.
Some ergonomic keyboards are designed with
angled arrangements of keys and with built-in wrist
rests that can minimize your risk of RSIs.
Most keyboards attach to the PC via a PS/2 connector
or USB port (newer). Older Macintosh computers
used an ABD connector, but for several years now all
Mac keyboards have connected using USB.

Pointing Devices
The graphical user interfaces (GUIs) in use today
require some kind of device for positioning the on-
screen cursor. Typical pointing devices are: mouse,
trackball, touch pad, trackpoint, graphics tablet,
joystick, and touch screen.
Pointing devices, such as a mouse, connected to the
PC via a serial ports (old), PS/2 mouse port (newer),
or USB port (newest). Older Macs used ADB to
connect their mice, but all recent Macs
use USB (usually to a USB port right on the USB
keyboard).

Mouse
The mouse pointing device sits on your work surface
and is moved with your hand. In older mice, a ball in
the bottom of the mouse rolls on the surface as you
move the mouse, and internal rollers sense the ball
movement and transmit the information to the
computer via the cord of the mouse.
The newer optical mouse does not use a rolling ball, Two-button mouse with scroll
but instead uses a light and a small optical sensor to wheel
detect the motion of the mouse by tracking a tiny
image of the desk surface. Optical mice avoid the
problem of a dirty mouse ball, which causes regular
mice to roll unsmoothly if the mouse ball and internal
rollers are not cleaned frequently.
A cordless or wireless mouse communicates with
the computer via radio waves (often
using BlueTooth hardware and protocol) so that a
cord is not needed (but such mice need internal Wireless Macintosh mouse
batteries).
A mouse also includes one or more buttons (and
possibly a scroll wheel) to allow users to interact with
the GUI. The traditional PC mouse has two buttons,
while the traditional Macintosh mouse has one
button. On either type of computer you can also use
mice with three or more buttons and a small scroll
wheel (which can also usually be clicked like a
button).

Touch pad
Most laptop computers today have a touch
pad pointing device. You move the on-screen cursor
by sliding your finger along the surface of the touch
pad. The buttons are located below the pad, but most
touch pads allow you to perform “mouse clicks” by
tapping on the pad itself.
Touch pads have the advantage over mice that they
take up much less room to use. They have the Touch pad of a PC laptop
advantage over trackballs (which were used on early
laptops) that there are no moving parts to get dirty
and result in jumpy cursor control.

Trackpoint
Some sub-notebook computers (such as the IBM
ThinkPad), which lack room for even a touch pad,
incorporate a trackpoint, a small rubber projection
embedded between the keys of the keyboard. The
trackpoint acts like a little joystick that can be used to
control the position of the on-screen cursor.
Trackpoint
Trackball
The trackball is sort of like an upside-down mouse,
with the ball located on top. You use your fingers to
roll the trackball, and internal rollers (similar to
what’s inside a mouse) sense the motion which is
transmitted to the computer. Trackballs have the
advantage over mice in that the body of the trackball
remains stationary on your desk, so you don’t need as
much room to use the trackball. Early laptop
Trackball
computers often used trackballs (before superior
touch pads came along).
Trackballs have traditionally had the same problem as
mice: dirty rollers can make their cursor control
jumpy and unsmooth. But there are modern optical
trackballs that don’t have this problem because their
designs eliminate the rollers.

Joysticks
Joysticks and other game controllers can also be
connected to a computer as pointing devices. They are
generally used for playing games, and not for
controlling the on-screen cursor in productivity
software.

Touch screen
Some computers, especially small hand-held PDAs,
have touch sensitive display screens. The user can
make choices and press button images on the screen.
You often use a stylus, which you hold like a pen, to
“write” on the surface of a small touch screen.

Graphics tablet
A graphics tablet consists of an electronic writing area
and a special “pen” that works with it. Graphics
tablets allows artists to create graphical images with
motions and actions similar to using more traditional
drawing tools. The pen of the graphics tablet is
pressure sensitive, so pressing harder or softer can
result in brush strokes of different width (in an
appropriate graphics program).

Scanners Graphics tablet.


A scanner is a device that images a printed page or
graphic by digitizing it, producing an image made of
tiny pixels of different brightness and color values
which are represented numerically and sent to the
computer. Scanners scan graphics, but they can also
scan pages of text which are then run through OCR
(Optical Character Recognition) software that
identifies the individual letter shapes and creates a
text file of the page's contents.

Microphone
A microphone can be attached to a computer to
record sound (usually through a sound card input or
circuitry built into the motherboard). The sound is
digitized—turned into numbers that represent the
original analog sound waves—and stored in the
computer to later processing and playback.

MIDI Devices
MIDI (Musical Instrument Digital Interface) is
a system designed to transmit information between
electronic musical instruments. A MIDI musical
keyboard can be attached to a computer and allow a
performer to play music that is captured by the
computer system as a sequence of notes with the
associated timing (instead of recording digitized
sound waves).

Output Devices

CRT Monitor
The traditional output device of a personal computer
has been the CRT (Cathode Ray Tube) monitor. Just
like a television set (an older one, anyway) the CRT
monitor contains a large cathode ray tube that uses an
electron beam of varying strength to “paint” a picture
onto the color phosphorescent dots on the inside of
the screen. CRT monitors are heavy and use more
electrical power than flat panel displays, but they are
preferred by some graphic artists for their accurate
color rendition, and preferred by some gamers for CRT monitor
faster response to rapidly changing graphics.
Monitor screen size is measured diagonally across
the screen, in inches. Not all of the screen area may be
usable for image display, so the viewable area is also
specified. The resolutionof the monitor is the
maximum number of pixels it can display horizontally
and vertically (such as 800 x 600, or 1024 x 768, or
1600 x 1200). Most monitors can display several
resolutions below its maximum setting. Pixels (short
for picture elements) are the small dots that make of
the image displayed on the screen. The spacing of the
screen’s tiny phosphor dots is called the dot
pitch (dp), typically .28 or .26 (measured in
millimeters). A screen with a smaller dot pitch
produces sharper images.
Your computer must produce a video signal that a
monitor can display. This may be handled by circuitry
on the motherboard, but is usually handled by
a video card in one of the computer’s expansion
slots; often the slot is a special one dedicated to video
use, such as an AGP slot (Accelerated Graphics
Port). Video cards are also called video display
adapters, and graphics cards. Many video cards
contain separate processors and dedicated video
memory for generating complex graphics quickly
without burdening the CPU. These accelerated
graphics cards are loved by gamers.

Flat Panel Monitor


A flat panel display usually uses an LCD (Liquid
Crystal Display) screen to display output from the
computer. The LCD consists of several thin layers that
polarize the light passing through them. The
polarization of one layer, containing long thin
molecules called liquid crystals, can be controlled
electronically at each pixel, blocking varying amounts Flat panel display (LCD)
of the light to make a pixel lighter or darker. Other
types of flat panel technology exist (such as plasma
displays) but LCDs are most commonly used in
computers, especially laptops.
Older LCDs had slow response times and low
contrast, butactive matrix LCD screens have a
transparent thin film transistor (TFT) controlling
each pixel, so response, contrast, and viewing angle
are much improved.
Flat panel displays are much lighter and less bulky
than CRT monitors, and they consume much less
power. They have been more expensive than CRTs in
the past, but the price gap is narrowing. You will see
many more flat panels in the future.
As with CRTs, the display size of a flat panel is
expressed in inches, and the resolution is the number
of pixels horizontally and vertically on the display.

Ink Jet Printer


For hardcopy (printed) output, you need some kind of
printer attached to your computer (or available over a
network). The most common type of printer for home
systems is the color ink jet printer. These printers
form the image on the page by spraying tiny droplets
of ink from the print head. The printer needs several
colors of ink (cyan, yellow, magenta, and black) to
make color images. Some photo-quality ink jet
printers have more colors of ink. Inkjet Printer

Ink jet printers are inexpensive, but the cost of


consumables (ink cartridges and special paper) make
them costly to operate in the long run for many
purposes.

Laser Printer
A laser printer produces good quality images by the
same technology that photocopiers use. A drum
coated with photosensitive material is charged, then
an image is written onto it by a laser (or LEDs) which
makes those areas lose the charge. The drum then
rolls through toner (tiny plastic particles of pigment)
that are attracted to the charged areas of the drum.
The toner is then deposited onto the paper, and then Laser Printer
fused into the paper with heat.
Most laser printers are monochrome (one color only,
usually black), but more expensive laser printers with
multiple color toner cartridges can produce color
output.
Laser printers are faster than ink jet printers. Their
speed is rated in pages per minute (ppm). Laser
printers are more expensive than ink jets, but they are
cheaper to run in the long term if you just need good
quality black & white pages.

Other Printers
Multi-function printers are available that not only
operate as a computer printer, but also include the
hardware needed to be a scanner, photocopier, and
FAX machine as well.
Dot matrix printers use small electromagnetically
activated pins in the print head, and an inked ribbon,
to produce images by impact. These printers are slow
and noisy, and are not commonly used for personal
computers anymore (but they can print multi-layer
forms, which neither ink jet or laser printers can).

Sound Output
Computers also produce sound output, ranging from
simple beeps alerting the user, to impressive game
sound effects, to concert quality music. The circuitry
to produce sound may be included on the
motherboard, but high quality audio output from a PC
usually requires a sound card in one of the
expansion slots, connected to a set of good quality
external speakers or headphones.
Multimedia is a term describing computer output
that includes sound, text, graphics, movies, and
animation. A sound card is an example of a
multimedia output device (as is a monitor that can
display graphics).

32. C - Command Line Arguments

Advertisements

Previous Page
Next Page

It is possible to pass some values from the command line to your C


programs when they are executed. These values are called command line
arguments and many times they are important for your program
especially when you want to control your program from outside instead of
hard coding those values inside the code.
The command line arguments are handled using main() function
arguments where argc refers to the number of arguments passed,
and argv[] is a pointer array which points to each argument passed to the
program. Following is a simple example which checks if there is any
argument supplied from the command line and take action accordingly −

#include <stdio.h>

int main( int argc, char *argv[] ) {

if( argc == 2 ) {

printf("The argument supplied is %s\n", argv[1]);

else if( argc > 2 ) {

printf("Too many arguments supplied.\n");

else {

printf("One argument expected.\n");

When the above code is compiled and executed with single argument, it
produces the following result.

$./a.out testing

The argument supplied is testing

When the above code is compiled and executed with a two arguments, it
produces the following result.

$./a.out testing1 testing2

Too many arguments supplied.

When the above code is compiled and executed without passing any
argument, it produces the following result.

$./a.out
One argument expected

It should be noted that argv[0] holds the name of the program itself
and argv[1] is a pointer to the first command line argument supplied, and
*argv[n] is the last argument. If no arguments are supplied, argc will be
one, and if you pass one argument then argc is set at 2.

You pass all the command line arguments separated by a space, but if
argument itself has a space then you can pass such arguments by putting
them inside double quotes "" or single quotes ''. Let us re-write above
example once again where we will print program name and we also pass
a command line argument by putting inside double quotes −

#include <stdio.h>

int main( int argc, char *argv[] ) {

printf("Program name %s\n", argv[0]);

if( argc == 2 ) {

printf("The argument supplied is %s\n", argv[1]);

else if( argc > 2 ) {

printf("Too many arguments supplied.\n");

else {

printf("One argument expected.\n");

When the above code is compiled and executed with a single argument
separated by space but inside double quotes, it produces the following
result.
$./a.out "testing1 testing2"

Progranm name ./a.out


The argument supplied is testing1 testing2

Command Line Parameters


Many programs allow command-line arguments to be specified when they are run. A
command-line argument is the information that follows the program's name on the command
line of the operating system. Command-line arguments are used to pass information to the
program. For example, when you use a text editor, you probably specify the name of the file
you want to edit after the name of the word processing program. For example, if you use a
word processor called WP, then this line causes the file TEST to be edited.

WP TEST

Here, TEST is a command-line argument. Your C programs may also utilize command-line
arguments. These are passed to a C program through two arguments to the main() function.
The parameters are called argc and argv. These parameters are optional and are not used
when no command-line arguments are being used.

The argc parameter holds the number of arguments on the command-line and is an integer.
It will always be at least 1 because the name of the program qualifies as the first argument.
The argv parameter is an array of string pointers. The most common method for
declaring argv is shown here.

char *argv[];

The empty brackets indicate that it is an array of undetermined length. All command-line
arguments are passed to main() as strings. To access an individual string, index argv. For
example, argv[0] points to the program's name and argv[1] points to the first argument.
This program displays all the command-line arguments that it is called with.

#include $$$$stdio.h££££

void main(int argc, char *argv[])

int i;

for (i=1; i&ltargc; i++) printf("%s",argv[i]);

}
The ANSI C standard does not specify what constitutes a command-line argument, because
operatring systems vary considerably on this point. However, the most common convention is
as follows:

Each command-line argument must be separated by a space or a tab character. Commas,


semicolons, and the like are not considered separators. For example:

This is a test

is made up of four strings, but

this,that,and,another

is one string. If you need to pass a command-line argument that does, in fact contain spaces,
you must place it between quotes, as shown in this example:

"this is a test"

A further example of the use of argc and argv now follows:

void main(int argc, char *argv[])

if (argc !=2) {

printf("Specify a password");

exit(1);

if (!strcmp(argv[1], "password"))

printf("Access Permitted");

else

printf("Access denied");

exit(1);
}

program code here ......

This program only allows access to its code if the correct password is entered as a command-
line argument. There are many uses for command-line arguments and they can be a powerful
tool.

My final example program takes two command-line arguments. The first is the name of a file,
the second is a character. The program searches the specified file, looking for the character.
If the file contains at least one of these characters, it reports this fact. This program
uses argv to access the file name and the character for which to search.

/*Search specified file for specified character. */

#include $$$$stdio.h££££

#include $$$$stdlib.h££££

void main(int argc, char *argv[])

FILE *fp; /* file pointer */

char ch;

/* see if correct number of command line arguments */

if(argc !=3) {

printf("Usage: find $$$$filename££££ $$$$ch££££\n");

exit(1);

/* open file for input */

if ((fp = fopen(argv[1], "r"))==NULL) {

printf("Cannot open file \n");


exit(1);

/* look for character */

while ((ch = getc(fp)) !=EOF) /* where getc() is a */

if (ch== *argv[2]) { /*function to get one char*/

printf("%c found",ch); /* from the file */

break;

fclose(fp);

[program]

The names of argv and argc are arbitrary - you can use any names you like.
However, argc and argv have traditionally been used since C's origin. It is a good idea to
use these names so that anyone reading your program can quickly identify them as
command-line parameters

33. What are the advantages and dis-advantages of


array?
Advantages:

1. It is used to represent multiple data items of same type by using only single
name.
2. It can be used to implement other data structures like linked lists, stacks,
queues, trees, graphs etc.
3. 2D arrays are used to represent matrices.
Disadvantages:

1. We must know in advance that how many elements are to be stored in


array.
2. Array is static structure. It means that array is of fixed size. The memory
which is allocated to array can not be increased or reduced.
3. Since array is of fixed size, if we allocate more memory than requirement
then the memory space will be wasted. And if we allocate less memory than
requirement, then it will create problem.
4. The elements of array are stored in consecutive memory locations. So
insertions and deletions are very difficult and time consuming.

Advantages and Disadvantages of Array in C


Programming
Advantages
 It is better and convenient way of storing the data of same datatype with same size.

 It allows us to store known number of elements in it.

 It allocates memory in contiguous memory locations for its elements. It does not allocate
any extra space/ memory for its elements. Hence there is no memory overflow or
shortage of memory in arrays.

 Iterating the arrays using their index is faster compared to any other methods like linked
list etc.

 It allows to store the elements in any dimensional array - supports multidimensional


array.

Disadvantages
 It allows us to enter only fixed number of elements into it. We cannot alter the size of the
array once array is declared. Hence if we need to insert more number of records than
declared then it is not possible. We should know array size at the compile time itself.

 Inserting and deleting the records from the array would be costly since we add / delete
the elements from the array, we need to manage memory space too.

 It does not verify the indexes while compiling the array. In case there is any indexes
pointed which is more than the dimension specified, then we will get run time errors
rather than identifying them at compile time.

Important things to know about Arrays


 Array indexes always begin with 0. Hence when we say array of size 10, array has
elements from index 0 to 9. If we specify or use array as intArr[10], intArr[11],
intArr[200], the C compiler will not show any error, but we will get run time errors while
executing the program.

 Arrays are supported by primitive datatypes, non-primitive types like structures, unions,
pointers etc

34. Write Logic Gate Functions in C Programming


Subject: Computer Science - C Programming.
Write Logic Gate Functions in C Programming
Subject: Computer Science - C Programming.
Context: This function takes in two files as inputs, one that describes the circuit and one that
contains input values. The program should read the files that contain commands like INPUTVAR,
OUTPUTVAR, AND, NOT, OR (And the values following the command).
Ex. INPUTVAR 3 A B C
OUTPUTVAR 1 Q
AND A B w
Which means there are 3 Input variables: A, B, C.
1 Output variable: Q
Use the AND logic and give it a variable name: w
etc. (More context below)
C Program to Check Whether
35.
a Number is Prime or Not
Example to check whether an integer (entered by the user) is a prime number or not
using for loop and if...else statement.
To understand this example, you should have the knowledge of following C
programming topics:

 C if...else Statement
 C Programming for Loop
 C Programming break and continue Statement

A prime number is a positive integer which is divisible only by 1 and itself. For
example: 2, 3, 5, 7, 11, 13

Example: Program to Check Prime Number


#include <stdio.h>
int main()
{
int n, i, flag = 0;

printf("Enter a positive integer: ");


scanf("%d",&n);
for(i=2; i<=n/2; ++i)
{
// condition for nonprime number
if(n%i==0)
{
flag=1;
break;
}
}

if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);

return 0;
}

Output

Enter a positive integer: 29

29 is a prime number.

If the for loop terminates when the test expression of loop i <= n/2 is false, the
entered number is a prime number. The value of flag is equal to 0 in this case.

If the loop terminates because of break statement inside the if statement, the
entered number is a nonprime number. The value of flag is 1 in this case.

Visit this page to learn, how you can display all prime numbers between two intervals
entered by the user.

36. Reverse a string in C


Reverse a string in C: This program reverses a string that a user inputs.
For example, if a user enters a string "reverse me" then on reversing it
will be "em esrever". C program to reverse a string using strrev library
function of "string.h", without using strrev, recursion and pointers. A
string which remains the same on reversal is a palindrome string.

String reverse in C
#include <stdio.h>
#include <string.h>

int main()
{
char arr[100];

printf("Enter a string to reverse\n");


gets(arr);

strrev(arr);

printf("Reverse of the string is \n%s\n",


arr);

return 0;
}

C reverse string program output:

Download Reverse string program.


C program to reverse words in a string

Reverse string C program without using


strrev
First we calculate length of the string without using strlen function and
then copy its characters in reverse order (from end to beginning) to a
new string using a for loop.

#include <stdio.h>

int main()
{
char s[1000], r[1000];
int begin, end, count = 0;

printf("Input a string\n");
gets(s);

// Calculating string length

while (s[count] != '\0')


count++;

end = count - 1;

for (begin = 0; begin < count; begin++) {


r[begin] = s[end];
end--;
}
r[begin] = '\0';

printf("%s\n", r);

return 0;
}

C program to reverse a string using


recursion
#include <stdio.h>
#include <string.h>

void reverse(char*, int, int);

int main()
{
char a[100];

gets(a);

reverse(a, 0, strlen(a)-1);

printf("%s\n", a);

return 0;
}
void reverse(char *x, int begin, int end)
{
char c;

if (begin >= end)


return;

c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;

reverse(x, ++begin, --end);


}

In the recursive method, we swap characters at the beginning and the


end of the string and then move towards the middle of the string. This
way is inefficient due to repeated function calls but useful in practicing
recursion.

C program to reverse a string using


pointers
Now we will invert a string using pointers or without using the library
function strrev.

#include<stdio.h>

int string_length(char*);
void reverse(char*);

main()
{
char s[100];

printf("Enter a string\n");
gets(s);

reverse(s);

printf("Reverse of the string is \"%s\".\n",


s);

return 0;
}

void reverse(char *s)


{
int length, c;
char *begin, *end, temp;

length = string_length(s);
begin = s;
end = s;

for (c = 0; c < length - 1; c++)


end++;

for (c = 0; c < length/2; c++)


{
temp = *end;
*end = *begin;
*begin = temp;

begin++;
end--;
}
}

int string_length(char *pointer)


{
int c = 0;

while( *(pointer + c) != '\0' )


c++;

return c;
}

37. write a c program to add the digits in an integer using


while loop
Sum of digits using while loop
/* Calculate sum of digits using while loop */

#include<stdio.h>
int main()
{
int a, s;
printf("Enter value of a: ");
scanf("%d",&a);
s = 0;
while(a > 0)
{
s = s + (a%10);
a = a / 10;
}
printf("Sum of digits: %d",s);
return 0;
}

39. compiler
A compiler is a special program that processes statements written in a
particular programming language and turns them into machine language or
"code" that a computer's processor uses. Typically, a programmer writes
language statements in a language such as Pascal or C one line at a time
using an editor. The file that is created contains what are called the source
statements. The programmer then runs the appropriate language compiler,
specifying the name of the file that contains the source statements.

When executing (running), the compiler first parses (or analyzes) all of the
language statements syntactically one after the other and then, in one or
more successive stages or "passes", builds the output code, making sure
that statements that refer to other statements are referred to correctly in the
final code. Traditionally, the output of the compilation has been
called object code or sometimes an object module . (Note that the term
"object" here is not related to object-oriented programming.) The object
code is machine code that the processor can execute one instruction at a
time.

The Java programming language, a language used in object-oriented


programming, introduced the possibility of compiling output
(called bytecode ) that can run on any computer system platform for which
a Java virtual machine or bytecode interpreter is provided to convert the
bytecode into instructions that can be executed by the actual hardware
processor. Using this virtual machine, the bytecode can optionally be
recompiled at the execution platform by a just-in-time compiler. (See
also: Java compiler)
Traditionally in some operating systems, an additional step was required
after compilation - that of resolving the relative location of instructions and
data when more than one object module was to be run at the same time
and they cross-referred to each other's instruction sequences or data. This
process was sometimes called linkage editing and the output known as
a load module.

A compiler works with what are sometimes called 3GL and higher-level
languages. An assembler works on programs written using a processor's
assembler language.

40. C - Operators

C - Operators

Advertisements

Previous Page
Next Page

An operator is a symbol that tells the compiler to perform specific


mathematical or logical functions. C language is rich in built-in operators
and provides the following types of operators −

 Arithmetic Operators

 Relational Operators

 Logical Operators

 Bitwise Operators

 Assignment Operators

 Misc Operators

We will, in this chapter, look into the way each operator works.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C
language. Assume variable A holds 10 and variable B holds 20 then −

Show Examples

Operator Description Example

+ Adds two operands. A+B=


30

− Subtracts second operand from the first. A−B=


-10

* Multiplies both operands. A*B=


200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer B%A=


division. 0

++ Increment operator increases the integer value by one. A++ =


11

-- Decrement operator decreases the integer value by one. A-- = 9

Relational Operators
The following table shows all the relational operators supported by C.
Assume variable A holds 10 and variable B holds 20 then −

Show Examples

Operator Description Example


== Checks if the values of two operands are equal or not. If (A == B)
yes, then the condition becomes true. is not
true.

!= Checks if the values of two operands are equal or not. If (A != B)


the values are not equal, then the condition becomes true. is true.

> Checks if the value of left operand is greater than the (A > B)
value of right operand. If yes, then the condition becomes is not
true. true.

< Checks if the value of left operand is less than the value of (A < B)
right operand. If yes, then the condition becomes true. is true.

>= Checks if the value of left operand is greater than or equal (A >= B)
to the value of right operand. If yes, then the condition is not
becomes true. true.

<= Checks if the value of left operand is less than or equal to (A <= B)
the value of right operand. If yes, then the condition is true.
becomes true.

Logical Operators
Following table shows all the logical operators supported by C language.
Assume variable A holds 1 and variable B holds 0, then −

Show Examples

Operator Description Example

&& Called Logical AND operator. If both the operands are non- (A && B)
zero, then the condition becomes true. is false.

|| Called Logical OR Operator. If any of the two operands is (A || B)


non-zero, then the condition becomes true. is true.
! Called Logical NOT Operator. It is used to reverse the !(A &&
logical state of its operand. If a condition is true, then B) is
Logical NOT operator will make it false. true.

Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ is as follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 60 and B = 13 in binary format, they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The following table lists the bitwise operators supported by C. Assume


variable 'A' holds 60 and variable 'B' holds 13, then −

Show Examples

Operator Description Example


& Binary AND Operator copies a bit to the result if it exists (A & B) =
in both operands. 12, i.e.,
0000 1100

| Binary OR Operator copies a bit if it exists in either (A | B) =


operand. 61, i.e.,
0011 1101

^ Binary XOR Operator copies the bit if it is set in one (A ^ B) =


operand but not both. 49, i.e.,
0011 0001

~ (~A ) = -
60, i.e,.
Binary Ones Complement Operator is unary and has the 1100 0100
effect of 'flipping' bits. in 2's
complement
form.

<< Binary Left Shift Operator. The left operands value is A << 2 =
moved left by the number of bits specified by the right 240 i.e.,
operand. 1111 0000

>> Binary Right Shift Operator. The left operands value is A >> 2 =
moved right by the number of bits specified by the right 15 i.e.,
operand. 0000 1111

Assignment Operators
The following table lists the assignment operators supported by the C
language −

Show Examples

Operator Description Example

= Simple assignment operator. Assigns values from right C=A+B


side operands to left side operand will assign
the value
of A + B
to C
+= Add AND assignment operator. It adds the right operand C += A is
to the left operand and assign the result to the left equivalent
operand. to C = C
+A

-= Subtract AND assignment operator. It subtracts the right C -= A is


operand from the left operand and assigns the result to equivalent
the left operand. to C = C -
A

*= Multiply AND assignment operator. It multiplies the right C *= A is


operand with the left operand and assigns the result to equivalent
the left operand. to C = C
*A

/= Divide AND assignment operator. It divides the left C /= A is


operand with the right operand and assigns the result to equivalent
the left operand. to C = C /
A

%= Modulus AND assignment operator. It takes modulus C %= A is


using two operands and assigns the result to the left equivalent
operand. to C = C
%A

<<= Left shift AND assignment operator. C <<= 2


is same
as C = C
<< 2

>>= Right shift AND assignment operator. C >>= 2


is same
as C = C
>> 2

&= Bitwise AND assignment operator. C &= 2 is


same as C
=C&2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is
same as C
=C^2

|= Bitwise inclusive OR and assignment operator. C |= 2 is


same as C
=C|2

Misc Operators ↦ sizeof & ternary


Besides the operators discussed above, there are a few other important
operators including sizeof and ? : supported by the C Language.

Show Examples

Operator Description Example

sizeof() sizeof(a), where a is integer, will


Returns the size of a variable.
return 4.

& &a; returns the actual address of


Returns the address of a variable.
the variable.

* Pointer to a variable. *a;

?: If Condition is true ? then value X


Conditional Expression.
: otherwise value Y

Operators Precedence in C
Operator precedence determines the grouping of terms in an expression
and decides how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has a
higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because


operator * has a higher precedence than +, so it first gets multiplied with
3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.

Show Examples

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left


Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

C Programming Operators
C programming has various operators to perform tasks including arithmetic,
conditional and bitwise operations. You will learn about various C operators and how
to use them in this tutorial.

An operator is a symbol which operates on a value or a variable. For example: + is


an operator to perform addition.

C programming has wide range of operators to perform various operations. For


better understanding of operators, these operators can be classified as:
Operators in C programming

Arithmetic Operators

Increment and Decrement Operators

Assignment Operators

Relational Operators

Logical Operators

Conditional Operators

Bitwise Operators

Special Operators

C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction and multiplication on numerical values (constants and variables).

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

% remainder after division( modulo division)


Example #1: Arithmetic Operators
// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;

c = a+b;
printf("a+b = %d \n",c);

c = a-b;
printf("a-b = %d \n",c);

c = a*b;
printf("a*b = %d \n",c);

c=a/b;
printf("a/b = %d \n",c);

c=a%b;
printf("Remainder when a divided by b = %d \n",c);

return 0;
}

Output

a+b = 13

a-b = 5

a*b = 36

a/b = 2
Remainder when a divided by b=1

The operators +, - and * computes addition, subtraction and multiplication


respectively as you might have expected.

In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.

It is because both variables a and b are integers. Hence, the output is also an
integer. The compiler neglects the term after decimal point and shows answer 2
instead of 2.25.

The modulo operator % computes the remainder. When a = 9 is divided by b = 4,


the remainder is 1. The % operator can only be used with integers.

Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,

a/b = 2.5 // Because both operands are floating-point variables

a/d = 2.5 // Because one operand is floating-point variable

c/b = 2.5 // Because one operand is floating-point variable

c/d = 2 // Because both operands are integers

Increment and decrement operators


C programming has two operators increment ++ and decrement -- to change the
value of an operand (constant or variable) by 1.

Increment ++ increases the value by 1 whereas decrement -- decreases the value by


1. These two operators are unary operators, meaning they only operate on a single
operand.

Example #2: Increment and Decrement Operators


// C Program to demonstrate the working of increment and decrement
operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);

printf("--b = %d \n", --b);

printf("++c = %f \n", ++c);

printf("--d = %f \n", --d);

return 0;
}

Output

++a = 11

--b = 99

++c = 11.500000

++d = 99.500000

Here, the operators ++ and -- are used as prefix. These two operators can also be
used as postfix like a++ and a--. Visit this page to learn more on how increment and
decrement operators work when used as postfix.

C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =
Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b

Example #3: Assignment Operators


// C Program to demonstrate the working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;

c = a;
printf("c = %d \n", c);

c += a; // c = c+a
printf("c = %d \n", c);

c -= a; // c = c-a
printf("c = %d \n", c);

c *= a; // c = c*a
printf("c = %d \n", c);
c /= a; // c = c/a
printf("c = %d \n", c);

c %= a; // c = c%a
printf("c = %d \n", c);

return 0;
}

Output

c = 5

c = 10

c = 5

c = 25

c = 5

c = 0

C Relational Operators
A relational operator checks the relationship between two operands. If the relation is
true, it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.

Operator Meaning of Operator Example

== Equal to 5 == 3 returns 0

> Greater than 5 > 3 returns 1


Operator Meaning of Operator Example

< Less than 5 < 3 returns 0

!= Not equal to 5 != 3 returns 1

>= Greater than or equal to 5 >= 3 returns 1

<= Less than or equal to 5 <= 3 return 0

Example #4: Relational Operators


// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;

printf("%d == %d = %d \n", a, b, a == b); // true


printf("%d == %d = %d \n", a, c, a == c); // false

printf("%d > %d = %d \n", a, b, a > b); //false


printf("%d > %d = %d \n", a, c, a > c); //false

printf("%d < %d = %d \n", a, b, a < b); //false


printf("%d < %d = %d \n", a, c, a < c); //true

printf("%d != %d = %d \n", a, b, a != b); //false


printf("%d != %d = %d \n", a, c, a != c); //true

printf("%d >= %d = %d \n", a, b, a >= b); //true


printf("%d >= %d = %d \n", a, c, a >= c); //false

printf("%d <= %d = %d \n", a, b, a <= b); //true


printf("%d <= %d = %d \n", a, c, a <= c); //true

return 0;

Output

5 == 5 = 1

5 == 10 = 0

5 > 5 = 0

5 > 10 = 0

5 < 5 = 0

5 < 10 = 1

5 != 5 = 0

5 != 10 = 1

5 >= 5 = 1

5 >= 10 = 0

5 <= 5 = 1

5 <= 10 = 1
C Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon
whether expression results true or false. Logical operators are commonly used
in decision making in C programming.

Operator Meaning of Operator Example

Logial AND. True only if all If c = 5 and d = 2 then, expression ((c == 5)


&&
operands are true && (d > 5)) equals to 0.

Logical OR. True only if either If c = 5 and d = 2 then, expression ((c == 5)


||
one operand is true || (d > 5)) equals to 1.

Logical NOT. True only if the If c = 5 then, expression ! (c == 5) equals to


!
operand is 0 0.

Example #5: Logical Operators


// C Program to demonstrate the working of logical operators

#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) equals to %d \n", result);

result = (a == b) && (c < b);


printf("(a == b) && (c < b) equals to %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) equals to %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) equals to %d \n", result);

result = !(a != b);


printf("!(a == b) equals to %d \n", result);

result = !(a == b);


printf("!(a == b) equals to %d \n", result);

return 0;
}

Output

(a == b) && (c > b) equals to 1

(a == b) && (c < b) equals to 0

(a == b) || (c < b) equals to 1

(a != b) || (c < b) equals to 0

!(a != b) equals to 1

!(a == b) equals to 0

Explanation of logical operator program

 (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c >


b) is 1 (true).
 (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
 (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
 (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c <
b) are 0 (false).
 !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is
1 (true).
 !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0
(false).

Bitwise Operators
During computation, mathematical operations like: addition, subtraction, addition and
division are converted to bit-level which makes processing faster and saves power.

Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Visit bitwise operator in C to learn more.

Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:

int a, c = 5, d;

The sizeof operator


The sizeof is an unary operator which returns the size of data (constant, variables,
array, structure etc).

Example #6: sizeof Operator


#include <stdio.h>
int main()
{
int a, e[10];
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
printf("Size of integer type array having 10 elements = %lu
bytes\n", sizeof(e));
return 0;
}

Output

Size of int = 4 bytes

Size of float = 4 bytes

Size of double = 8 bytes

Size of char = 1 byte

Size of integer type array having 10 elements = 40 bytes

C Ternary Operator (?:)


A conditional operator is a ternary operator, that is, it works on 3 operands.

Conditional Operator Syntax


conditionalExpression ? expression1 : expression2

The conditional operator works as follows:


 The first expression conditionalExpression is evaluated first. This expression
evaluates to 1 if it's true and evaluates to 0 if it's false.
 If conditionalExpression is true, expression1 is evaluated.
 If conditionalExpression is false, expression2 is evaluated.

Example #7: C conditional Operator


#include <stdio.h>
int main(){
char February;
int days;
printf("If this year is leap year, enter 1. If not enter any
integer: ");
scanf("%c",&February);

// If test condition (February == 'l') is true, days equal to 29.


// If test condition (February =='l') is false, days equal to 28.
days = (February == '1') ? 29 : 28;

printf("Number of days in February = %d",days);


return 0;
}

Output

If this year is leap year, enter 1. If not enter any integer: 1

Number of days in February = 29

Other operators such as & (reference operator), * (dereference operator) and ->
(member selection) operator will be discussed in C pointers.

41. Types of Handheld Devices, Handheld Device Software,


Handheld Gadgets, What are Handheld Devices
A handheld device is a pocket-sized computing device with a display screen and
input/output interface like an external or touch screen keyboard. Going by this definition
of handheld devices and gadgets many appliances can qualify to be called handheld, like
a mobile phone, PDA, mobile PC, handheld game consoles and so on.
What are Handheld Devices?
All About Handheld Devices and Gadgets
Handheld devices have become a craze in the new millennium and it is difficult to find anyone
today without some or the other handheld gadget in his or her hands (pocket, if you so prefer).
So what exactly is a handheld device? Simply put, a handheld device is a pocket-sized
computing device with a display screen and input/output interface like an external or touch
screen keyboard. Going by this definition of handheld devices and gadgets many appliances can
qualify to be called handheld, like a mobile phone, PDA, mobile PC, handheld game consoles
and so on.
Various popular handheld devices include:
Mobile computers
 Notebook PC
 Ultra-Mobile PC
 Handheld PC
 Personal digital assistant/Enterprise digital assistant
 Graphing calculator
 Pocket computer (largely obsolete)
 Handheld game consoles
 Nintendo DS (NDS)
 Game Boy, Game Boy Color
 Game Boy Advance
 Sega Game Gear
 PC Engine GT
 Pokémon Mini
 NeoGeo Pocket, NeoGeo Color
 Atari Lynx
 Pandora
 GP2X/GP32
 Gizmondo
 PlayStation Portable (PSP)
 N-Gage
Media recorders
Digital still camera(DSC)
Digital video camera (DVC or digital Camcorder)
Digital audio recorders
Media players/displayers
Portable media player
e-book reader
Communication devices
 Mobile phone
 Cordless telephone
 Pager
Benefits of Handheld Devices and Gadgets
Literally speaking, handheld devices have become as popular as oxygen and their popularity
cuts across age, class, sex, nationality, race and ethnicity barriers. Even a roadside tea vendor
can be seen merrily chatting away on his handheld mobile device or the busy executive jotting
down notes on her handheld PDA. Handheld gadgets like the mobile are steadily replacing the
fixed-line telephone and this amazing transition from the wired to the wireless world couldn't have
been possible without the numerous benefits offered by handheld devices.
Office on the go: Today's handheld devices like smartphones and PDA's enable you to literally
take your office with you. You can send and receive emails, browse the net wirelessly at 3G
speeds, access secure office files through VPNs, edit files and much more on your handheld
mobiles. Thus, you are no longer limited by either size or mobility to increase your productivity.
High Convenience: Isn't it far more convenient to just store a quick note on your PDA instead of
rushing to your home and accessing your bulk of a machine? Today's handheld devices can do
all the functions that your traditional computer can do, and more. Today's smartphones like the
iPhone have inbuilt GPS navigation services, which was unthinkable just a few years back.
New Entertainment forms: As technology has progressed and computing prowess has found its
way on small and miniaturised gadgets, new entertainment forms have also emerged. Today
people don't just watch movies on television or in theatres, rather their own notebooks and wide
display mobile phones offer digital quality experience with Dolby surround sound, entertainment
on the move? You bet. Similarly the Nintendo's and PSPs have ensured non-stop action to the
avid gamer.
Breaking the Communication Barrier: Previously snail mail was the only way to keep in touch
with your friends, loved ones and in many cases with your business associates too. Not
anymore. With umpteen forms of communication devices and tools making appearance almost
daily, the communication barrier is well and truly broken. Today you may just ‘tweet' your status
on your mobile, or book a railway ticket through your cell while sitting in a bus. Even real time
chatting on cool hand held appliances and devices has become possible. No place to hide
yourself now.
The Future of Handheld Devices: With handheld devices scaling new heights of popularity
everyday and becoming almost indispensable in our busy lives, it is certainly worth asking, where
are these handheld gizmos headed for? While some take the line that we may have an all
integrated device in the future that serves all our purposes equally well, others beg to disagree.
Prominent among these is Nokia VP Tim Eckersley, who says that no single device would
dominate the humungous handheld market. Rather the honours would be evenly shared between
three device types, data-centric, voice-centric and the hybrid PDA type handheld devices. So
hold on tight and don't fall, the journey promises to be a rocking one.

42. browser
A browser is an application program that provides a way to look at and
interact with all the information on the World Wide Web. The word "browser"
seems to have originated prior to the Web as a generic term for user
interfaces that let you browse (navigate through and read) text files online.

echnically, a Web browser is a client program that uses HTTP (Hypertext


Transfer Protocol) to make requests of Web servers throughout
the Internet on behalf of the browser user. Most browsers support e-mail
and the File Transfer Protocol (FTP) but a Web browser is not required for
those Internet protocols and more specialized client programs are more
popular.

The first Web browser, called WorldWideWeb, was created in 1990. That
browser's name was changed to Nexus to avoid confusion with the
developing information space known as the World Wide Web. The first
Web browser with a graphical user interface was Mosaic, which appeared
in 1993. Many of the user interface features in Mosaic went
into Netscape Navigator. Microsoft followed with its Internet Explorer (IE).

As of September 2006, Internet Explorer is the most commonly used


browser, having won the so-called browser wars between IE and Netscape.
Other browsers include:

 Firefox, which was developed from Mozilla (the open source version of
Netscape).

 Flock, an open source browser based on Firefox and optimized for Web
2.0 features such as blogging and social bookmarking .

 Safari, a browser for Apple computers (at this writing, the third most
popular browser).

 Lynx, a text-only browser for UNIX shell and VMS users.

 Opera, a fast and stable browser that's compatible with most relatively
operating systems.

43. Computer vs. Calculator: What's


the Difference?
Contents [hide]
 1 Primary Difference
 2 Comparison Chart
 3 Definition of Computer
 4 Definition of Calculator
 5 Differences in a Nutshell
 6 Comparison Video
 7 Conclusion

Primary Difference

Electronic devices have become a critical part of our lives, and people depend on them for the
purpose of collecting information and solving problems. The two most important tools in this
category are a computer and calculator that have made our lives easier. Their differences
become clearer through the definition and go as follows. A computer is usually known as a
desktop device where people have the option of using the tool for several purposes. A calculator
gets defined as a small device that performs all the basic arithmetic tasks and operations that
help people in solving complex numbers and numerical.

Advertisement

Comparison Chart

Computer Calculator

An electronic device which is An electronic device used for


capable of receiving information and mathematical calculations and has a
Definition
performing a sequence of operations small keyboard and display screen
by the instructions given that shows the results.

Development 1960’s 1700’s

Price Starts from $300 Starts from $20

Carries out several actions at one


Performance Performs one calculation at one time.
time.

Size Bigger, that fits in a room. Smaller, that fits in the pocket.

Definition of Computer

A computer is usually known as a desktop device where people have the option of using the
tool for several purposes. It gets designed such that people get to use it for regularity and gets
placed in a single location near a desk or table due to its equipment and shape. Initially, most
of these were bigger in size and required larger tables and space to fit in. The sizes have
decreased over time, and now monitors have become slicker, the base is also smaller and more
efficient. Before the making, if a microprocessor the standard desktop device was considered
as a small unit since the original computers were enormous and required a proper room for
their working. A computer usually consists of few main items, and these include a monitor that
displays everything on the screen. A Power cable that connects the computer and the wires
with electricity to run. A keyboard that is used to input data to the computer and has numbers,
alphabets, and other keys to help to send the information. A mouse that is used to click different
items and then open them for viewing. A hard disk on which all the data gets saved and
accessed whenever it is required. A central processing unit that helps in performing all the tasks
and makes communication between the user and the computer easier. A memory that keeps
track of all the actions taken and in some cases, a printer that is used to print the data preset on
the monitor.

Advertisement
Definition of Calculator

A calculator gets defined as a small device that performs all the basic arithmetic tasks and
operations that help people in solving complicated numbers and numerical. Initially, the
devices considered as a calculator were the abacus that developed around 200 BC. Then the
mechanical calculators followed that came into existence in around 17th century. The modern
ones were drawn up in the 1970’s and came in the market parallel to the analog computers.
Different kinds of calculators are present in the market, and the most common ones provide
people with the option of doing the four basic operations that include addition, subtraction,
multiplication and division. The more complex ones have many other facilities such as solving
different matrices, arithmetic operations, geometry, theorems, probability, combination and
much more. Sizes have also changed over time, the first calculators were larger in size and had
few buttons, but now they range from pocket-size to credit card size and have many options in
buttons and others screens. The input is given through a keyboard with buttons for digits and
operations, and some also have buttons to make things simpler. Most of the simple calculators
use one button for one function, but the more excellent ones have the shift key that assigns
another task with the original button. The display shows on the screen which is smaller in size
and has a liquid-crystal display. Other kinds of the display include light-emitting diode and
vacuum fluorescent displays. It also has a memory that stores the most recent calculations and
does not have the facility f saving more data within it.

Advertisement

Differences in a Nutshell

1. A computer is an electronic device which is capable of receiving information and performing


a sequence of operations by the instructions given to produce a result in the form of output. A
calculator is a device used for mathematical calculations and has a small keyboard and display
screen that shows the results.
2. The first computers were developed in the 1960’s whereas the first calculators formulated in
the 17th century.
3. A computer has the capacity of performing the calculations and other logical functions whereas
a calculator only shows arithmetic and geometrical operations.
4. A computer is bigger in size and is not that easy to carry on its own, whereas a calculator is
small and fits in the pocket.
5. A computer is costly and ranges from $300 onwards whereas a calculator is cheaper in
comparison and ranges from $20 on wards.
6. A calculator only carries out one action at a time, and displays result whereas a computer can
perform several functions at one time.
7. A computer has a large memory and stores data in several megabytes whereas a calculator is
smaller in memory and stores one calculation.

Comparison Video

Conclusion
After reading this article, the reader will be able to develop a clear stance on how these two
devices differ from each other, what are the benefits of using them and how they get the
distinction they have gained. This task completes with relevant tables, examples, and
definitions provided along the length

44. what is ascii in computer


ASCII (American Standard Code
for Information Interchange)
ASCII (American Standard Code for Information Interchange) is the most
common format for text files in computers and on the Internet. In an ASCII
file, each alphabetic, numeric, or special character is represented with a 7-
bit binary number (a string of seven 0s or 1s). 128 possible characters are
defined.

UNIX and DOS-based operating systems use ASCII for text files. Windows
NT and 2000 uses a newer code, Unicode. IBM's S/390 systems use a
proprietary 8-bit code called EBCDIC. Conversion programs allow different
operating systems to change a file from one code to another.

ASCII was developed by the American National Standards Institute (ANSI).

ASCII stands for “American Standard Code for Information Interchange”

As it says, it’s a Code, and it also explains that this Code is the American
Standard for Information Interchange.

As you may know, computers only work with HIGH(1) and LOW(0) electrical states,
known as bits, with correspond to mathematical Base 2 numbers.

Numbers are easy to store using bits, as for example, ‘8’ would be ‘1000’ at Base 2.

But graphically, you don’t have ‘8’, neither ‘0’ or ‘1’, bits in fact are just states: “On”
when powered, “Off” when not, so how could we display characters on a screen?

Skipping how they did the screen printing itself, ASCII is a Code that tells to the
display what he should print given an input.

This Code output is, internally, a byte (8 bits) that are simple regular numbers at
Base 2 (as ‘00001000’ stands for 8 at Base 10).

So what ASCII in fact is: The mapping of Binary Numbers that correspond to
Actions (that may be an action to Display a Graphical Representation of
an Character or, for example, Remove Previous Character, as does
Backspace - ASCII Code ‘00001000’)

Here is the ASCII Table:

There are many characters on Keyboard which we can type and see and many other
which can't see. Computer being a digital machine only understands and represents
Binary information. It Does not know what does character 'T' means. Inside the
computer every character is represented by a sequence of binary digits. ASCII is a
character representation scheme based on 7 bits. That is, every character in this
scheme can be represented as a unique combination of 7 binary digits. ASCII table tell
us what is the binary sequence against any character that we are familiar of. for
example 'a' has its own binary sequence representation which is 01100001 (97 in
decimal) and so on. because of it's seven bits limitation it can only represent 128
unique characters. some other character sets also exist which uses more bit and hence
capable of representing even every possible character that exists in any language in the
world e.g extended ASCII table and Unicode which is among one of the most famous

45. Multi-dimensional Arrays in C


C programming language allows multidimensional arrays. Here is the
general form of a multidimensional array declaration −
type name[size1][size2]...[sizeN];

For example, the following declaration creates a three dimensional integer


array −
int threedim[5][10][4];

Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array.
A two-dimensional array is, in essence, a list of one-dimensional arrays.
To declare a two-dimensional integer array of size [x][y], you would write
something as follows −
type arrayName [ x ][ y ];

Where type can be any valid C data type and arrayName will be a valid
C identifier. A two-dimensional array can be considered as a table which
will have x number of rows and y number of columns. A two-dimensional
array a, which contains three rows and four columns can be shown as
follows −

Thus, every element in the array a is identified by an element name of the


form a[ i ][ j ], where 'a' is the name of the array, and 'i' and 'j' are the
subscripts that uniquely identify each element in 'a'.

Initializing Two-Dimensional Arrays


Multidimensional arrays may be initialized by specifying bracketed values
for each row. Following is an array with 3 rows and each row has 4
columns.

int a[3][4] = {

{0, 1, 2, 3} , /* initializers for row indexed by 0 */

{4, 5, 6, 7} , /* initializers for row indexed by 1 */

{8, 9, 10, 11} /* initializers for row indexed by 2 */


};

The nested braces, which indicate the intended row, are optional. The
following initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array


Elements
An element in a two-dimensional array is accessed by using the subscripts,
i.e., row index and column index of the array. For example −
int val = a[2][3];

The above statement will take the 4th element from the 3rd row of the
array. You can verify it in the above figure. Let us check the following
program where we have used a nested loop to handle a two-dimensional
array −
Live Demo

#include <stdio.h>

int main () {

/* an array with 5 rows and 2 columns*/

int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

int i, j;

/* output each array element's value */

for ( i = 0; i < 5; i++ ) {

for ( j = 0; j < 2; j++ ) {

printf("a[%d][%d] = %d\n", i,j, a[i][j] );

}
return 0;

When the above code is compiled and executed, it produces the following
result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

As explained above, you can have arrays with any number of dimensions,
although it is likely that most of the arrays you create will be of one or two
dimensions.

C Programming Multidimensional
Arrays
In this article, you will learn to work with multidimensional arrays (two
dimensional and three dimensional array).
In C programming, you can create an array of arrays known as multidimensional
array. For example,

float x[3][4];

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can
think the array as table with 3 row and each row has 4 column.
Similarly, you can declare a three-dimensional (3d) array. For example,

float y[2][4][3];

Here,The array y can hold 24 elements.

You can think this example as: Each 2 elements have 4 elements, which makes 8
elements and each 8 elements can have 3 elements. Hence, the total number of
elements is 24.

How to initialize a multidimensional


array?
There is more than one way to initialize a multidimensional array.

Initialization of a two dimensional array


// Different ways to initialize two dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};

Above code are three different ways to initialize a two dimensional arrays.

Initialization of a three dimensional array.


You can initialize a three dimensional array in a similar way like a two dimensional
array. Here's an example,
int test[2][3][4] = {

{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },

{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }

};

Example #1: Two Dimensional Array to store and


display values
// C program to store temperature of two cities for a week and display
it.
#include <stdio.h>

const int CITY = 2;


const int WEEK = 7;

int main()
{
int temperature[CITY][WEEK];
for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j) {
printf("City %d, Day %d: ", i+1, j+1);
scanf("%d", &temperature[i][j]);
}
}

printf("\nDisplaying values: \n\n");


for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d = %d\n", i+1, j+1,
temperature[i][j]);
}
}
return 0;
}

Output

City 1, Day 1: 33

City 1, Day 2: 34

City 1, Day 3: 35

City 1, Day 4: 33

City 1, Day 5: 32

City 1, Day 6: 31

City 1, Day 7: 30

City 2, Day 1: 23

City 2, Day 2: 22

City 2, Day 3: 21

City 2, Day 4: 24

City 2, Day 5: 22

City 2, Day 6: 25

City 2, Day 7: 26

Displaying values:
City 1, Day 1 = 33

City 1, Day 2 = 34

City 1, Day 3 = 35

City 1, Day 4 = 33

City 1, Day 5 = 32

City 1, Day 6 = 31

City 1, Day 7 = 30

City 2, Day 1 = 23

City 2, Day 2 = 22

City 2, Day 3 = 21

City 2, Day 4 = 24

City 2, Day 5 = 22

City 2, Day 6 = 25

City 2, Day 7 = 26

Example #2: Sum of two matrices using Two


dimensional arrays
C program to find the sum of two matrices of order 2*2 using multidimensional
arrays.

#include <stdio.h>
int main()
{
float a[2][2], b[2][2], c[2][2];
int i, j;

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
printf("Enter a%d%d: ", i+1, j+1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
printf("Enter b%d%d: ", i+1, j+1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
c[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

for(i=0; i<2; ++i)


for(j=0; j<2; ++j)
{
printf("%.1f\t", c[i][j]);

if(j==1)
printf("\n");
}
return 0;
}

Ouput

Enter elements of 1st matrix

Enter a11: 2;

Enter a12: 0.5;

Enter a21: -1.1;

Enter a22: 2;

Enter elements of 2nd matrix

Enter b11: 0.2;

Enter b12: 0;

Enter b21: 0.23;

Enter b22: 23;

Sum Of Matrix:

2.2 0.5

-0.9 25.0
Example 3: Three Dimensional Array
C Program to store values entered by the user in a three-dimensional array
and display it.

#include <stdio.h>
int main()
{
// this array can store 12 elements

int i, j, k, test[2][3][2];

printf("Enter 12 values: \n");

for(i = 0; i < 2; ++i) {


for (j = 0; j < 3; ++j) {
for(k = 0; k < 2; ++k ) {
scanf("%d", &test[i][j][k]);
}
}
}

// Displaying values with proper index.

printf("\nDisplaying values:\n");

for(i = 0; i < 2; ++i) {


for (j = 0; j < 3; ++j) {
for(k = 0; k < 2; ++k ) {
printf("test[%d][%d][%d] = %d\n", i, j, k,
test[i][j][k]);
}
}
}
return 0;
}

Output

Enter 12 values:

10

11

12

Displaying Values:

test[0][0][0] = 1

test[0][0][1] = 2
test[0][1][0] = 3

test[0][1][1] = 4

test[0][2][0] = 5

test[0][2][1] = 6

test[1][0][0] = 7

test[1][0][1] = 8

test[1][1][0] = 9

test[1][1][1] = 10

test[1][2][0] = 11

test[1][2][1] = 12

S-ar putea să vă placă și