computer concept & programming in c ankur choudhary ap ... · computer concept &...

39
Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) Unit-1 1. Draw the Functional block diagram of a digital computer and discuss its components in brief. Ans. Computer: The term computer is derived from the word “Compute”. Compute => calculate “A computer is an electronic device which is capable of creating solution by performing complex processing at information.” “A computer is an electronic device for the storage and processing of information.” “A computer is an electronic device that stores, retrieves and process data and can be programmed with instruction.” “A machine that accepts input, process it according to specified rules and produce output.” Digital Computer: Digital computer is a computer which represents information by numerical (binary) digits. These types of computer broken any type of information into tiny units and these piece of information is represented by numbers. Personal computer is an example of digital computer. Essential Computer Hardware: 1. Processor 2. Memory: a)RAM- Random Access Memory- Volatile b)ROM- Read Only Memory- Non-Volatile 3. Input & Output Devices 4. Storage Devices: Hard Disk, Digital tape, Floppy disk, Optical Disk Block diagram of Digital Computer: Digital computer is an electronic device. It comprises of many units. These units work in coordination with each other to perform the given task. Each unit exists in the form of electronic equipments called devices. Input Unit: The role of input unit in computer is to provide means for supplying data or instructions to the computer. Secondary Storage Magnetic tape Magnetic Disk Input media Input Unit Main Memory Output Unit Arithmetic Unit Control unit Output media

Upload: others

Post on 15-Mar-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University)

Unit-1

1. Draw the Functional block diagram of a digital computer and discuss its components in brief. Ans. Computer: The term computer is derived from the word “Compute”. Compute => calculate “A computer is an electronic device which is capable of creating solution by performing complex processing at information.” “A computer is an electronic device for the storage and processing of information.” “A computer is an electronic device that stores, retrieves and process data and can be programmed with instruction.” “A machine that accepts input, process it according to specified rules and produce output.” Digital Computer: Digital computer is a computer which represents information by numerical (binary) digits. These types of computer broken any type of information into tiny units and these piece of information is represented by numbers. Personal computer is an example of digital computer. Essential Computer Hardware:

1. Processor 2. Memory: a)RAM- Random Access Memory- Volatile b)ROM- Read Only Memory- Non-Volatile 3. Input & Output Devices 4. Storage Devices: Hard Disk, Digital tape, Floppy disk, Optical Disk

Block diagram of Digital Computer:

Digital computer is an electronic device. It comprises of many units. These units work in coordination with each other to perform the given task. Each unit exists in the form of electronic equipments called devices. Input Unit: The role of input unit in computer is to provide means for supplying data or instructions to the computer.

Secondary Storage

Magnetic tape

Magnetic Disk

Input media

Input Unit Main Memory

Output Unit

Arithmetic Unit

Control unit

Output media

Page 2: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) Exp: Keyboard, Mouse, CD-ROM Drive, Bar code reader, Scanner & OCR, Web camera, Light pen, Touch Screen, Joystick, Microphone, Digital Camera. Output Unit: The role of the output unit is to show the result of processing. In other words, we can say that computer displays all the results on its output unit. Exp: Monitor, Speakers, Printers (Dot Matrix, Inkjet & Laser) Storage Devices: All input / output units which provides means for storing the data, instruction or results permanently are called storage devices (input / output units). Exp: Floppy Drive, Hard Disk, CD-Writer (CD-R, CD-R/W), Magnetic Tape Drive, Pen Drive. Central Processing Unit (CPU):The CPU consists of Control Unit (CU) and Arithmetic Logical Unit (ALU). CU stores the instruction set, which specifies the operations to be performed by the computer. CU transfers the data and the instruction to the ALU for an arithmetic operation. ALU performs arithmetical or logical operation on the data received. The CPU register stores the data to be processed by the CPU and the processed data also. Components of CPU : Arithmetic and Logical unit(ALU) Control Unit (CU) CPU Registers Memory: Memory holds data, instruction or results temporarily we can say that the unit which holds data instruction or results in it, is called memory. Types of Memory: Primary Memory: - RAM, ROM Cache Memory Parts of Computer Systems 1. Hardware 2. Software Physical parts of a computer is called hardware. Exp: Monitor Keyboard, Mouse, CPU, hard disk etc... A sequence of instructions or programs given to a computer to perform a particular well defined task task is called a software. Exp.: MS Word , Operating System etc. 2. Explain system software and application software. Give 2 examples of each. Answer: Types of Software: 1. System Software: A software that supports the functionality of computer system is called system software .e.g. Operating system , compiler , linker, loader, assembler etc. 2. Application Software: Application software is a set of one or more programs designed to carry out operations for specific applications. Exp: word processing, spreadsheet & database management system fall under the category of application software.

Main Memory

Cache Memory

Processor

Application Software

System Software

Hardware

Page 3: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) Relationship among hardware, software, and user Characteristics of Computers:

2. Speed 3. Accuracy 4. Reliability: Guaranteed Results. 5. Versatility: Flexibility / Adaptability

Types of Computers:

1. Super Computer 2. Main Frame Computer 3. Mini Computers or Mid Range Computers 4. Micro Computers or Personal Computers

3. Define an Operating system. Explain basic functions of Operating system. What are the types of Operating systems and give

example of each. Answer: OPERATING SYATEM: OS is system software that helps the users to operate the computer and manage its resources. The primary purpose of the OS is to act as an interface between the computer and the user. OS acts as an interface between user and computer. It provides a set of commands through which user can type, copy, print etc. Without OS, a computer cannot be used. Exp: OS/2, Windows 98, Windows 2000, Windows XP, Vista., UNIX ,LINUX . Components of Operating System:

1. Process Management Subsystem 2. Memory Management Subsystem 3. File Management Subsystem 4. I/O Management Subsystem 5. Secondary Management Subsystem 6. Network Management Subsystem 7. Protection Management Subsystem

Function of Operating System:

1. Program Execution Services 2. I/O Operation Services 3. File System Services 4. Communication Services 5. Error detection Services 6. Accounting Services

Types of Operating System: 1. Batch operating system: This is earliest operating system, where only one program is allowed to run at a one time. We cannot modify any data used by the program while it is being run. A popular batch operating system is MS DOS.

Operating System

Moniter

Keyboard

Printer

Application Disk Drive

Mouse

Page 4: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A multi-user operating system allows more than one user to use a computer system either at the same time or different time. Exp: Linux, Windows 2000. 3. Multi-tasking operating system: A multi-tasking operating system allows more then one program to run at the same time. Exp: UNIX, Windows 2000. 4. Multithreading operating system: A multithreading operating system allows the running of different parts of a program at a same time. Exp: UNIX, Linux. 4. What do you mean by Programming language. Explain the different types of programming languages. Also, explain the use

of high level languages for the systematic development of programs. Programming Language: A program is a set of instruction which is executed by a computer. A programming language consists of all the symbols, characters and usage rules that permit the people to communicate with computer. 1. Low level language: It contains the strings of binary number (0’s & 1’s) and is machine dependent. It means that the machine language( First generation language ) for every processor is different. An instruction prepared in any machine language has two part format:-

Advantages: Disadvantage: 1. Very Efficient 1. Machine Dependent 2. Requires less storage space 2. Programming is difficult 3. The processor can execute without any transaction

3. Error Prone

