Vous êtes sur la page 1sur 50

1. Define the importance/purpose of computer.

 Solving numerical problems.


 Storing and retrieving information
 Creating and displaying documents and pictures.

2. Define : Flow chart


A Flowchart is a pictorial representation of an algorithm. It is often used by programmer
as a program planning tool for organizing a sequence of step necessary to solve a problem by a
computer.

3. Write the syntax with example to FOR loop.


for(expression-1; expression-2; expression-3)
{
//set of statements
}

When control reaches for expression-1 is executed first. Then following


expression-2, and if expression-2 evaluates to non-zero set of statements and
expression-3 is executed, follows expression-2.

4. Define: goto statement.


“goto” is a jumping statement in c language, which transfer the program's control
from one statement to anotherstatement (where label is defined). goto can transfer the
program's within the same block and there must a label, where you want to transfer
program's control.

5. Define array and function.

Array :
An array is a group of similar data types stored under a common name. An array
is used to store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
Example:
int a[10];
Here a[10] is an array with 10 values.

Function :
A function is a group of statements that together perform a task. Every C program
has at least onefunction, which is main(), and all the most trivial programs can define
additional functions. ... Afunction declaration tells the compiler about afunction's name,
return type, and parameters.

6. What are the storage classes available in C?


A storage class defines the scope (visibility) and life time of variables and/or functions
within a C Program. There are following storage classes which can be used in a C Program
 auto
 register
 static
 extern
7. Define Union.
A union is a special data type available in C that enables you to store 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 multi-purpose.

8. What is a pointer to a function? Give the general syntax.


In C, it is also possible to define and use function pointers, i.e. pointer variables
which point to functions. Function pointers can be declared, assigned values and then
used to access the functions they point to.
<return_type> (*<pointer_name>) (function_arguments);
9. Define macros.
A macro is a name given to a block of C statements as a pre-processor directive.
Being a pre-processor, the block of code is communicated to the compiler before entering
into the actual coding (main () function). A macro is defined with the preprocessor
directive, #define.

10. Define fseek() and fopen().

fseek( ):

In the C Programming Language, the fseek function changes the file position
indicator for the stream pointed to by stream.
Syntax

int fseek(FILE *stream, long int offset, int whence);

fopen( )

C fopen function is used to open an existing file or create a new file.

Syntax:

FILE *fopen( const char * filePath, const char * mode );


11. a) Explain the characteristics of computer.

The main characteristics of computers are:

a) Speed

b) Storage

c) Accuracy

d) Versatility

e) Automation

f) Diligence

g) Reliability

a) Speed :

Computers are capable of carrying out the task with enormous speed. Today’s computers,
according to their class, can perform from 4 MIPS (Millions of instructions per second) to
100MIPS. What may take days for manual calculations may take only a few hours for
computers toperform. Inside the computer the information signal travels at incredible
electronic speed.
b) Storage:

Computers can store enormous quantity of information. Which is expressed in terms of


Kilobytes (or) Mega Bytes (MB) or Gega Bytes (GB). It is achieved through its ‘Main
memory’ or ‘Primary storage’ and through ‘auxiliary storage’ or ‘Secondary storage’. The
Hard disks Floppy disk, Compact Disc(CD) and Magnetic Tape storage are examples of
secondary storages.These large volumes of storage occupy much lesser space compared to
paper documents and this aspect of computers makes them more powerful.
c) Accuracy:

The accuracy of a Computer is consistently high. In fact, this quality of the computers
make them indispensable in various fields such as Scientific Research, Space Research,
Weather Predictions and many other areas where precision of a high order is required. The
accuracy of the computer is best achieved by programming them in the most efficient
manner. When it comes to very complex mathematical or scientific problem the computer’s
accuracy has no substitute.
d) Versatility:

Computers are versatile in that they can perform almost any task, provided they are given
the appropriate logical steps. For example, they are capable of performing wide ranging
tasks such as construction of a payroll, inventory management in a factory, hotel billing,
hospital management, banking applications and any imaginable task in every walk of life.
e) Automation:

The biggest advantage of computers is that it is automatic in its operation. Once a


programming logic is initiated the computer performs repeated operations without human
interventions until program completion.

f) Diligence:

Computers are machines and that do not get tired or ‘lose concentration’ like human
beings. If a large number of calculations say million calculations are to be performed the
resultant output will remain exactly the same even if operations are repeated any number of
times. But when a human being is asked to do the same job this consistency cannot be
achieved. Thus for those who want consistent and continuous standard output, computer’s
‘diligence’ is of great help.
g) Reliability:

The computers give very accurate results with predetermined values. They correct and
modify the parameters automatically, giving suitable signals. They give formatted results
with high degree of precisions.
11.b) What are the Input and output devices and what are their functions?

Input Devices :

The input unit is used for entering the data and instruction into the computer for
performing computation of the data. The input unit accepts or reads the list of instructions
and data and converts these instructions and data in computer acceptable form. It supplies
the converted instructions and data to the computer for further processing. The devices
used for this purpose are called as Input Devices. Key Board and Mouse are the important
input devices used in our offices. Light pen, Joy stick, tracker ball, Touch pad, Scanner
and Pointing stick are some of the Input Devices.

a) Key Board:

The keys in Computer keyboards are almost similar to the keys in a typewriter but
in addition there are some special operational keys carrying special symbols that help us
in giving instructions to computer.

b) Mouse:

Mouse is an essential component in the modern computers which use Windows


and other Graphical User Interface [GUI] applications. Mouse is a small service in which
a small ball is kept inside and the ball touches the pad through a hole at the bottom of the
mouse.
When the mouse is held in hand pushed along a flat surface [mouse pad], the ball
inside the mouse rolls and this movement of the ball is converted into electronic signals
and sent to the computer, now we get advanced versions of mouse like optical mouse,
scroll mouse cordless mouse etc. using the mouse the cursor can be moved in any
direction. The mouse is used for selecting part or full text or object, and also for dragging
and dropping the selected text or object.
c) Uses of scanners:

Optical Character Recognition OCR – We can convert text based document


images into text that can be edited by a word – processing software. Enrich our
presentations and documents by adding images. Convert hard-copy images or documents
into a fax format for faxing or for record purpose. Add scanned images to our e-mil to
enrich the content.

Type of scanners:

 Flatbed Scanner,
 Sheet fed,
 Handheld,
 Card scan.

Flatbed Scanner

The flat bed scanner as shown in the illustration is one of the most commonly used and
most recommended scanners. This scanner allows the user to place a full piece of paper,
book, magazine, photo or any other object onto the bed of the scanner and have the
capability to scan that object. Flatbed scanner A sheet containing text can be scanned
using the scanner and saved as an image file. There is software to convert the image file
once again into a text file.

Sheet fed scanner:

This scanner allows us to scan pieces of paper. The sheet fed scanner is a less expensive
solution when compared to the flatbed scanner.

Handheld Scanner:

The handheld scanner allows the user to drag over select sections of pages, books,
magazines, and other objects scanning only sections. However it can be tedious to drag
the handheld correctly which can cause distortion in the image being scanned.
Card scan Scanner:

This scanner is mainly used to scan visiting cards for creating database of the addresses.

d) Punched cards

Punched cards are still in use as medium for recording data and instructions in the form
of punched holes to denote and then they are sequentially read by the card Reader. The card
Reader sends the data and instructions to the CPU to process them. The punched cards used for
data processing are made generally of 80 columns and 12 rows. Today 96 columns cards are
available. In these cards a hole in punched to represent the binary l. The absence of a hole
represents binary 0. If a card is punched wrongly, it cannot be corrected. Further, the punched
cards are not reusable, i.e., cannot be used for any other data. Many numbers of cards are
required for the computer programs. Such a collection of cards is called a deck. Each card has
the left top corner cut to identify the arrangement of the cards is correct or not. The cards are
read by a Unit called a card Reader. The punched cards are placed in the Read Hopper after
verification. On receiving the command from the control unit the device moves the cards one by
one over two sub-devices. One of which, sense the punched holes (0s and 1s) and transcribes the
pulses to the CPU. Then the output is given as per user specification.

e) Paper Tapes

The punched paper tape is a continuous strip of a paper about one inch wide and up to
300 meters long. The characters are recorded on tape, which may be 5 or 8 as per the design of
the tape. These punched positions are called as channels. It is the oldest media, of input and
output media. Her also, a hole represent 1 and its absence represents 0. Data from the tape is read
through a Tape Recorder per second. The tape comes in various forms viz., Oil paper, dry paper,
metalized paper and laminated paper.

f) Magnetic Tape

Because of the problems faced in the paper media, magnetic substances have come. First
among these was the magnetic tape. This is also a sequential media for normally between 1.25-
2cms. Wide and up to 900 meters long. It is made of plastic with a metallic magnetic oxide
coating on one side. Generally, data is recorded on either a 7 parallel-rack-tape or on a 9 parallel
track-tape. Writing on and reading from the tape is done with the assistance of READ/WRITE
head. The number of characters per inch length of tape stored is called the 'density' of the tape.
This varies from 550 to 1600 or even 16K. The 9 Track tapes have the higher densities.

g. Magnetic Disk
It is yet another step in the evolution of Input/Output devices. The Magnetic Disk has an
advantage over the punched cards and Magnetic Tapes i.e., the data stored on a disk can be read
randomly while in the magnetic tape, the data are read sequentially. Random access is that the
particular record in the file can be detected directly and the access time is saved. In Magnetic
disk the record is accessed in a fraction of second i.e., less than 0.01 sec. The disk varying in
diameter are generally coated on both sides with magnetic oxide. Each surface of the disk is
divided into a number of sectors, called storage segments. The storage segment is a specific
portion of a specific side of the disk. A segment can store one or more record of a file, which will
vary according to the size of the record. While searching, a particular record can randomly be
selected and directly accessed, because, each storage segment is uniquely marked by an address
with side number, track number, sector number etc.