4. Cost is high 2. Assembly Language( Second Generation Language ): Assembly language or symbolic language is a language that uses symbols instead of numbers. A translator program that translates an assembly code with the computer machine code is called assembler.

Advantages: Disadvantage: 1. Time saving & reduce details 1. Coding is time consuming. 2. Fewer errors & made which is easier to find.

2. It is also machine oriented as the code for one machine is not used by the other one.

3. Assembly lang. program are easier to modify then the m/c language program.

4. Easier to understand & use. 3. High Level Language: To overcome the difficulties of low level language, the high level language was developed. These languages, instead of being machine based, are oriented more towards solving the problem. High level languages can be classified in to three categories :

Language

Low Level Lang.

High Level Lang.

Machine Lang.

Assembly Lang.

OPCODE (Operation Code)

OPERAND (Address/Location)

Tells the computer what function to perform.

Tells the computer where to find or store the data or other instruction that are to be manipulated.

Page 5: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University)

• Third-generation language:- Procedure –oriented languages ( BASIC , COBOL, FORTRAN,C,C++,JAVA) • Fourth-generation language:- Problem – oriented languages (Query languages ) • Fifth-generation language:- Natural languages ( LISP and PROLOG )

Advantages: 1. These are easier to learn than low level language. 2. It required less time to write. 3. They provide better documentation. 4. Easier to maintain. 5. They are not machine oriented.

Comparison of High Level Language, Assembly Language & Machine Language

High Level Language Assembly Language Machine Language 1. These are easily

understandable. Less understandable then high level language but more then m/c language.

Programs are less understandable.

2. Programs are portable. Not portable to processor to same interpreter only.

Not portable only processor of same architecture.

3. Debugging is easier. Debugging is more complex then high level language.

Not good as high level language and assembly language.

Properties of Programming Language:

1. Efficiency 2. Reliability 3. Robustness 4. Usability 5. Portability

Q. Write short note on the following Algorithm Development approaches: • Top-Down development • Structured Programming • Procedural Programming • Modular Programming

Answer : Top-Down development: Top-down development provides a method to handle the complexity of the problem by breaking them into easy and understandable sub modules. The process of repeatedly breaking a task down into subtasks should continue until we eventually end up with subtasks that can be easily implanted. Advantages of top-down programming:

1. Separating the low level work from the higher level objects leads to a modular design. 2. Modular design means development can be self contained. 3. Less operations errors. 4. Much less time consuming. (Many programmer works together). 5. Very optimized way of processing. (Each programmer applies their own knowledge & experience). 6. Easy to maintain (If error occurs, it is easy to identify the errors generated from which modules of the entire program).

Main Program

Input function Main Process Output Function

Subfunction-1 Subfunction-2 Subfunction-3

Page 6: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) Structured Programming: In structural programming, the program is divided into small independent tasks. These tasks are small enough to be understood easily without having to understand the entire program at once. Each task is designed to perform specific functionality on its own. When these tasks are performed, their outcomes are combined together to procedural programming and modular programming. Procedural Programming: Procedural programming is a programming paradigm based upon the concept of procedure call. Procedures are also known as routines, subroutines, methods or functions. Any given procedure might be called at any point during programs, the flow of program execution continues from where call was made. Procedural programming is often a better choice than simple sequential or unstructured programming. Advantages of Procedural Programming:

1. The ability to re-use the same code at different places in the program without copying it. 2. An easier way to keep track of program flow than a collection of “goto” or “jump” statements. 3. An ability to be strongly structured.

Modular Programming: The programs written with procedural paradigm usually fit into a single program file and it is meant for relatively smaller programs. If the program gets large, then modular way of programming is recommended. Modular programming is subdividing our program into separate small programs called modules. Each module is designed to perform specific function. Modules make our actual program shorter, hence easier to read and understand. A define function or set of similar function is coded in a separate modules or sub modules. After a module has been tested individually, it is then integrated with other modules into overall program structure 5. Convert the following:

i. (478A)16 = ( )10 xi. (1230)4 = ()6

ii. (975.55)10 = ( )2 xii. (1011)Gray = ( )Binary

iii. (11001100.10)2 = ( )16 xii. (5214)10 = ( )16

iv. (15)10 = ( )Gray xiv. (7F2)16 = ( )8

v. (251)10 = ( )2 = ( )8 = ( )16 = ( )BCD xv. (13)10 = ( )BCD

vi. (141)10 = ( )2 = ( )8 = ( )16 = ( )BCD xvi. (24.25)10 = ( )2 = ( )16

vii. (011010111101001100)2 = ( )10 = ( )8 = ( )16 xvii. (56)10 = ( )2 = ( )16

viii. (235.4)8 = ( )16 xviii. (133.15)10 = ( )2 = ( )16

ix. (5214)10 = ( )16 xix. (752)8 = ( )16

x. (1011)10 = ( )2 xx. (678)10 = ( )3

xxi (1011010)2= ()2’s Complement xxii (151)10= ()2’s Complement

Unit-2

6. What are various data types supported by C Language? Describe briefly, choose suitable example whenever required? Answer: Data types: A data type is used to tell about the type of the data(numbers, characters) being used in a program. C language data types can be broadly classified as 1) Fundamental data types i) int ii) float iii) char iv) double 2) User- defined data types i) Type-defined data type ii) enumeration data type 3) Derived data types i) Arrays ii) structures iii) union iv) function Primary data type: All C Compilers accept the following fundamental data types S.No. Values Data type Format Specifier Range of values 1.

Integer

int

%d -128 to 127

2. Character char %c -32768 to +32767

Page 7: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 3.

Floating Point

float

%f 3.4 e-38 to 3.4 e+38

4.

Double precision floating point

double

%lf 1.7 e-308 to 1.7 e+308

5.

Void

void

-------- -128 to 127

int data type is used for numeric values being used in a program. float and double data type is used for real numbers being used in a program. char data type is used for characters being used in a program. User-defined data type: • type –defined data type: It is used to rename lengthy and existing data type to make a program easy to understand. Syntax: typedef existing data type new data type For example: typedef long int f Here typedef is a keyword used to rename long int data type into short data type such as f. Now there is no need to write every time long int in a program, we can just write f instead of long int to declare a variable of long int type. 7. Describe bitwise and logical operator with example? Answer: The bitwise operators perform bitwise-AND (&), bitwise-exclusive-OR (^), and bitwise-inclusive-OR (|) operations.

The operands of bitwise operators must have integral types, but their types can be different. These operators perform the usual arithmetic conversions; the type of the result is the type of the operands after conversion.

The C bitwise operators are described below:

Operator Description

& The bitwise-AND operator compares each bit of its first operand to the corresponding bit of its second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

^ The bitwise-exclusive-OR operator compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

| The bitwise-inclusive-OR operator compares each bit of its first operand to the corresponding bit of its second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

Examples

These declarations are used for the following three examples:

short i = 0xAB00; short j = 0xABCD; short n; n = i & j; The result assigned to n in this first example is the same as i (0xAB00 hexadecimal). n = i | j; n = i ^ j; The bitwise-inclusive OR in the second example results in the value 0xABCD (hexadecimal), while the bitwise-exclusive OR in the third example produces 0xCD (hexadecimal).

The results of bitwise operation on signed integers is implementation-defined according to the ANSI C standard. For the Microsoft C compiler, bitwise operations on signed integers work the same as bitwise operations on unsigned integers. For example, -16 & 99 can be expressed in binary as