h. Joysticks and Trackballs


Joysticks provide an alternative method for feeding the computer visually interesting
data. When you move the joystick, cursor on the screen moves in a corresponding way. A
trackball is a plastic sphere mounted in a socket so that it is free to rotate in any direction.

i. Touch Screens
Touch Screens are another favorite "user friendly" method for feeding data into
computer. User can command the computer to perform various useful tasks simply by touching
specific sectors of the screen with their forefingers. The computer senses the Location of the
finger in various ways.
Output Devices :

The results of the data processed by the computer are available in electronic signals. The
output unit converts these signals into a form which could be easily understood by us. The
output is usually given either on the screen by visual display unit/monitor or in a printed form by
printers.

a) Monitor (Visual Display Unit or Screen)


The monitor is made up of cathode-ray tube CRT due to which it also called C.R.T
terminal. The screen consists of horizontal and vertical sweep circuits similar to T.V. sets. The
screen’s inside is coated with dots of phosphor called pixel and can be used for games or
graphics or displaying the results of a calculation done by computer. The more the number of
pixel or dots in a screen, the better will be the capability of computer to display an information.
This capability is known as resolution. The characters typed with the keyboard are displayed on
the screen. We can thus verify whether the programs we enter into computer is corrector not.

b. Printer
Printer is the most commonly used output device. It is used to prepare permanent
documents in human – readable form [hard copy]. The are several types of printers that are
designed for different types of applications.

Printers are of two types-impact and non impact. Impact printers use the familiar
typewriter approach of hammering a typeface against paper and inked ribbon. Non- impact
printers do not hit or impact a ribbon to print. They use thermal, electrostatic, chemical and
inkjet technologies.
Depending on their speed and approach of printing, printers are also classified as
character printers, and page printers.
Types of Printers:
1. Dot Matrix Printer:
In this printer characters to print are made up of a finite number of dots and so, the print head
consists of an array of pins. Characters to be printed are made up of a finite number of dots and
so, the printer. The character code is decoded by the printer electronics and activates the
appropriate pins in the print head.Many dot matrix printers are bi-directional. i.e., they print from
left to right as well as from right to left on return. This enhances the speed of printing. The
printing speed is around 300 characters per second.

2. Line Printer:
Unlike a dot matrix printer, line printer prints a complete line at a time. Two types of line
printers are available.
3. Drum Printer
It consists of cylindrical drum. The characters to be printed are embossed on its surface.
4. Chain Printer:
It has a steel band on which the character sets are embossed. Printing speed varies from
150 lines to 2500 lines per minute with 96 to 160 characters on a 15 inch line. Six to eight lines
per vertical inch are printed. Usually 64 and 96 character sets are used with English letters.

5. Inkjet Printer:
It consists of print heard, which has a number of small holes of nozzles. Individual holes
are heated very rapidly by an integrated circuit resistor. When the resistor heats up, the
ink near it vaporizes and is ejected through the nozzle and makes a dot on paper placed near the
head. A high –resolution inkjet printer has around 50 nozzles within a height of 7mm and can
print with a resolution of more than 300 dots per inch. Latest inkjet printers have multimedia
heads, one per color , which allow color printing. The printing speed is
around 120 characters per second.

6. Laser Printers:
In laser printer an electronically controlled laser beam traces out the desired character to
be printed on a photo conductive drum § The drum attracts an ink toner on to the exposed areas.
This image is transferred to the paper, which comes in contract with the drum.
Very fast printers print 10,000 lines per minute. These printers give excellent outputs and
can print a variety of fonts.
Low speed laser printers, which can print 4 to 16 pages per minute, are now very popular.
12. a) Write the basic structure of C Program with example.

Documentation Section
Link Section
Definition Section
Global Declaration Section
main()
{
Declaration Section
Executable part
}
Subprogram section
Function 1
Function 2
.
.
function n

The Documentation Section consists of a set of comment lines giving the name of
the program and other details.

The Link Section provides instructions to the compiler to link functions from the
system library.

The Definition Section defines all symbolic constants.

The Global Declaration Section: There are some variables and those variables are
declared in this section that is outside of all functions.

main() function: Every C program must have one main function section. This
section contains two parts, declaration and executable part.

Declaration Part declares all the variables used in the executable part.

There should be at least one statement in the executable part which contains
instructions to perform certain task. The declaration and executable part must appear
between the opening and closing braces. All statements in the declaration part should end
with the semicolon.
The Subprogram Section contains all the user defined functions that are called in
the main function.

Example Program:
12. b) Write the Scanf() and Printf() functions in C with one example program.

Scanf() function:

In C programming language, scanf() function is used to read character, string,


numeric data from keyboard Consider below example program where user enters a
character. This value is assigned to the variable “ch” and then displayed. Then, user
enters a string and this value is assigned to the variable “str” and then displayed.

Syntax :

scanf("%d", &b);
The scanf function uses the same placeholders as printf:
int uses %d
float uses %f
char uses %c
character strings use %s

Printf() function

In C programming language, printf() function is used to print the “character,


string, float, integer, octal and hexadecimal values” onto the output screen. We use
printf() function with %d format specifier to display the value of an integer variable.

Similarly %c is used to display character, %f for float variable, %s for string


variable, %lf for double and %x for hexadecimal variable.

To generate a newline,we use “\n” in C printf() statement.

Syntax :
Printf(“%d”,a);
Ex :
C program to add two numbers

#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter the first value:");
scanf("%d", &a);
printf("Enter the second value:");
scanf("%d", &b);
c = a + b;
printf("%d + %d = %d\n", a, b, c);
return 0;
}

13. a) Distinguish between Call by value Call by reference.

Call by value Call by reference

a) In call by value, the value of actual agreements is a) In call by reference, the address of actual
passed to the formal arguments and the operation is argument values is passed to formal argument
done on formal arguments. values.
b) Formal arguments values are photocopies of actual b) Formal arguments values are pointers to the
arguments values. actual argument values.
c) Changes made in formal arguments valued do not c) Since Address is passed, the changes made in
affect the actual arguments values. the both arguments values are permanent.
13. b) Write notes on arrays and strings.

An array is a sequential collection of variables of same data type which can be


accessed using an integer as index, that generally starts from 0. It stores data elements in
a continuous memory location. Each element can be individually referenced with its
respective index.

1-Dimensional array:
It is a linear array that stores elements in a sequential order. Let us try to
demonstrate this with an example: Let us say we have to store integers 2, 3, 5, 4, 6, 7. We
can store it in an array of integer data type.

dataType nameOfTheArray [sizeOfTheArray];


int Arr[6];

To store the above elements in the array:

dataType nameOfTheArray [ ] = {elements of array };


int Arr [ ] = { 2, 3, 5, 4, 6, 7 };

Multidimensional array:

It can be considered as an array of arrays. The most commonly used


multidimensional array is 2-dimensional array. It stores the elements using 2 indices,
which give the information, in which row and which column a particular element is
stored. A 2D array is essentially a matrix.
Declaration:

char A[ 3 ] [ 2 ] ;

String :

A string is essentially a sequence of characters. In other words, we can say that


string is an array of character data type. An instance of a string is called a string literal .
They are enclosed in double quotes (“”) . For example “HackerEarth” is a called a string
literal. There are two types of string in C++: C-style string String class type
Sstrings are one dimensional array of characters. However they have a special
property, they end with a null character (‘\0’) to signify the end of the string.

Declaration:
char str[ 6 ];
Initialization: A character array can be initialized like any other normal array
char str[ 6 ] = { ‘H’, ‘E’, ‘L’, ‘L’, ‘O’ };
or it can directly be initialized using a string literal
char str[ ] = “HELLO”;
str is a string which has an instance (string literal) “HELLO”. In spite of only 5
characters, the size of the string is 6, because the null character represents the end of the
string. The null character is automatically added by the compiler as long as the size of the
array is at least one larger than the size of the string. It is not mandatory that the array
size (N) be exactly greater than the size of the string (n) by 1 i.e. N >= n + 1

14. a) Explain pointers and strings.

Pointer :

Pointer is a variable which holds the address of another variable.


Pointer Declaration:
datatype *variable-name;
Example:
int *x, c=5;
x=&a;
Strings:
The group of characters, digit and symbols enclosed within quotes is called as
Stirng (or) character Arrays. Strings are always terminated with „\0‟ (NULL) character.
The compiler automatically adds „\0‟at the end of the strings.
Example:
char name[]={„C‟,‟O‟,‟L‟,‟L‟,‟E‟,‟G‟,‟E‟,‟E‟,‟\0‟};

POINTERS TO DISPLAY A STRING

You’re most likely familiar with displaying a string in C, probably by using either
the puts() or printf() function. Strings, too, can be displayed one character a time by
plodding through an array.

HOW TO DECLARE A STRING BY USING A POINTER

Consider A Pointer Announces a String.

A POINTER ANNOUNCES A STRING

#include <stdio.h>
int main()
{
char *sample = "From whence cometh my help?n";
while(putchar(*sample++))
;
return(0);
}

In A Pointer Announces a String, the string that’s displayed is created by


initializing a pointer. It’s a construct that looks odd, but it’s something you witness often
in C code, particularly with strings.
14. b) Define: structure. How structure members are accessed?

Introduction to Structure

Structure is a user-defined datatype in C language which allows us to combine data of


different types together. Structure helps to construct a complex data type which is more
meaningful. It is somewhat similar to an Array, but an array holds data of similar type only.
But structure on the other hand, can store data of any type, which is practical more useful.

Defining a structure

struct keyword is used to define a structure. struct defines a new data type which is a
collection of primary and derived datatypes.
Syntax:
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];

Example :

struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};

Accessing Structure Members

Structure members can be accessed and assigned values in a number of ways.