11111111 11110000 & 00000000 01100011 _________________ 00000000 01100000

Page 8: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) The result of the bitwise AND is 96 decimal.

The logical operators perform logical-AND (&&) and logical-OR ( || ) operations.

Logical operators do not perform the usual arithmetic conversions. Instead, they evaluate each operand in terms of its equivalence to 0. The result of a logical operation is either 0 or 1. The result's type is int.

The C logical operators are described below:

Operator Description

&& The logical-AND operator produces the value 1 if both operands have nonzero values. If either operand is equal to 0, the result is 0. If the first operand of a logical-AND operation is equal to 0, the second operand is not evaluated.

|| The logical-OR operator performs an inclusive-OR operation on its operands. The result is 0 if both operands have 0 values. If either operand has a nonzero value, the result is 1. If the first operand of a logical-OR operation has a nonzero value, the second operand is not evaluated.

The operands of logical-AND and logical-OR expressions are evaluated from left to right. If the value of the first operand is sufficient to determine the result of the operation, the second operand is not evaluated. This is called "short-circuit evaluation." There is a sequence point after the first operand. See Sequence Points for more information.

Examples

The following examples illustrate the logical operators:

int w, x, y, z; if ( x < y && y < z ) printf( "x is less than z\n" );

In this example, the printf function is called to print a message if x is less than y and y is less than z. If x is greater than y, the second operand (y < z) is not evaluated and nothing is printed. Note that this could cause problems in cases where the second operand has side effects that are being relied on for some other reason.

printf( "%d" , (x == w || x == y || x == z) );

In this example, if x is equal to either w, y, or z, the second argument to the printf function evaluates to true and the value 1 is printed. Otherwise, it evaluates to false and the value 0 is printed. As soon as one of the conditions evaluates to true, evaluation ceases.

8. Explain difference between following terms: a. Local variable and Global variable b. Declaration and Definition c. Formal parameter and Actual parameter d. explicit and implicit type casting

Answer:a) Local variables and global varaiables: S.No. Local Variables Global Variables

1. Variables that are declared inside a function are called local variables.

Variables that are declared outside a function are called global variables.

2. It can be used only by the statements that are inside the block in which the variables are declared, i.e. local variables are not known to outside their own code block.

It can be used throughout the program in any function, regardless of what block of code that expression is in., i.e. global variables are known to outside their own code block.

Page 9: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 3. Local variables hold their values till that block in which it

is declared. e.g. #include<stdio.h> int main(void ) { int x=10; // local variables if(x==10) { int x; // this hides the outer x x=99; printf(Inner x: %d\n”, x); } printf(“outer x: %d\n”,x); return 0; } o/p: Inner x: 99 outer x: 10

Global variables hold their values throughout the program’s execution. For example: #include<stdio.h> int x=10; // global variables int main(void ) { if(x==10) { int x; // this hides the outer x x=99; printf(Inner x: %d\n”, x); } printf(“outer x: %d\n”,x); return 0; } o/p: Inner x: 99 outer x: 10

b) c) Implicit Type Conversion C permits mixing of constants and variables of different types in an expression .C automatically converts any intermediate values to the proper type so that the expression can be evaluated without losing any significance. This automatic conversion is known as implicit type conversion. int i, x; float f; double d; long init l; x = ½ + i * f-d Explicit Type Conversion Ratio = abc / xyz (float) (int) (int) Decimal part of division would be lost this problem will be solved by the following Ratio = (float) abc /xyz ____(float) __ (float) The process of such a local conversion is known as explicit conversion or casting a value. The general form of a cast is: (type- name) expression d.)Formal parameter and Actual parameter: Actual Parameters are the parameters which are passed by the calling function . Formal Parameters are the parameters which are used by called function to hold actual parameters . 9. Explain operator precedence and associativity with suitable example

S. No. Declaration Definition 1. Declaring a variable & function means

describing its type to the compiler and also allocating space to hold the variable’s data.

Defining a variable & function means declaring it and also allocating space to hold the variable’s data. You can also initialize a variable at the time it is defined.

2. In case of a variable, a variable can be declared once.

But in this, definition of a variable is defined only one time in a program.

3. For example int a; For example int a=7;

Page 10: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) Answer: Each operator in C has a precedence associated with it. Precedence denotes the priority of operators. In other words if number of operators occur in a expression the priority in which the operators gets executes is decided by precedence of operators. The precedence is used to determine how an expression involving more than one operator is evaluated. There are distinct levels of precedence and an operator may belong to one of these levels. The operators of higher precedence are evaluated first. Associativity is the order in which a operator gets executes. The operators of same precedence are evaluated from right to left or from left to right depending on the level. This is known as associativity property of an operator.

The table given below gives the precedence of each operator.

Order Category Operator Operation

Associativity

1

Highest precedence

( ) [ ] → : : .

Function call

L → R Left to Right

2

Unary

! ~ + -

++ - - & *

Size of

Logical negation (NOT) Bitwise 1’s complement Unary plus Unary minus Pre or post increment Pre or post decrement Address Indirection Size of operant in bytes

R → L Right -> Left

3

Member Access

.* →*

Dereference Dereference

L → R

4

Multiplication

* /

%

Multiply Divide Modulus

L → R

5

Additive

+ -

Binary Plus Binary Minus

L → R

6

Shift

<< >>

Shift Left Shift Right

L → R

7

Relational

< <= >

>=

Less than Less than or equal to Greater than Greater than or equal to

L → R

8

Equality

== !=

Equal to Not Equal to

L → R

9

Bitwise AAND

&

Bitwise AND

L → R

10

Bitwise XOR

^

Bitwise XOR

L → R

11

Bitwise OR

|

Bitwise OR

L → R

12

Logical AND

&&

Logical AND

L → R

14

Conditional

? :

Ternary Operator

R → L

Page 11: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University)

15

Assignment

= *= %= /= += -= &= ^= |=

<<= >>=

Assignment Assign product Assign reminder Assign quotient Assign sum Assign difference Assign bitwise AND Assign bitwise XOR Assign bitwise OR Assign left shift Assign right shift

R → L

10. Define storage classes in C. Explain with suitable example? Answer: Storage classes in C define where a variable is stored, what should be its initial value, scope, and life. There are four types of storage class having characteristics as shown below: S.no. Storage class &

Declaration Where stored Initial value Scope Life span

1. Automatic: Example: auto int x; By default a variable is auto if its storage class is not specified.

In memory garbage Local to the block in which it is declared.

The variable is accessible only while program is inside the block in which variable has been declared and used.

2. Static: Example: static int x; Variables which are required to maintain their values until the next function call are declared as static.

In memory Static variables are initialized to 0.

Local to the block in which it is declared.

Same as auto variables, except that the previous value is retained and can be used.

3. Register: Example: register int x; Only integer variables can be declared as register.

Such variables are stored in the CPU registers for quick access provided a register is free , otherwise it will be treated as auto variable.

garbage Local to the block in which it is declared

Same as auto variables.

4. External: Example: Extern int x;

In memory Initialized to 0. Such variables are declared on the top of the program after the preprocessor directives; and are globally accessible.

As long as program runs.

Page 12: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University)