Structure members have no meaning individually without the structure. In order to assign
a value to any structure member, the member name must be linked with the structure
variable using a dot[ . ]operator also called period or member access operator.

For example:
#include<stdio.h>
#include<string.h>

struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};

int main()
{
struct Student s1;
s1.age = 18;
strcpy(s1.name, "Viraaj");
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);
return 0;
}
15. a) Write bitwise operators in c.

In arithmetic-logic unit (which is within the CPU), mathematical operations like:


addition, subtraction, multiplication and division are done in bit-level. To perform bit-
level operations in C programming, bitwise operators are used.

Operators Meaning of operators


& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise complement
<< Shift left
>> Shift right

Bitwise AND operator &

The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If


either bit of an operand is 0, the result of corresponding bit is evaluated to 0.

Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is
1. In C Programming, bitwise OR operator is denoted by |.

Bitwise XOR (exclusive OR) operator ^


The result of bitwise XOR operator is 1 if the corresponding bits of two operands
are opposite. It is denoted by ^.

Bitwise complement operator ~


Bitwise compliment operator is an unary operator (works on only one operand). It
changes 1 to 0 and 0 to 1. It is denoted by ~.
15. b) How to open and close the file stream in c.

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

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 file, and access
mode can have one of the following values −

S.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 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 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.

16. Explain in detail about the classification of computer system.

According to functionality, Type of computers are classified as :

Analog Computer

An analog computer (spelt analogue in British English) is a form of computer


that uses continuous physical phenomena such as electrical, mechanical, or hydraulic
quantities to model the problem being solved.

Digital Computer

A computer that performs calculations and logical operations with quantities


represented as digits, usually in the binary number system

Hybrid Computer (Analog + Digital)

A combination of computers those are capable of inputting and outputting in both


digital and analog signals. A hybrid computer system setup offers a cost effective method
of performing complex simulations.

Super Computer

The fastest and most powerful type of computer Supercomputers are very
expensive and are employed for specialized applications that require immense amounts of
mathematical calculations. For example, weather forecasting requires a supercomputer.
Other uses of supercomputers include animated graphics, fluid dynamic calculations,
nuclear energy research, and petroleum exploration.

The chief difference between a supercomputer and a mainframe is that a


supercomputer channels all its power into executing a few programs as fast as possible,
whereas a mainframe uses its power to execute many programs concurrently.

Mainframe Computer

A very large and expensive computer capable of supporting hundreds, or even


thousands, of users simultaneously. In the hierarchy that starts with a simple
microprocessor (in watches, for example) at the bottom and moves to supercomputers at
the top, mainframes are just below supercomputers. In some ways, mainframes are more
powerful than supercomputers because they support more simultaneous programs. But
supercomputers can execute a single program faster than a mainframe.

Mini Computer

A midsized computer. In size and power, minicomputers lie between workstations


and mainframes. In the past decade, the distinction between large minicomputers and
small mainframes has blurred, however, as has the distinction between small
minicomputers and workstations. But in general, a minicomputer is a multiprocessing
system capable of supporting from 4 to about 200 users simultaneously.

Micro Computer or Personal Computer

• Desktop Computer: a personal or micro-mini computer sufficient to fit on a desk.

• Laptop Computer: a portable computer complete with an integrated screen and


keyboard. It is generally smaller in size than a desktop computer and larger than a
notebook computer.

• Palmtop Computer/Digital Diary /Notebook /PDAs: a hand-sized computer.


Palmtops have no keyboard but the screen serves both as an input and output device.
Workstations

A terminal or desktop computer in a network. In this context, workstation is just a


generic term for a user's machine (client machine) in contrast to a "server" or
"mainframe."

17. Describe the control statements in C with example.

CONTROL STATEMENTS

The statements that are used to control the flow of execution of statements are
known as conditional control statements.

Conditional statements are divided into three types:-

 Conditional
 Unconditional
 Looping

Conditional Control statements:

A ‘c ’program is a set of statements which are normally executed sequentially in


the order in which they appear. This happens when no options (or) no repetitions of
certain calculations are necessary .however in practice we have a number of situations
where we may have to change the order of execution of statements until certain specified
conditions are met.

This involves a kind of “decision making” to see whether a particular condition


has occurred (or0 not & then direct the computer to execute certain statements
accordingly.

‘C’ language passes such decision making capabilities & supports the following
statements known as conditional (or) decision making statements.

 if statements
 switch statement
 conditional operator statement

If statement:

The 'if' statement is a powerful decision making statement and is used to control
the flow of execution of statements. It is basically a two way decision statement and is
used in conjunction with as expression .
It takes the following form:-

if (test expression )

It allows the computer to evaluate the expression first & then depending on
whether the value of the expression (relation(or)condition) is 'true'(non-zero)or
'false'(zero),it transfer the control to a particular statement .This point of program has two
paths follow, one for true condition & the other for the false condition.

The if statement may be implemented in different forms depending on the


complexity of condition to be tested

1. simple if statement
2. if …else statement
3. nested if …else statement
4. else if ladder

1. Simple if statement:

General form:

if (test expression)
{
Statement–block;
}
Statement –x;

Ex:

main()
{
int a, b,max;
printf("Enter any 2 values");
scanf("%d%d",&a,&b);
max=a;
if(max< b)
{
max =b;
}
printf("max =%d",max);
getch();
}
2. If-else statement:
Syntax:
if(test expression)
{
True block statement ;
}
else
{
false block statement;
}
Statement-x;

Example: To check whether given no is even (or) odd

main()

int n:

clrscr();

printf("enter any number");


scanf("%d",&n);

if(n%2==0)

printf("even number is even");

else

printf("Given nmber is odd");

getch();

3. Nested if---else statement:

When a series of decision are involved, we may to have to use more than if-----else
statement in nested form as follows:

if(test condition)

if(test condition)

Statement-1;

else

Statement-2;

else

Statement-3;

Statement-x;
}

Ex: Program to find max of 3 numbers.

#include < stdio.h>

void main( )

int a,b,c,max;

printf("enter any 3 numbers");

scanf("%d%d%d",&a,&b,&c);

if(a>b)

{
if(a>c)

max=a;

else

max=c;

else

if(b>c)

max=b;

else

max=c;

printf ("max=%d",max); }

THE ELSE IF LADDER:

There is another way of putting 'if's together when multipath decisions are involved. A
multipath decision is a chain of 'if's' in which the stmt associated with each else is an if.

Loops

The versatility of computer lies in its ability to perform as set of instructions repeatedly.
This involves a repeating some position of a program either a specified number of a time or
until a particular condition is being satisfied. This repeative operation is done through a loop
control structure.

There are 3 methods by way of which we can repeat a part of a program. They are

1. Using a while statement


2. Using a do while statement
3. Using a for while statement
While loop:

It is a conditional control loop statement The while is an entry controlled loop statement.
In entry controlled loop, the control conditions are tested before start of the loop execution. If
the conditions are not satisfied then the body of the loop will not be executed.

General form

While (test condition) { Body of the loop }

The condition being tested may use relational or logical operators.

Ex: program to print "n" natural numbers while using loop.

main()

int n, i=1;

clrscr ();

printf ("enter the values of n");

scanf ("%d", &n);

printf ("natural numbers from 1 to %d ", n);

while (i<=n)

printf ("%d\ t", i);

i++;

getch ();

}
do while :

On some occasions it might be necessary to execute the body of the loop before test is
performed. Such situations can be handled with the help of do while statement.

General form:

do

Body of the loop

} while (test condition);

On reaching the do statement the program proceeds to evaluate the body of the loop first.
At the end of loop, the test condition in the while statement is evaluated. If the condition is true,
the program continues to evaluate the body of loop once again. This program continues as long
as the condition is true. When the condition becomes false, the loop while be terminated and the
control goes to the statement that appears immediately after while statement.

Since, the test condition is evaluated at the bottom of the loop,the do while construct provides
an exit-controlled loop and the form the body of the loop is always executed at least once.
Example: To print ‘n’ natural number using do while

#include < stdio.h>

#include < conio.h>

void main()

int n,i=1;

clrscr();

printf("enter any number");

scanf("%d",&n);

printf("natural numbers from 1 to %d",n);

do

printf("%d\t",i);

i++;

}while(i<=n);

getch();

FOR Loop :

The for loop is another entry controlled loop that provides a more concise loop control
structure.

The general form of for loop is

for(initialization; test condition; increment)

Body of the loop

}
The initializing control variables using assignment statement such as i=1&count=0,we
can initialize control variables. The variables i & count are known as

LOOP CONTROL VARIABLES

The value of control is tested using the test condition. The test condition is a relational
expression, such as i<10 determine, when the loop will exit. If condition is true ,the body will
executed otherwise the execution continues with the statement that immediately follows the
loop.

When the body of the loop is executed, the control is transferred back to for statement
after evaluating the last statement in the loop. Now the control variable is incremented using
assignment statement such as i=i+1 and the new value of control variable is again tested to see
whether the loop condition is satisfied or not.

Ex: To print 1 to 100 digits

#include < stdio.h>

#include < conio.h>

void main()

clrscr();

for(i=1,i<=100,i++)

printf("%d/t",i);

getch();

}
UNCONDITIONAL CONTROL STATEMENTS

BREAK

It is used to terminate a switch statement.

BREAK is a keyword that allows us to jump out of a loop instantly, without waiting to
get back to the conditional test.

CONTINUE

The keywords continue allow us to take the control to the beginning of the loop, by
passing the statements inside the loop which have not yet been executed.

GOTO STATEMENT

‘C’ supports go to statement to branch unconditionally from one point to another in the
program.

The GOTO General Form is

goto Label;

----------- Label:

---------- Statement

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

Label: -----------

Statement; ------------

Forward jump goto Label:

Backward jump

Ex; program to print ‘n’ natural number

main()

int n,i=1;

clrscr();

printf("enternumber");
scanf("%d\t",i);