Unit-3 11. What is the use of ‘switch’ statement Write down its syntax and explain how it is different from ‘if’ statement? Answer: The general syntax is: switch (expression) { case constant1: group of statements 1; break; case constant2: group of statements 2; break; . . . default: default group of statements } In the above example, the expression is first evaluated and the value id checked with the constant1 in the case statement. If this is evaluated with the same value, then the group of statements is executed. When a break statement is encountered, the control is switched to the end of the switch statement. If the value of the expression is not equal to connstant1, it is checked with constant2. If it evaluates the same value, then the group of statements (in the case of constant2) are executed. When a break statement is encountered, the control is then switched to the end of the switch statement. This proceeds until the value of expressions equal one of the constant values given. If the value of the expression is not equal to any of the constant values given, then, by default, the statements present are executed. S.No. Switch If 1. In switch condition the condition is checked only once

and jumps to required block In multiple if statements the conditions are to be checked as many times the if statements are written

2. A switch statement is generally best to use when you have more than two conditional expressions based on a single variable of numeric & character type.

A if else statement can take any kind of value in conditional expression.

3. CASE statement is definitely better when there are more than 2 conditions because it makes the code more structured, systematic and easy to understand in terms of programming efficiency.

In if statements to get required result, we have to check many conditions first. this is time consuming

4. Switch is better to use provided the results of the check-condition are discreet values.

A if else is better to use when multiple condition is to be evaluated.

5. Logical operators are not allowed in cases. All operators are allowed in if-else.

12. How do you classify the control statements? Describe different forms of ‘if’ statement. Write the differences among for loop,

while loop and do-while loop. Answer: Control Statements: A program consists of a number of statements which are usually executed in sequence. Programs can be much more powerful if we can control the order in which statements are run.

Statements fall into three general types;

• Assignment, where values, usually the results of calculations, are stored in variables. • Input / Output, data is read in or printed out. • Control, the program makes a decision about what to do next.

This section will discuss the use of control statements in C. We will show how they can be used to write powerful programs by;

• Repeating important sections of the program. • Selecting between optional sections of a program.

• The if else Statement

Page 13: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University)

• The switch Statement • Loops • The while Loop • The do while Loop • The for Loop • The break Statement • The continue Statement • The goto Statement

if statement

This is the simplest form of the branching statements.

It takes an expression in parenthesis and an statement or block of statements. if the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.

NOTE: Expression will be assumed to be true if its evaulated values are non-zero.

Different forms of If statement:

if (expression) statement; or if (expression) { Block of statements; } or if (expression) { Block of statements; } else { Block of statements; } or if (expression) { Block of statements; } else if(expression) { Block of statements; } else { Block of statements; } 13. Differentiate between them:

a. Break and continue

Page 14: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University)

b. Switch and if -else c. While and do-while d. Preincrement and postincrement e. Declaration and Definition f. Local and Global Variable g. exit( ) & return( ) h. function and macro i. Structure and Union

Answer: a) 1) break: It takes the control outside the block in which it is placed. It provides An early exit from for, while, do-while, if and switch constructs. 2) Continue: It can be used only with the loops. It causes the loop to be continued with the next iteration after skipping any statement in between.

b)

S.No. Switch If 1. In switch condition the condition is checked only once

and jumps to required block In multiple if statements the conditions are to be checked as many times the if statements are written

2. A switch statement is generally best to use when you have more than two conditional expressions based on a single variable of numeric & character type.

A if else statement can take any kind of value in conditional expression.

3. CASE statement is definitely better when there are more than 2 conditions because it makes the code more structured, systematic and easy to understand in terms of programming efficiency.

In if statements to get required result, we have to check many conditions first. this is time consuming

4. Switch is better to use provided the results of the check-condition are discreet values.

A if else is better to use when multiple condition is to be evaluated.

5. Logical operators are not allowed in cases. All operators are allowed in if-else.

c)

S.No. While Do-While 1. A while statement checks test-condition at the

beginning of a loop to see whether the next loop iteration should occur or not.

A do-while statement checks test-condition at the end of a loop to see whether the next iteration of a loop should occur or not.

2. It will not execute any statements written in loop block until condition is evaluated true.

The do- while statement will always execute the body of a loop at least once, even if the condition is false.

d) Preincrement & Postincrement:

Preincrement Postincrement 1.

Unary operator denoted with ++ before the variable name; e.g. ++i

Unary operator denoted with ++ after the variable name; e.g. i++

2. 3.

Associativity is left to right.

Increments the variable by one before the expression in which variable appears is evaluated.

Associativity is right to left.

Increments the variable by one afterthe expression in which variable appears is evaluated.

e) Declaration and Definition

. Declaration Definition 1. Declaring a variable & function means describing

its type to the compiler and also allocating space to hold the variable’s data.

Defining a variable & function means declaring it and also allocating space to hold the variable’s data. You can also initialize a variable at the time it is

Page 15: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University)

f) Local variables and global varaiables: Local Variables Global Variables 1. Variables that are declared inside a function are

called local variables. Variables that are declared outside a function are called global variables.

2. It can be used only by the statements that are inside the block in which the variables are declared, i.e. local variables are not known to outside their own code block.

It can be used throughout the program in any function, regardless of what block of code that expression is in., i.e. global variables are known to outside their own code block.

3. Local variables hold their values till that block in which it is declared. e.g. #include<stdio.h> int main(void ) { int x=10; // local variables if(x==10) { int x; // this hides the outer x x=99; printf(Inner x: %d\n”, x); } printf(“outer x: %d\n”,x); return 0; } o/p: Inner x: 99 outer x: 10

Global variables hold their values throughout the program’s execution. For example: #include<stdio.h> int x=10; // global variables int main(void ) { if(x==10) { int x; // this hides the outer x x=99; printf(Inner x: %d\n”, x); } printf(“outer x: %d\n”,x); return 0; } o/p: Inner x: 99 outer x: 10

g) exit( ) & return( ) : exit( ) return( ) 1. It is used to exit the program as a whole. In other

words it returns control to the operating system The return () statement is used to return from a function and return control to the calling function.

2 After exit () all memory and temporary storage areas are all flushed out and control goes out of program.

It does not flush out the memory space which is reserved by a program.

3 Also in a program there can be only one exit () statement.

But a function can have number of return( ) statements.

4 exit () statement is placed as the last statement in a program since after this program is totally exited.

Return( ) statement can take its presence anywhere in the function. It need not be presented as the last statement of the function.

defined. 2. In case of a variable, a variable can be declared

once. But in this, definition of a variable is defined only one time in a program.

3.

For example int a; For example int a=7;

Page 16: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University)

h) Macro & Function

macro Function 1. In it, we can define function definition in one line. In function, we can write as many statements as

we want in function definition. 2. It has faster execution speed. It has slower execution speed. 3. No function call overhead. There is function call overhead every time

when function is called.

I) Structure and Union: S.No. Union Structure 1. All members share same memory storage area

within a union. In structure, each member has its own unique storage area.

2. union s { int age; char name[20]; }e; void main( ) { printf(“%d”, sizeof(e)); } o/p: 20

Struct s { int age; char name[20]; }e; void main( ) { printf(“%d”, sizeof(e)); } o/p: 22

14. What is function? Differentiate “Call by Value” and “Call by reference” with example? Answer: A function is a self-contained block of code that performs a particular task. Once a function has been defined, it can be treated as a ‘black box’ that takes some data from main program and returns a value. The inner details (coding) of a function are invisible to the rest of the program. All that the program knows about a function is : What goes in & what comes out. Three steps are required before using a function:

1) Function Declaration(i.e., prototype): to specify the function’s interface to the program. 2) Function Definition – It is used to tell the program about what & how a function is doing. 3) Function call - it is used to invoke the function at a required place.

(Note: Calling function or calling program: The program or function that calls the required function is referred to as the calling function or calling program. The calling function should declare the function (like declaration of a variable ) that is used later in the program. This is known as function declaration or function prototype.) Call by value and call by reference: S.No Call by Value Call by Reference 1. Only a copy of the parameters is passed in function call.

e.g. : swap(a, b); // function call Address of the parameter is passed in the function call. e.g. : Swap(&a, &b); // function call

2. Called function can not access the original parameters of the calling function, so changes made to the formal arguments of called function will not be reflected on the actual arguments of calling function.

Called function can access the original parameters of the calling function, so changes made to the formal arguments of called function will be reflected on the actual arguments of calling function.

3. The function can return at most one value. Since function has the access to original parameters, the function can indirectly return several values.

Unit-4 15. What is an array? Give classification of array. Give different ways of initialization of array.

Page 17: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) Answer: An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, int for example, with a unique identifier. For example, an array to contain 5 integer values of type int called billy could be represented like this:

where each blank panel represents an element of the array, that in this case are integer values of type int. These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length. Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is: type name [elements]; where type is a valid type (like int, float...), name is a valid identifier and the elements field (which is always enclosed in square brackets []), specifies how many of these elements the array has to contain. Therefore, in order to declare an array called billy as the one shown in the above diagram it is as simple as:

int billy [5]; NOTE: The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed, which is explained later in these tutorials.

Initialization of array is very simple in c programming. There are two ways you can initialize arrays.

• Declare and initialize array in one statement. • Declare and initialize array separately.

Look at the following C code which demonstrates the declaration and initialization of an array.

int Age [5] = {30, 22, 33, 44, 25}; int Age [5]; Age [0]=30; Age [1]=22; Age [2]=33; Age [3]=44; Age [4]=25;

Array can also be initialized in a ways that array size is omitted, in such case compiler automatically allocates memory to array.

int Age [] = {30, 22, 33, 44, 25}; 16. What is dynamic memory allocation? Explain malloc and calloc function with suitable example?

Page 18: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) Answer: Dynamic memory allocation:

The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this function. Many languages permit a programmer to specify an array size at run time. Such languages have the ability to calculate and assign during executions, the memory space required by the variables in the program. But c inherently does not have this facility but supports with memory management functions, which can be used to allocate and free memory during the program execution. The following functions are used in c for purpose of memory management.

Function malloc: Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space calloc: Allocates space for an array of elements initializes them to zero and returns a pointer to the memory free: Frees previously allocated space realloc: Modifies the size of previously allocated space. Malloc: 1. Takes only 1 argument- the size of the memory block to be allocated. 2. Allocates memory as a single contiguous block. 3. Will fail if a single contiguous memory block of required size is not available. Calloc: 1. Takes two arguments - the number of memory blocks needed and the size of each memory block. 2. It may or may not allocate a single contiguous block, thus will not fail if a single contiguous memory block of required size is not available. 3. Initializes the memory blocks to 0.

Unit-5 17. What is sorting? Sort the following numbers with help of any sorting technique? Answer: SORTING: The process of arranging data or records in a sequence is known as sorting. The data can be sorted in two ways: Ascending Sort and Descending Sort. Ascending sort is a sorting technique in which the smallest data is placed at the position and the largest data is placed at last position. Descending sort is a sorting technique in which the largest data is placed at first position and the smallest data is placed at last positing. 18. What is sorting? Explain any sorting technique with suitable example? SORTING: The process of arranging data or records in a sequence is known as sorting. The data can be sorted in two ways: Ascending Sort and Descending Sort. Ascending sort is a sorting technique in which the smallest data is placed at the position and the largest data is placed at last position. Descending sort is a sorting technique in which the largest data is placed at first position and the smallest data is placed at last positing. BubbleSort( int a[], int n) Begin

for i = 1 to n-1 sorted = true

for j = 0 to n-1-i if a[j] > a[j+1]

temp = a[j] a[j] = a[j+1] a[j+1] = temp

sorted = false end for if sorted

break from i loop end for

Page 19: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) End EXAMPLE FOR BUBBLE SORT:

19. What is the use of header files? Discuss with example? Answer: A header file is used to define constants, variables, macros and functions that may be common to several applications. When a system consists of multiple applications that all access the same data it becomes essential that each application uses identical definitions and it is safer for all of those applications to use the same methods to read that data. Updating data should only be performed by a single function, from a single application, but reading data can be safely performed by using the common definitions found in header files.

Standard Header Files

Set of libraries for additional functionality. We place references to these at the start of the source code file that uses one or more functions from that library.

Example: The compiler can compile the source code below, thanks to the #include line, which tells it where the definition of printf can be found.

#include <stdio.h> void main ( void ) // Entry point function { printf("Hello World"); // Output } 20. Write the syntax and return value of string functions: strlen, strcat, strrev, strcmp, strcpy Answer:

strlen() function:

This function counts and returns the number of characters in a string. The length does not include a null character. Syntax n=strlen(string);

Page 20: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) Where n is integer variable. Which receives the value of length of the string.

Example

length=strlen(“Hollywood”);

strcat() function:

when you combine two strings, you add the characters of one string to the end of other string. This process is called concatenation. The strcat() function joins 2 strings together. It takes the following form

strcat(string1,string2)

string1 & string2 are character arrays. When the function strcat is executed string2 is appended to string1. the string at string2 remains unchanged.

Example

strcpy(string1,”sri”); strcpy(string2,”Bhagavan”); Printf(“%s”,strcat(string1,string2);

strcmp function:

In c you cannot directly compare the value of 2 strings in a condition like if(string1==string2) Most libraries however contain the strcmp() function, which returns a zero if 2 strings are equal, or a non zero number if the strings are not the same. The syntax of strcmp() is given below:

Strcmp(string1,string2)

String1 & string2 may be string variables or string constants. String1, & string2 may be string variables or string constants some computers return a negative if the string1 is alphabetically less than the second and a positive number if the string is greater than the second.

Example:

strcmp(“Newyork”,”Newyork”) will return zero because 2 strings are equal. strcmp(“their”,”there”) will return a 9 which is the numeric difference between ASCII ‘i’ and ASCII ’r’. strcmp(“The”, “the”) will return 32 which is the numeric difference between ASCII “T” & ASCII “t”.

strcpy() function:

C does not allow you to assign the characters to a string directly as in the statement name=”Robert”; Instead use the strcpy(0 function found in most compilers the syntax of the function is illustrated below.

strcpy(string1,string2);

Strcpy function assigns the contents of string2 to string1. string2 may be a character array variable or a string constant.

strcpy(Name,”Robert”);

In the above example Robert is assigned to the string called name

Page 21: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) strrev() function: This function takes a string as input and returns the reverse of string to the string written in left of assignment.

dest = strrev(source);

21. What do you mean by macro and pre processor directive? Explain with example? Answer: A preprocessor is a program that processes its input data to produce output that is used as input to another program. The output is said to be a preprocessed form of the input data, which is often used by some subsequent programs like compilers. It operates under the control of preprocessor command lines and directives. Preprocessor directives are placed in the source program before the main line before the source code passes through the compiler it is examined by the preprocessor for any preprocessor directives. If there is any appropriate actions are taken then the source program is handed over to the compiler. Preprocessor directives follow the special syntax rules and begin with the symbol # and do not require any semicolon at the end. A set of commonly used preprocessor directives Preprocessor directives: Directive

Function

#define

Defines a macro substitution

#undef

Undefines a macro

#include

Specifies a file to be included

#ifdef

Tests for macro definition

#endif

Specifies the end of #if

#ifndef

Tests whether the macro is not def

#if

Tests a compile time condition

#else

Specifies alternatives when # if test fails

The preprocessor directives can be divided into three categories 1. Macro substitution division 2. File inclusion division 3. Compiler control division

MACRO: Macro substitution is a process where every occurrences of an identifier in a program is replaced by a macro expansion by preprocessor. The definition should start with the keyword #define and should follow on identifier and macro-expansion with at least one blank space between them. Syntax: #define macro-identifier macro-expansion There are different forms of macro substitution. The most common form is

1. Simple macro substitution 2. Argument macro substitution 3. Nested macro substitution

#define MAX 1 #define SQUARE(x) x*x #define CAL(y) y+y Void main( ) { if(CAL(SQUARE(5)) > MAX) printf(“hello”); else printf(“bye”); } 22. Write a short note on the file handling in C programming.

Page 22: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) Ans: Many applications require that information to be written to or read from an auxiliary memory device. Such information is stored in the form of a data file which provides many benefits:

It allows us to store large amount of information permanently. Easy to access Easy to alter the information whenever necessary. The transfer of input-data/ output-data from one computer to another

can be done easily. There are different operations that can be carried out on a file. These are:

a) Creation of a new file b) Opening an existing file c) Reading from a file d) Writing to a file e) Moving to a specific location in a file(seeking) f) Closing a file.

Explain difference between following terms: a) fprintf ( ) and fwrite( ) : S.No fprintf( ) fwrite( ) 1. It is a text mode function, i.e. stores data in

text format. It is a binary mode function, i.e. stores data in binary format.

2. In text mode function, the numbers are stored as strings of characters, so numbers would occupy more number of bytes in memory. For instance, 20000, an int, which occupies two bytes in memory, would be treated as a string of characters ‘2’,’0’,’0’,’0’,’0’,which would occupy five bytes in the file, one for each character. Thus, three bytes would be wasted in storing a two byte number

In it, the numbers occupy as much as storage area it is required to store a single number. For example, 20000, an int, it would occupy 2 bytes in memory.

3. If number of fields in the structure increase (say, by adding address, house rent etc.), writing structure using fprintf( ) becomes quite clumsy.

The format of fwrite( ) would remain same even if the number of fields belonging to the structure increases.

4. Syntax: fprintf(file pointer, “control string”, variable list); for example: fprintf(fp,”%d%f”, age, salary);

Syntax: fwrite(&e, sizeof(e), 1, fp); here, &e is the address of the structure to be written to the disk. sizeof(e) is the size of the structure in bytes. Third argument is the number of such structures that we want to write at a time. fp is the pointer to the file we want to write to.

List of Programs 22. Write a program to find the area of triangle. Area = sqrt(s*(s-a)*(s-b)*(s-c)) #include<stdio.h> #include<conio.h> #include<math.h> void main() { int a,b,c; float s,d,area;

Page 23: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) clrscr(); printf("Enter the sides of tringle:"); scanf("%d%d%d",&a,&b,&c); s=(a+b+c)/2.0; d=(s*(s-a)*(s-b)*(s-c)); area=sqrt(d); printf("Area of:%f",area); getch(); }

23. Write a program to find the factorial of any number. #include<stdio.h> #include<conio.h> void main() { long int f=1; int n,i; clrscr(); printf("Enter the number"); scanf("%d",&n); for(i=1;i<=n;i++) { f=f*i; } printf("The factorial is %ld",f); getch(); } 24. Write a program to find the sum of following series:

a. 1 – 1/2 + 1/3 – 1/4 + 1/5 - …… up to n terms. #include<stdio.h> #include<conio.h> void main() { int i,sign = +1,n; double s=0.0; clrscr(); printf("enter number of terms "); scanf("%d",&n); for(i=1;i<=n;i++) { s=s+sign * 1.0/i; sign= -1*sign; } printf("sum of series = \t%lf",s); getch(); }

b. 1! + 2! + 3! + 4! + ….. + n!

#include<stdio.h> #include<conio.h> void main() { int i,j,n; long int fact,s=0; clrscr(); printf("enter number of terms "); scanf("%d",&n);

Page 24: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) for(i=1;i<=n;i++) { fact=1; for(j=1;j<=i;j++) fact=fact*j; s=s+fact; } printf("sum of series = \t%ld",s); getch(); }

c. S = 2+4+6+8+……………N terms.

#include<stdio.h> #include<conio.h> void main() { int i,k,n,s=0; clrscr(); printf("enter number of terms "); scanf("%d",&n); k=2; for(i=1;i<=n;i++) { s=s+k; k=k+2; } printf("sum of series = \t%ld",s); getch(); }

d. S = -13 + 33 - 53 + 73 – 93 + 113 - ……..N terms. #include<stdio.h> #include<conio.h> #include<math.h> void main() { int i,k,n,s=0,sign=-1; clrscr(); printf("enter number of terms "); scanf("%d",&n); k=1; for(i=1;i<=n;i++) { s=s+sign*pow(k,3); k=k+2; sign=-1*sign; } printf("sum of series = \t%d",s); getch(); }

e. S = 1/1! + 2/2! + 3/3! + ………….. 7 terms.

#include<stdio.h> #include<conio.h> #include<math.h> void main() { int i,k,n,fact;float s=0;

Page 25: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) clrscr(); printf("enter number of terms "); //remove this line for 7 terms scanf("%d",&n); //remove this line for 7 terms for(i=1;i<=n;i++) //replace n by 7 to get sum upto 7 terms { fact=1; for(k=1;k<=i;k++) fact=fact*k; s=s+(float)i/fact; //printf("sum of series = \t%f",s); for step by step check //getch(); } printf("sum of series = \t%f",s); getch(); }

f. S = 14 + 34 + 54 + 74 + …………….. 100 terms #include<stdio.h> #include<conio.h> #include<math.h> void main() { int i,k,n;long int s=0; clrscr(); printf("enter number of terms "); //remove this line for 100 terms scanf("%d",&n); //remove this line for 100 terms k=1; for(i=1;i<=n;i++) //replace n by 100 to get sum upto 100 terms { s=s+pow(k,4); k=k+2; } printf("sum of series = \t%ld",s); getch(); } 25. Write a program to find number is even or odd. #include<stdio.h> #include<conio.h> void main() { int a; clrscr(); printf("Enter The Number to be checked"); scanf("%d",&a); if(a%2==0) { printf("Number %d is Even",a); } else { printf("Number %d is odd",a); } getch(); } 26. Write a program for finding year is leap or not. #include<stdio.h> #include<conio.h> void main( )

Page 26: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) { int year; printf("Enter the year: "); scanf("%d",&year); if(year%400 ==0 || (year%100 != 0 && year%4 == 0)) { printf("Year %d is a leap year",year); } else { printf("Year %d is not a leap year",year); } getch(); } 27. Admission to a professional course is subject to the following condition math>=60, phy>=50, chem>= 150. Write a program