printf("natural numbers from 1to%d",n);

lb: printf("%d\t",i);

i++;

if(i<=n)

goto lb;

getch();

SWITCH

It is a multiway decision statement.The switch statement tests the value of guven


variable( or expression) against a list of "case" values and when a match is found, a block of
statements associated with that case is executed.

General form of switch is

switch(expression)

case value-1:

block-1;

break;

case value-2:

block-2;

break;

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

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

case value-n:
block-n;

break;

default:

default-block;

break;

statement-x;

Ex: program to test all arithmetic operations using switch statement

main( )

int a,b ,opt;

clrscr( );

printf("enterany2values");

scanf("%d%d",&a,&b);

printf("1.addition\n2.subraction\n3.multiplication\4.division\n6.modular\n");

printf("\nenter option");

scanf("%d",&opt);

switch(opt)

case 1:

printf("aditionof%d&%dis%d",a,b,a+b);

break;

case 2:

printf("subof%d&%dis%d",a,b,a-b");
break;

case 3:

printf("multipleof%d&%dis%d",a,b,a*b);

break;

case 4:

printf("divof%d&%dis%d",a,b,a/b);

break;

case 5:

printf("modularof%d&%dis%d",a,b,a/b);

break;

default:

printf ("\n invalid option");

getch();

}
18. Explain

a) Passing parameters to functions

In C Programming Language, there are two methods to pass parameters from calling
function to called function and they are as follows...
 Call by Value
 Call by Reference

Call by Value

In call by value parameter passing method, the copy of actual parameter values are
copied to formal parameters and these formal parameters are used in called function. The
changes made on the formal parameters does not effect the values of actual parameters. That
means, after the execution control comes back to the calling function, the actual parameter
values remains same. For example consider the following program..

#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int,int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;

swap(num1, num2) ; // calling function

printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);


getch() ;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a=b;
b = temp ;
}

Call by Reference

In Call by Reference parameter passing method, the memory location address of the
actual parameters is copied to formal parameters. This address is used to access the memory
locations of the actual parameters in called function. In this method of parameter passing, the
formal parameters must be pointer variables.

That means in call by reference parameter passing method, the address of the actual
parameters is passed to the called function and is recieved by the formal parameters (pointers).
Whenever we use these formal parameters in called function, they directly access the memory
locations of actual parameters. So the changes made on the formal parameters effects the values
of actual parameters. For example consider the following program.

#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;

printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;


swap(&num1, &num2) ; // calling function

printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);


getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ;

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

18. b) Discuss in detail about storage classes with examples

Storage Classes are used to describe about the features of a variable/function. These
features basically include the scope, visibility and life-time which help us to trace the existence
of a particular variable during the runtime of a program.

C language uses 4 storage classes, namely:

1. auto:
This is the default storage class for all the variables declared inside a function or a
block. Hence, the keyword auto is rarely used while writing programs in C language.
Auto variables can be only accessed within the block/function they have been declared
and not outside them (which defines their scope). Of course, these can be accessed within
nested blocks within the parent block/function in which the auto variable was declared.
However, they can be accessed outside their scope as well using the concept of pointers
given here by pointing to the very exact memory location where the variables resides.
They are assigned a garbage value by default whenever they are declared.

2. extern:
Extern storage class simply tells us that the variable is defined elsewhere and not
within the same block where it is used. Basically, the value is assigned to it in a different
block and this can be overwritten/changed in a different block as well. So an extern
variable is nothing but a global variable initialized with a legal value where it is declared
in order to be used elsewhere. It can be accessed within any function/block. Also, a
normal global variable can be made extern as well by placing the ‘extern’ keyword before
its declaration/definition in any function/block. This basically signifies that we are not
initializing a new variable but instead we are using/accessing the global variable only.
The main purpose of using extern variables is that they can be accessed between two
different files which are part of a large program. For more information on how extern
variables work, have a look at this link.

3. static:
This storage class is used to declare static variables which are popularly used
while writing programs in C language. Static variables have a property of preserving their
value even after they are out of their scope! Hence, static variables preserve the value of
their last use in their scope. So we can say that they are initialized only once and exist till
the termination of the program. Thus, no new memory is allocated because they are not
re-declared. Their scope is local to the function to which they were defined. Global static
variables can be accessed anywhere in the program. By default, they are assigned the
value 0 by the compiler.

4. register:
This storage class declares register variables which have the same functionality as
that of the auto variables. The only difference is that the compiler tries to store these
variables in the register of the microprocessor if a free register is available. This makes
the use of register variables to be much faster than that of the variables stored in the
memory during the runtime of the program. If a free register is not available, these are
then stored in the memory only. Usually few variables which are to be accessed very
frequently in a program are declared with the register keyword which improves the
running time of the program. An important and interesting point to be noted here is that
we cannot obtain the address of a register variable using pointers.

Syntax:

storage_class var_data_type var_name;


#include <stdio.h>
extern int x = 9;
int z = 10;
int main()
{
auto int a = 32;
register char b = 'G';
extern int z;
printf("Hello World!\n");
printf("\nThis is the value of the auto "
" integer 'a': %d\n",a);
printf("\nThese are the values of the"
" extern integers 'x' and 'z'"" respectively: %d and %d\n", x, z);
printf("\nThis is the value of the "
"register character 'b': %c\n",b);
x = 2;

z = 5;
printf("\nThese are the modified values "
"of the extern integers 'x' and " "'z' respectively: %d and %d\n",x,z);
while (x > 0)
{
static int y = 5;
y++;
printf("The value of y is %d\n",y);
x--;
}
printf("\nBye! See you soon. :)\n");
return 0;
}

19. Explain in detail notes on structures in C.

C provides a special kind of variable called structure. C structure allows you to


wrap related variables that has different data types into a single variable. A structure can
contain any valid data types such as int, char, float, array, pointer or even other
structures. Each variable in the structure is called structure member.
Defining structure

To define a structure, you use the struct keyword. The following illustrates the syntax of
the structure definition:

struct struct_name{ structure_member };

Ex :

struct address{
unsigned int house_number;
char street_name[50];
int zip_code;
char country[50];
};

Declaring structure

The above example only defines the address structure without creating any structure variable.
There are two ways to declare a structure variable:

Ddeclare structure variables together with the structure definition as follows:

struct struct_name {

structure_member;

...

} instance_1,instance_2 instance_n;

Second, declare the structure variable after you define the structure. The following is structure
declaration syntax:

struct struct_name instance_1,instance_2, instance_n;

ex:

struct address home_address, business_address;


Accessing structure member

To access a structure member, you use the dot operator ( .) between structure name and
the member as follows:

structure_name.structure_member

The following example illustrates how to access street_name of the address structure :

struct address billing_addr;

billing_addr.country = "US";

Initializing structure variable

C treats a structure as a custom data type therefore you can initialize a structure like a
variable. The following example demonstrates how to initialize product structure:

struct product{

char name[50];

double price;

} book = { "C programming language",40.5};

We defined the product structure; declared and initialized book structure variable.

Structure and pointer

A structure can contain pointers as structure members. You can create an invoice
structure that contains invoice_number as a pointer:

struct invoice{

char* invoice_number;

char date[20];

};

struct address billing_addr;

struct address *pa = &billing_addr;


Shorthand structure with typedef keyword

To make the code clear, you can use typedef keyword to create a synonym for a structure.
This is an example of using typedef keyword to define address structure so that when you want
to create a structure variable, you can omit the struct keyword

typedef struct{

unsigned int house_number;

char street_name[50];

int zip_code;

char country[50];

} address;

address billing_addr;

address shipping_addr;

Copy a structure into another structure

One of major advantage of structure is that you can copy it with the assignment ( =)
operator:

struct_intance1 = struct_intance2

Structure and the sizeof operator

The sizeof operator is used to get the size of any data type as well as a structure.
20. How to declare, open and close the file stream in c language.

Declaring a file pointer

In C language, in order to declare a file, we use a file pointer. A file pointer is a pointer
variable that specifies the next byte to be read or written to. Every time a file is opened, the
file pointer points to the beginning of the file. A file is declared as follows :

FILE *fp; //fp is the name of the file pointer

Opening and Creating a File

C language provides a number of functions to perform file handling. fopen() is used to


create a new file or open an existing file. The syntax is as follows :

fp = FILE *fopen(const char *filename, const char *mode);

fp is the file pointer that holds the reference to the file, the filename is the name of the file
to be opened or create and mode specifies the purpose of opening a file i.e. for reading or
writing. FILE is an object type used for storing information about the file stream.

Different modes of opening a file

A file can be opened in different modes. Given below are some of the most commonly
used modes for opening or creating a file.

r : opens a text file in reading mode.

w : opens or create a text file in writing mode.

a : opens a text file in append mode.

r+ : opens a text file in both reading and writing mode. The file must exist.

w+ : opens a text file in both reading and writing mode. If file exists, it is truncated first before
overwriting. Any old data will be lost. If the file does not exist, a new file will be created.

a+ : opens a text file in both reading and appending mode. New data is appended at the end of
the file and does not overwrite the existing content.

rb : opens a binary file in reading mode.

wb : opens or create a binary file in writing mode.


ab : opens a binary file in append mode.

rb+ : opens a binary file in both reading and writing mode, the original content is overwritten if
the file exists.

wb+: opens a binary file in both reading and writing mode and works similar to the w+ mode for
binary files. The file content is deleted first and then new content is added.

ab+: opens a binary file in both reading and appending mode and appends data at the end of the
file without overwriting the existing content.

Closing a File

A file needs to be closed after read or write operation to release the memory allocated by the
program. In C, a file is closed using the fclose() function. This returns 0 on success and EOF in
case of a failure. An EOF is defined in the library called stdio.h. EOF is a constant defined as a
negative integer value which denotes that the end of file has reached.

fclose( FILE *fp );

Vous aimerez peut-être aussi