for finding that candidates are eligible or not #include<stdio.h> #include<conio.h> void main() { int math,phy,chem; clrscr(); printf("Enter the marks math:"); scanf("%c",&math); printf("Enter the marks phy:"); scanf("%c",&phy); printf("Enter the marks chem:"); scanf("%c",&chem); if(math >= 60 && phy >= 50 && chem >= 40) { printf("Candidte is eligble"); } else { printf("Candidte is not eligble"); } getch(); } 28. Write a program to find gross salary of employee if DA is 40% of basic Salary and HRA is 20% of basic salary. Basic salary

input by keyboard. #include<stdio.h> #include<conio.h> void main() { int bs; float da,hra,gross; clrscr(); printf("Enter the basic salary:"); scanf("%d",&bs); da = (0.4*bs); hra = (0.2*bs); gross = bs+da+hra;

Page 27: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) printf("\nDearness allowance: %f",da); printf("\nHouse rent allowance: %f",hra); printf("\nGross salary: %f",gross); getch(); } 29. Write a program to print given format * * * * * * * * * * #include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for(i=1;i<=5;i++) { for(j=1;j<=i;j++) printf("* "); printf("\n"); } getch(); } 30. Write a program to print given format * * * * * * * * * * * * * * * * #include<stdio.h> #include<conio.h> void main() { int i ,j,k; clrscr(); for(i=1;i<=5;i++) { for(k=0;k<5-i;k++) printf(" "); for(j=1;j<=2*i-1;j++) printf("*"); printf("\n"); } getch(); } 31. Write a program for performing all arithmetic operation using switch case. #include<stdio.h> #include<conio.h> void main() { int a,b,n;

Page 28: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) float c; clrscr(); printf("Enter the number:"); scanf("%d%d",&a,&b); printf("1.Addition\n"); printf("2.Subtraction\n"); printf("3.Division\n"); printf("4.Multiply\n"); printf("5.Modulo Division\n"); printf("Enter ur choce:"); scanf("%d",&n); switch(n) { case 1: c=a+b; printf("Add:%f",c); break; case 2: c=a-b; printf("Sub:%f",c); break; case 3: c=a/b; printf("Div:%f",c); break; case 4: c=a*b; printf("Muli:%f",c); break; case 5: c=a%b; printf("Modulo Div:%f",c); break; default: printf("U enter worng choice"); } getch(); } 32. Write a program to print Fibonacci sequence 0 1 1 2 3 5 8 13…… N terms and prints the sum of

sequence. #include<conio.h> #include<stdio.h> void main() { int a=0,b=1,n,i,c=1,sum=1; clrscr(); printf("Enter the Last Number of series"); scanf("%d",&n); printf("\n The Fibbonacci Series is "); printf(" %d %d ",a,b); while(c!=n) { c=a+b; if(c>n) { break; } printf(" %d ",c); sum=sum+c; a=b; b=c;

Page 29: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University)

} printf("\n The Sum of fibbonacci Series is %d",sum); getch(); }

33. Write a program to print all prime numbers <= a given number. #include<conio.h> #include<stdio.h> void main() { int i, j, n,flag; clrscr(); printf("enter number upto which you want to print prime numbers "); scanf("%d",&n); for(i=2;i<=n;i++) { flag=0; for(j=2;j<i;j++) { if(i%j==0) flag=1; } if(flag==0) printf("\t%d",i); } getch(); } Second Method #include<conio.h> #include<stdio.h> void main() { int i, j, n; clrscr(); printf("enter number upto which you want to print prime numbers "); scanf("%d",&n); for(i=2;i<=n;i++) { for(j=2;j<i;j++) { if(i%j==0) break; } if(j==i) printf("\t%d",i); } getch(); } 34. Write a program in C to perform Sequential/Linear Search. (OR to Search a number in a given list) #include<stdio.h> #include<conio.h> void main() { int a[10],i, search_item;

Page 30: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) clrscr(); printf("enter ten no"); for(i=0;i<10;i++) { printf("enter the %d element of the array",i); scanf("%d",&a[i]); } printf("\n enter the element to be searched"); scanf("%d",&search_item); for(i=0;i<10;i++) { if(a[i]= =search_item) { printf("%d is present in the list",search_item); break; } } getch(); } 35. Write a program to find product, sum, average, max and min from a list of n numbers. #include<stdio.h> #include<conio.h> void main() { int a[20],i,n,prod=1,sum=0,max,min; float average; clrscr(); /* Determination of Size */ printf("Enter the size of List i.e. n not more than 20"); scanf("%d",&n); /* Entry the values into Array */ printf("\nEnter the %d values into array \n",n); for(i=0;i<n;i++) { printf("Enter the Number a[%d]",i); scanf("%d",&a[i]); } /* Product of Numbers */ for(i=0;i<n;i++) { prod=prod*a[i]; } /* Summation of Numbers */ for(i=0;i<n;i++) { sum=sum+a[i]; } average=sum/n; max=a[0]; min=a[0]; for(i=1;i<n;i++) { if(a[i]>max) max=a[i];

Page 31: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) } for(i=1;i<n;i++) { if(a[i]<min) min=a[i]; } printf("\nThe Product of %d Numbers=%d",n,prod); printf("\nThe Sum of %d Numbers=%d",n,sum); printf("\nThe Average of %d Numbers=%f",n,average); printf("\nThe Maximum of %d Numbers=%d",n,max); printf("\nThe Minimum of %d Numbers=%d",n,min); getch(); } 36. Write a ‘C’ program to swap two numbers: using third variable and without using third variable. With Third Variable: #include<stdio.h> #include<conio.h> void main() { int a,b,t; clrscr(); printf("Enter The Numbers to be swapped"); scanf("%d%d",&a,&b); printf("\n Numbers before swap are a=%d b=%d",a,b); /* Logic for Swap using third Variable */ t=a; a=b; b=t; printf("\n Numbers After swap are a=%d b=%d",a,b); getch(); } /* Without Third Variable: */ #include<stdio.h> #include<conio.h> void main() { int a,b; clrscr(); printf("Enter The Numbers to be swapped"); scanf("%d%d",&a,&b); printf("\n Numbers before swap are a=%d b=%d",a,b); /* Logic for Swap without using third Variable */ a=a+b; b=a-b; a=a-b; printf("\n Numbers After swap are a=%d b=%d",a,b); getch(); } 37. WAP to find the reverse of a number and check whether it is palindrome or not. #include<stdio.h> #include<conio.h> void main()

Page 32: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) { int n,num,rev=0,temp; clrscr(); printf("Enter The Number"); scanf("%d",&n); num =n; while(n!=0) { temp=n%10; rev=rev*10+temp; n=n/10; } printf("\nreverse of given number = %d",rev); if(rev==num) printf("\n%d is palindrom",num); else printf("\n%d is not palindrom",num); getch(); } 38. Write a program to accept three numbers and smallest number among them.

Smallest Number: #include<stdio.h> #include<conio.h> void main() { int a,b,c; printf(“enter 3 nos”); scanf(“%d%d%d”,&a,&b,&c); if((a<b)&&(a<c)) printf(“smallest no among given three no is %d”,a); else { if(b<c)

printf(“smallest no among given three no is %d”,b); else printf(“smallest no among given three no is %d”,c);} } getch(); }

Largest Number: #include<stdio.h> #include<conio.h> void main() { int a,b,c; printf(“enter 3 nos”); scanf(“%d%d%d”,&a,&b,&c); if((a>b)&&(a>c)) printf(“Largest no among given three no is %d”,a); else { if(b>c)

printf(“Largest no among given three no is %d”,b); else printf(“Largest no among given three no is %d”,c);} } getch(); }

Page 33: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 39. What is pointer? Write a C program to swap the values of two variables making use of pointers. Answer: Pointer: In general, Pointer is something, which points to something specific. With reference to C languahe, A pointer is a special variable, which holds the address of another variable. #include<stdio.h> #include<conio.h> void main() { int a,b; printf(“enter 2 values”); scanf(“%d%d”,&a,&b); swap(a,b); printf("%d%d",b,a); getch(); } swap(int *x,int *y) { int t; t=*x; *x=*y; *y=t; printf("%d%d",x,y); } 40. Write a program to calculate the factorial of a number without using function, using function and using recursion Without function

#include<stdio.h> #include<conio.h> void main() { int n,i; long int f=1; clrscr(); printf("Enter the number"); scanf("%d",&n); for(i=1;i<=n;i++) { f=f*i; } printf("The factorial is %ld",f); getch(); } Using function '#include<stdio.h>

#include<conio.h> long int fact(int n); void main() { int n,i; long int f; clrscr(); printf("Enter the number"); scanf("%d",&n); f=fact(n); printf("The factorial is %ld",f); getch(); } long int fact(int n) { long int f=1;

Page 34: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) int i; for(i=1;i<=n;i++) { f=f*i; } return(f); } Using Recursion #include<stdio.h> #include<conio.h> long int fact(int n); void main() { int n,i; long int f; clrscr(); printf("Enter the number"); scanf("%d",&n); f=fact(n); printf("The factorial is %ld",f); getch(); } long int fact(int n) { long int f; if(n==1) return(1); else f=n*fact(n-1); return(f); } 41. Write a program to find out the product/Multiplication of two matrices and print the product matrix. #include<stdio.h> #include<conio.h> void main() { int a[10][10],b[10][10],c[10][10],i,j,k,n; clrscr(); /* Determination of Size */ printf("Enter the size of matrix n (nxn) not nore than 10"); scanf("%d",&n); /* Entry of Matrix A */ printf("\nEnter the values in matrix A\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("Enter the Number a[%d][%d]",i,j); scanf("%d",&a[i][j]); } } /* Entry of Matrix B */ printf("\nEnter the values in matrix B\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++)

Page 35: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) { printf("Enter the Number b[%d][%d]",i,j); scanf("%d",&b[i][j]); } } /* Initialization of Matrix C */ for(i=0;i<n;i++) { for(j=0;j<n;j++) { c[i][j]=0; } } /* Multiplication of Matrix A & B */ for(i=0;i<n;i++) { for(j=0;j<n;j++) { for(k=0;k<n;k++) { c[i][j]=c[i][j]+a[i][k]*b[k][j]; } } } /* Printing of Matrix C */ printf("\nThe Matrix C\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("\t%d",c[i][j]); } printf("\n"); } getch(); } 42. Write a program to accept two matrices of the same order find out the sum of these matrices and print the sum of matrices. #include<stdio.h> #include<conio.h> void main() { int a[10][10],b[10][10],c[10][10],i,j,n; clrscr(); /* Determination of Size */ printf("Enter the size of matrix n (nxn) not nore than 10"); scanf("%d",&n); /* Entry of Matrix A */ printf("\nEnter the values in matrix A\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("Enter the Number a[%d][%d]",i,j); scanf("%d",&a[i][j]); } }

Page 36: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) /* Entry of Matrix B */ printf("\nEnter the values in matrix A\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("Enter the Number b[%d][%d]",i,j); scanf("%d",&b[i][j]); } } /* Addition of Matrix A & B */ for(i=0;i<n;i++) { for(j=0;j<n;j++) { c[i][j]=a[i][j]+a[i][j]; } } /* Printing of Matrix C */ printf("\nThe Matrix C\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("\t%d",c[i][j]); } printf("\n"); } getch(); } 43. WAP in C that accepts N*N matrix as input and print transpose of this matrix. #include<stdio.h> #include<conio.h> void main() { int a[10][10],b[10][10],i,j,n; clrscr(); /* Determination of Size */ printf("Enter the size of matrix n (nxn) not nore than 10"); scanf("%d",&n); /* Entry of Matrix A */ printf("\nEnter the values in matrix A\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("Enter the Number a[%d][%d]",i,j); scanf("%d",&a[i][j]); } } /* Transpose of Matrix A */ for(i=0;i<n;i++) { for(j=0;j<n;j++) {

Page 37: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) b[i][j]=a[j][i]; } } /* Printing of Matrix B */ printf("\nThe Matrix C\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("\t%d",b[i][j]); } printf("\n"); } getch(); } 44. Write a program in C to accept an integer numbers and find sum of digits. #include<stdio.h> #include<conio.h> void main() { int n,x,sum=0; clrscr(); printf("Enter The Number"); scanf("%d",&n); while(n!=0) { x=n%10; sum=sum+x; n=n/10; } printf("\nThe Sum of Digits is=%d",sum); getch(); } 45. Write a program to copy the contents of one file to another file.

#include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { FILE *fs,*ft; char ch; clrscr(); fs = fopen(“Source.c”,"r"); if(fs==NULL) { printf("Cannot open source file ! Press key to exit."); getch(); exit(0); } ft = fopen(“Destination.c”,"w"); if(ft==NULL) { printf("Cannot copy file ! Press key to exit."); fclose(fs); getch(); exit(0); }

Page 38: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University)

while(1) { ch = getc(fs); if(ch==EOF) { break; } else putc(ch,ft); } printf("File copied succesfully!"); fclose(fs); fclose(ft); }

46. What do you mean by structure? Declare a structure name student containing members name, roll_no, marks. Create an

array of 30 such students. Write a program to read and display the contents of array. Answer: Structure: A structure is basically a logical group of multiple items of different data types such as int, float etc. #include<stdio.h> #include<conio.h> struct student { char name[20]; int roll; char branch[10]; }; struct student std[100]; void main() { clrscr(); int i; for(i=0;i<100;i++) { printf("enter student detail"); scanf("%s%d%s",std[i].name,&std[i].roll,std[i].branch); } for(i=0;i<100;i++) printf("%s%d%s",std[i].name,std[i].roll,std[i].branch); getch(); } 47. Write a simple database program in C which stores personal details of 100 persons such as Name, Date of Birth, Address,

Phone number etc. #include<stdio.h> #include<conio.h> struct info { char name[20]; int pn; char dob[10]; char add[10]; }; struct info std[100]; void main() { clrscr(); int i;

Page 39: Computer Concept & programming in C Ankur Choudhary AP ... · Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) 2. Multi-user operating system: A

Computer Concept & programming in C Ankur Choudhary AP( ASET – Amity University) for(i=0;i<100;i++) { printf("enter student detail"); scanf("%s%d%s%s",std[i].name,&std[i].pn,std[i].dob,std[i].add); } for(i=0;i<100;i++) printf("%s%d%s%s",std[i].name,std[i].pn,std[i].dob,std[i].add); getch(); }