Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

Introduction to Computers What Is A Computer?

A computer is an electronic device, operating under the control of instructions (software) stored in its own memory unit, that can accept data (input), manipulate data (process), and produce information (output) from the processing. Generally, the term is used to describe a collection of devices that function together as a system. Devices that comprise a computer system
Monitor (output) Printer

Speaker (output)

System unit (Processor, memory)

Scanner (input)

Mouse (input) Keyboard (input) Storage devices (CD-RW, Floppy, Hard disk, zip,)

What Does A Computer Do? Computers can perform four general operations, which comprise the information processing cycle. Input Process Output Storage

Data and Information All computer processing requires data, which is a collection of raw facts, figures and symbols, such as numbers, words, images, video and sound, given to the computer during the input phase.

Computers manipulate data to create information. Information is data that is organized, meaningful, and useful.

During the output Phase, the information that has been created is put into some form, such as a printed report.

The information can also be put in computer storage for future use.

Why Is A Computer So Powerful? The ability to perform the information processing cycle with amazing speed.

Reliability (low failure rate). Accuracy. Ability to store huge amounts of data and information. Ability to communicate with other computers.

How Does a Computer know what to do? It must be given a detailed list of instructions, called a compute program or software that tells it exactly what to do.

Before processing a specific job, the computer program corresponding to that job must be stored in memory.

Once the program is stored in memory the compute can start the operation by executing the program instructions one after the other.

What Are The Primary Components Of A Computer? Input devices.

Central Processing Unit (containing the control unit and the arithmetic/logic unit).

Memory. Output devices. Storage devices.

Input Devices
Keyboard. Mouse.

The Keyboard The most commonly used input device is the keyboard on which data is entered by manually keying in or typing certain keys. A keyboard typically has 101 or 105 keys.

The Mouse Is a pointing device which is used to control the movement of a mouse pointer on the screen to make selections from the screen. A mouse has one to five buttons. The bottom of the mouse is flat and contains a mechanism that detects movement of the mouse.

The Central processing Unit The central processing unit (CPU) contains electronic circuits that cause processing to occur. The CPU interprets instructions to the computer, performs the logical and arithmetic processing operations, and causes the input and output operations to occur. It is considered the brain of the computer.

Memory Memory also called Random Access Memory or RAM (temporary memory) is the main memory of the computer. It consists of electronic components that store data including numbers, letters of the alphabet, graphics and sound. Any information stored in RAM is lost when the computer is turned off. Read Only Memory or ROM is memory. It is permanent memory. Output Devices Output devices make the information resulting from the processing available for use. The two output devices more commonly used are the printer and the computer screen.

The printer produces a hard copy of your output, and the computer screen produces a soft copy of your output.

Storage Devices Auxiliary storage devices are used to store data when they are not being used in memory. The most common types of auxiliary storage used on personal computers are floppy disks, hard disks and CD-ROM drives. .

Hard Disks

Another form of auxiliary storage is a hard disk. A hard disk consists of one or more rigid metal plates coated with a metal oxide material that allows data to be magnetically recorded on the surface of the platters.

The hard disk platters spin at a high rate of speed, typically 5400 to 7200 revolutions per minute (RPM).

Storage capacities of hard disks for personal computers range from 10 GB to 120 GB (one billion bytes are called a gigabyte).

Computer Software Computer software is the key to productive use of computers. Software can be categorized into two types:

Operating system software Application software.

Operating System Software


Operating system software tells the computer how to perform the functions of loading, storing and executing an application and how to transfer data. Today, many computers use an operating system that has a graphical user interface (GUI) that provides visual clues such as icon symbols to help the user. Microsoft Windows 98 is a widely used graphical operating system. DOS (Disk Operating System) is an older but still widely used operating system that is textbased.

Application Software Application Software consists of programs that tell a computer how to produce information. Some of the more commonly used packages are:

Word processing Electronic spreadsheet Database Presentation graphics

Word Processing

Word Processing software is used to create and print documents. A key advantage of word processing software is that users easily can make changes in documents.

Electronic Spreadsheets

Electronic spreadsheet software allows the user to add, subtract, and perform user-defined calculations on rows and columns of numbers. These numbers can be changed and the spreadsheet quickly recalculates the new results.

Database Software

Allows the user to enter, retrieve, and update data in an organized and efficient manner, with flexible inquiry and reporting capabilities.

Presentation Graphics

Presentation graphic software allows the user to create documents called slides to be used in making the presentations. Using special projection devices, the slides display as they appear on the computer screen.

Compliers and interpreters High level languages are called either compiled languages or interpreted languages. In a compiled language, a translation program is run to convert the programmers entire high level program, which is called the source code, into a machine language code. This translation process is called compilation. Some of the most widely used compiled languages are c, c++, cobol , fortran. In an interpreted language, a translation program converts each program statement into machine code just before the program statement is to be executed. The most frequently used interpreted language is BASIC. The compilation process Source file --compiler ----object file ---linker ---executable program

Run time library

Computer Language /Programming language A language thats is acceptable to a computer system is called computer language or programming language , and the process of writing instructions in such a language for an already planned program is called programming or coding. A computer language is used by a programmer to instruct a computer what he/she wants it to do. Natural language has a systematic method using the words and symbols of that language, which is defined by the grammar rules of the language. Similarly, the words and symbols of a computer language must also be used as per set rules, which are known as the syntax rules of the language. Computer languages can be broadly classified into three categories. Machine language Assembly language High-level language Machine Language Computers can be programmed to understand many different computer languages, there is only one language understood by the computer without using translation program. This language is called the machine language. The machine language of computer is normally written as binary 1s and 0s. A Machine language instruction has two-part format. The first part of an instruction is the operation code, which tells the computer what function to perform, and the second part is the operand, which tells the computer where to find or store the data or other instructions, which are to be manipulated.

Machine Language EG: Opcode (Operation code) Operand (Address/Location)

Advantages and limitations of Machine Language

Programs written in machine language can be executed very fast by the computer. This is because machine instructions are directly understood by the computer, and no translation of the program. Disadvantages Machine dependent because the internal design of every type of computer is different from every other type of computer, the machine language also differs from computer to computer. Difficult to program It is necessary for the programmer to memorize the dozens of operation code numbers for the commands. Error prone(level) For writing programs in machine language, since a programmer has to remember the opcodes, and must keep track of the storage locations of data and instructions, it becomes very difficult for him/her to concentrate fully on logic of the problem. Difficult to modify: its difficult to correct or modify machine language programs. Checking machine instructions to locate errors is very difficult and time consuming. In Short, writing a program in machine language is so difficult and time consuming that it is rarely used today.

Assembly language Assembly language programming, which was introduced in 1952, helped in overcoming the above listed limitations of machine language programming. A language, which allows instructions and storage locations to be represented by letters and symbols, instead of numbers is called an assembly language or symbolic language. Assembler An assembly language program must be converted into its equivalent machine language program, before it can be executed on the computer. This translation is done with the help of a translator program, which is known as assembler. EG:

Mnemonic Opcode ADD SUB 14 15 Assembler ----------Machine language

Assembly language program------ program Advantages Easier to understand and use

Due to the use of mnemonics, instead of numeric op codes, and symbolic names and locations, assembly language programs are much easier to understand. Easier to locate and correct errors Easier to modify No worry about address Easily relocatable

Limitation of Assembly language Machine dependent Knowledge of hardware required Machine level coding. High Level language They are machine independent That is, a program written in a high level language can be easily ported and executed on any computer, which has the translator software for high level language. They dont require the programmers to know anything about internal structure of the computer on which the high level language programs will be executed. This allows the programmers to mainly concentrate on the logic of the problem, rather than be concerned with details of internal structure of the computer. High level language program (source program) ------Complier------Machine language program (object program) Linker is used to properly combine all the object program files (modules) of the software, and to convert them into the final executable program, Advantages of high level languages

Machine independence Easier to understand Fewer error Lower program preparation cost Better documentation Easier to maintain Selecting a language for coding an application Nature of the application Familiarity with the language Ease of learning the language Availability of program development tools. Execution efficiency Features of a good programming language (simplicity, naturalness, extensibility and etc) Five levels of language Machine language /first generation language Assembly language/second generation language Procedural language/third generation language General purpose languages are called procedural languages. (eg. BASIC, COBOL, FORTRAN) Problem oriented language/fourth generation language High level languages designed to solve specific problems or develop specific applications. Natural language/fifth generation language Natural language are still in the development stages .(egs artificial intelligence and expert system)

Algorithm A step by step procedure to solve a problem Properties o A finite sequence of steps o Each step shall be explicit and unambiguous Algorithms are not specific to any programming language An algorithm can be implemented in any programming language An algorithm is just steps that are needed to solve a given problem. Algorithm o Identify the Inputs and Outputs o Identify any other data and constants required to solve the problem o Identify what needs to be computed o Write an algorithm Let us now take an example. Iterative refinement: This is stepwise refinement of the algorithm to get to the actual solution Ex. Taking names, then marks, validating marks, finding average Algorithm Example Find the average marks scored by a student in 3 subjects: BEGIN Step 1 : Accept 3 marks say Marks1, Marks2, Marks3 scored by the student Step 2 : Add Marks1, Marks2, Marks3 and store the result in Total Step 3 : Divide Total by 3 and find the Average Step 4 : Display Average END To find the average marks scored by a student in three subjects. Read the problem statement and find out What is the input required to solve the problem ( marks scored in 3 subjects in case of the example above) What is the processing needed on the input that will generate the desired Output (the marks are added and the total is divided by 3 to get average) What is the output (the result we get is average which is displayed back to the user) The above algorithm can be written in precise steps.

Algorithm-Example Find the average marks scored by a student in 3 subjects: BEGIN

Step 1 : Read Marks1, Marks2, Marks3 Step 2 : Sum = Marks1 + Marks2 + Marks3 Step 3 : Average = Sum / 3 Step 4 : Display Average END Use of Algorithms Facilitates easy development of programs Iterative refinement Easy to convert it to a program Review is easier Different Patterns in Algorithms Sequential Sequential constructs execute the program in the order in which they appear in the program Selectional (Conditional) Selectional constructs control the flow of statement execution in order to achieve the required result Iterational (Loops) Iterational constructs are used when a part of the program is to be executed several times Example Selectional Write a program to find the average marks of a student. Also check whether the student has passed or failed. For a student to pass, average marks should not be less than 65. BEGIN Step 1 : Read Marks1, Marks2, Marks3 Step 2 : Total = Marks1 + Marks2 + Marks3 Step 3 : Average = Total / 3 Step 4 : Set Output = Student Passed Step 5 : if Average < 65 then Set Output = Student Failed Step 6 : Display Output END

Example Iterational Find the average marks scored by N number of students BEGIN Step 1 : Read NumberOfStudents Step 2 : Counter = 1 Step 3 : Read Marks1, Marks2, Marks3 Step 4 : Total = Marks1 + Marks2 + Marks3

Step 5 : Average = Total / 3 Step 6 : Set Output = Student Passed Step 7 : If (Average < 65) then Set Output = Student Failed Step 8 : Display Output Step 9 : Counter = Counter + 1 Step 10 : If (Counter <= NumberOfStudents ) then goto step 3 END Programming Methodologies o Classification based on behavior Sequential Approach Event Driven Approach o Classification based on structure Structured Programming Object Oriented Programming Structured programming is built on systematically breaking down the problem into modules .The programs are organized into modules that are coded using independent functions and data. Eg. BASIC/ FORTRAN/ MSDOS programs Definition of Structured Programming: A Technique for organizing and coding computer programs in which a hierarchy of modules is used, each having a single entry and a single exit point, and in which control is passed downward through the structure without unconditional branches to higher levels of the structure. Object oriented programming style results in programs that are organized into objects that encapsulate functions and data. Eg. C++ / Java / Windows programming. Sequential programming results in programs that allow the user to follow a predefined sequence of events. For example if there is a structured program written to accept student info the sequence in which this input is prompted is fixed. Any user using the application has to necessarily enter the input in that sequence only. Eg. MS DOS programs/CUI (Character User Interface) applications Event driven programming - the user can control the flow of events and may choose the sequence of events. In such cases the UI is displayed to the user. User is then allowed to enter the input in the sequence which the user wants. The program waits for the user to send a message (by raising a event) which is processed and the program proceeds with execution. Eg. Windows/GUI (Graphical User Interface) programs. History and Features of C Dennis Ritchie is the creator of C Created at Bell Laboratories Portable Language C language is machine independent. Source Code written using C can be compiled on any machine Structured Language Problem is solved using a divide and conquer approach

NOTE: C is used as the language to teach Programming Fundamentals. Programming fundamentals does not cover all aspects of C. A person proficient in C can easily pick up other languages. Comments Comments are used to document programs and improve readability In C a comment will start with /* and ends with */ Syntax: /* Comments */ /*This is a single line comment */ /* This is a multiline * comment in C */ /**************************************************** * This style of commenting is used for functions ****************************************************/ Variables o Hold the data in your program o Is a location (or set of locations) in memory where a value can be stored for use by a program o A quantity that can change during program execution Variable Names o A variable name can either begin with an alphabet or underscore o No other special character except underscore is allowed o Maximum characters recognized is 31 (compiler dependent) o Variable names are case sensitive o Keywords cannot be used as variable names

Data Types o Data types determine the following: Type of data stored Number of bytes it occupies in memory Range of data Operations that can be performed on the data o C supports the following data types: int for storing whole numbers char for storing character values, represents a single character float double o Note: float and double data types are used to store fractional values. o float can store up to 6 digits of precision o double can store up to 12 digits of precision Data types specify various formats that data can appear in. The fundamental data types are the basic building blocks for all the other data types. Primitive data types: o Basic/Primitive data types supported by C are:

o int for storing integer values. Size will vary from 2 bytes 4 bytes o char for storing character values Size is 1 byte o float for storing decimal values single precision values are stored where number of digits of precision after the decimal point is 6. o double used to store decimal values of 12-digit precision o char data types in C are represented using ASCII coding format. ASCII stands for American Standard Code for Information Interchange. True and false values in C: C does not have a boolean data type. In C, a true value is any non zero value including negative numbers. A false value is zero. Declaration of variables Syntax: data-type [variable-name list] data-type variable-name1 , variable-name2, ; Example: int iNum; Declares a variable of int data type The variables will contain some garbage value when they are declared. A variable can be initialized when it is declared int iNum = 10; float fData = 2.3F ; char cChoice = Y;

A complete C program: #include <stdio.h> // Pre processor directive void main() // Entry point for program execution { printf(Hello World);// Each instruction in a C program terminates with a semicolon (;) } Explanation Each C-program has a main function Execution of a program starts from main() Hello World is a string literal and is displayed as it is. A block of code begins with an opening curly brace and ends with a closing curly brace. The first line of the program is pre processor directive. Directives are executed during the preprocessor phase, a phase prior to compilation phase. The program begins its execution with the first instruction in the main function. The instruction is a print instruction that prints Hello World on the screen. printf() is a predefiend function of the std I/O library which is made available to your program by including it using a #include directive.

Other predefined function is scanf() for accepting input from the user during execution. Each instruction in a C program terminates with a semicolon. Comments are inserted in the program and more clarity and readability of the programs. They are enclosed between /*.*/ or proceeded by //. Preprocessor Directives C provides many built-in functions, also called as library functions. These functions are declared in header files. To use them, weve to include proper header files in our program using #include statement. e.g.: #include <stdio.h> More Header files in C: math.h string.h limits.h types.h Each standard library has a corresponding header file containing the function prototypes for all the functions in that library and definitions of various data types and constants needed by those functions.

Compiler and Linker Errors o If a program do not follow the syntax of a language then the compiler raises errors Example: Missing semicolon, improper use of key words o When the linker is not able to find a piece of code the linker errors are generated Example: Variable or function referenced, but not defined anywhere in code Operators In C

Assignment operator = Arithmetic operators +, -, *, /, % Relational operators >, >=, <, <=, == , != Logical operators !, &&, || Address operator & Increment and Decrement operators ++, -Compound Assignment Operators =, +=, -=, /=, *=, %= sizeof operator Arithmetic operators The % (modulo operator) is used to find the reminder of a divide operation o eg.int x=5,y=2; o int z=5/2; will store 2 in z o int z=5%2 will store 1 in z o % operator cannot be applied to float data type. Hence the instruction 5.2 % 2.5 will result in error. For comparing if 2 values are equal or not remember to use == and not a single =. == indicates comparisons and = indicates assignment operation. o eg. int x=5,y=3 o x==y will be considered as an conditional expression that will be evaluated to true(non-zero) for false(zero) o x=y will be considered as an assignment expression which will assign 3 (value of y) to x. x after the instruction will have value 3. Logical operators ! (NOT), && (AND), || (OR) eg. consider 3 variables x,y,x containing values 1,2,3 respectively x=1, y=2, z=3 The condition x==1 && y == 3 will evaluate to false The condition x==1 && z==3 will evaluate to true The condition x==1 || y==3 will evaluate to true The condition x==1 || z==3 will evaluate to true The condition !(x <2 && y==2) will evaluate to false

Increment and Decrement Operators Operators ++ and - are called as increment and decrement operators These operators increment or decrement the variables value by 1 They are also called as unary operators because they have only one operand to operate If the operator is used before the operand, it is prefix and if the operator is used after the operand, it is postfix

Example: ++iValue and -iValue is called as prefix iValue++ and iValue-- is called as postfix

Difference between prefix and postfix Prefix operator first increments / decrements and then makes the assignment Example: int iValue; int iResult; iValue = 5; iResult = ++iValue;

Difference between prefix and postfix Post fix operator makes the assignment and then increments/decrements the value Example: int iValue; int iResult; iValue = 5; iResult = iValue++;

Address of Operator Ampersand (&) is the address of operator It is used to fetch the memory address of a variable

Precedence of Arithmetic Operators Operator Priority , / and % Highest + and - Lowest The expression that is written within parenthesis is given highest priority

Format Specifier (sometimes called Conversion Specifier): These characters tell the input or output functions as to what type of data is being read or written. Few Format Specifiers that can be used in a printf statement: %d signed decimal integers

Formatted output using printf (3 of 4) An escape sequence is interpreted to have a special meaning in the screen output All the escape sequences must be preceded by a back slash (\) Escape sequences are non printable characters Escape sequences are generally used with printf function

Escape Sequence Purpose \n New line character. This moves the cursor to the next line \t Prints a sequence of blank spaces. \\ Prints back slash (\). \ Prints the double quote () \ Prints a single quote (). \a Causes an audible sound on the computer

Fundamental Algorithms EXCHANGING VALUES OF TWO VARIABLES Requirement : If we have variables with values like this, A = 10 B = 20 At the end of Running your logic, the values in the variables should be exchanged, that is A = 20 B = 10 Algorithm 1 ( By using Third variable) 1) 2) 3) 4) 5) 6) 7) Have two variables ready by declaring. Get First value from the user and store it in First variable. Get another value and store it in second variable. Declare another variable, say temp Store the value in the First Variable in the Temp variable Store the value in the Second variable in the First Variable Store the value in the temp variable to the Second Variable

Temp = A A= B B = Temp Program Logic : int a , b; scanf(%d%d, &a,&b); temp = a; a = b; b = temp;

EXCHANGING VALUES OF TWO VARIABLES Algorithm 2 (Without using a Third Variable) :

1) 2) 3) 4) 5)

Have two variables ready by declaring. Get First value from the user and store it in First variable. Get another value and store it in second variable. Add the two values and store it in First Variable Subtract value in second variable from value in First Variable and store it in second variable 6) Subtract value in second variable from value in first variable and store the result in first variable

Logic Sequene with pseudocode : a = a + b; b = a b; a = a b; Program Logic : int a , b; scanf(%d%d, &a,&b); a = a + b; b = a b; a = a b;

COUNTING SET OF NUMBERS Requirement : User goes on entering the numbers as inputs, once the user is done with entering giving the inputs, the logic should say the COUNT of Numbers he has inputted. We can use arrays to store the numbers the user is inputting

Algorithm 1) 2) 3) 4) 5) Declare an integer array named numberSet with a large Pre-Determined size Have a character variable named Choice Have a variable called Count to store the count of numbers, which is the output Initialize Count to 0 Start a loop that runs for i value from 0 to (Pre-Determined size of array -1)

5.1) Get integer value from the user and store it array numberSet[]using i value as index value 5.2) Increment Count value 5.3) Ask the user if he wants to continue inputting number 5.4) Get character input from user and store it in choice variable 5.5) If value in Choice variable is equal to Y (yes) or y (yes) , then CONTINUE the loop or else BREAK the loop. 6) Display the value in the count

Program Logic Sequence int numberSet[100000] char Choice; int Count = 0, i, for ( i = 0 ; i <= (100000 1) ; i++) { scanf(%d,&numberSet[i]); Count++; printf(Do you want to input more ?); scanf(%c,&Choice); if ((Choice == Y) || (Choice = = y)) continue; else break; } printf( Count of Numbers in the Array is %d , Count); SUMMATION OF SET OF NUMBERS Requirement : Have to get Set of Numbers from the user and Display the Summed up value of the Set of Numbers. Algorithm : (Without Array usage) 1) Have one variable say sum with value initialized to zero 2) Get the Count value of Numbers in the set from the user. 3) Start a Loop, that runs for the Count value number of times 3.1) Get the value from the user 3.2) Add the input value with the sum 4) Print the Value that is in the sum

Program Sequence : (Without Array Usage) int Sum = 0; int Count, i, Value printf( How many Numbers are in the set); scanf(%d, &count); for( i = 1; i <= Count ; count++) { Scanf(%d, &Value); Sum = Sum + Value ; } Printf(The summation of set of numbers is %d , Sum); Program Sequence : (With Array Usage) int numSet[10] = { 23, 54, 5, 3, 223, 32, 1, 21, 12, 18}; int Sum = 0; for( i = 0; i <= 9 ; count++) { Sum = Sum + numSet[i] ; } printf(The summation of set of numbers is %d , Sum);

FACTORIAL COMPUTATION Requirement : Have to get an integer value from the user and display its Factorial Value For example, 5! Means - 1 * 2 * 3 * 4 * 5 = 120

Algorithm

1) Get the value to be computed from the user and store it in Val 2) Declare Variable for storing the result say Factorial 3) Store value 1 in the Factorial variable 4) Run a Loop that runs for i value from 1 to Val number of times 4.1) Multiply value in Factorial variable with i and store it back in Factorial 5) Display the value in Factorial Variable

Program Sequence for the Logic :

int Val ; int Factorial = 1; int i; printf(Enter the Value to compute Factorial for); scanf(%d, &Val); for( i = 1; i <= Val ; i++) { Factorial = Factorial * i ; } Printf(The Factorial of %d is %d , Val, Factorial);

Exchanging the values of two variables Problem Given two variables, a and b, exchange the values assigned to them. Algorithm development The problem of interchanging the values associated with two variables. Example A -721 B -463 After Swap A-463 B-721 Algorithm description I. Save the original value of a in t. II. Assign to a the original value of b. III. Assign to b the original value of a that is stored in t. Swapping the two variables using Temporary variable #include<stdio.h> #include<conio.h> main() { int a=10; int b=50; int t; clrscr(); printf("before swapping"); printf("%d%d",a,b); t=a;

a=b; b=t; printf("after swapping"); printf("%d%d",a,b); getch(); } Output : 50,10 Swapping the two variables without using Temporary variable #include<stdio.h> #include<conio.h> main() { int a=10; int b=50; clrscr(); printf("before swapping"); printf("%d%d",a,b); a=b; b=a; printf("after swapping"); printf("%d%d",a,b); getch(); } Output: 50 ,50

Swapping the two variables using Temporary variable #include<stdio.h> #include<conio.h> main() { int a=10; int b=50; int t; clrscr(); printf("before swapping"); printf("%d%d",a,b); t=a; a=b; b=t; printf("after swapping"); printf("%d%d",a,b);

getch(); } Output : 50,10 Sorting(ascending) an array using swapping concept #include<stdio.h> #include<conio.h> main() { int a[5]={83,42}; int t,i,j; clrscr(); for(i=0;i<2;i++) { for(j=0;j<2;j++) { if(a[i]<a[j]) { t=a[i]; a[i]=a[j]; a[j]= t; printf("\n%d%d%d%d",i,j,a[i],a[j]); } } } printf("\n"); for(i=0;i<2;i++) { printf("%d",a[i]); } getch(); } Output: 108342 4283 ************************************************************************ Counting Problem Given set of n students examination marks make a count of the number of students that passed the examination. A pass awarded for all marks of 20 and above. Example Set of marls ={20,40,50,30,10,20} No.of.passed =5

Algorithm development I. Prompt the read the number of marks to be processed. II. Initialize count to zero; III. While there are still marks to be processed repeatedly do a. Read next mark b. If it is pass(ie >=20) then add one to count. IV. Write out total number of passes Count how many numbers are greater than or equal to 20(Using 2 step) #include<stdio.h> #include<conio.h> main() { int sub[5]={10,20,30,40,50}; int count,ccount=0; clrscr(); for(int i=0; i<5;i++) { if(sub[i]>=20) { count=1; ccount=ccount+count; } } printf("%d",ccount); getch(); } ************************************************************************ Summation of a set of numbers Problem Given set of n numbers design an algorithm that adds these numbers and returns the resultant sum. Example Set of marls ={20,40,50,30,10,20} Sum=170 Algorithm description I. Prompt and read in the number of numbers to be summed. II. Initialize sum for zero numbers. III. While less than n numbers have been summed repeatedly do a. Read in next number b. Compute current sum by adding the number read to the most recent sum. IV. Write sum of n numbers.

Program #include<stdio.h> #include<conio.h> main() { int mark[5]={23,43,56,12,40}; int sum=0,i; clrscr(); for(i=0;i<5;i++) { sum=sum+mark[i]; } printf("%d",sum); getch();} Factorial Computation Problem : Given a number n,compute n factorial where n>0 Example N!=N*(N-1)! 4!=4*3! 3!=3*2! 2!=2*1! 1!=1*0! 4!=4*3*2*1=24. Program Method 1 #include<stdio.h> #include<conio.h> main() { int fn=1; clrscr(); for(int i=5;i>0;i--) { fn=fn*i; } printf("%d",fn); int n=6; int fact=1; clrscr(); while(n>0) { fact=fact*n; n--;

} Method 2 int n=5; int fact=1; clrscr(); do { fact=fact*n; n--; }while(n>0); printf("%d",fact); getch(); } Generation of the Fibonacci sequence Problem: Generate and print the first n terms of the Fibonacci sequence where n>=1 The first few terms are 0,1,1,2,3,5,8,13,. Algorithm development I. Prompt and read n, the number of Fibonacci numbers to be generated. II. Assign first two Fibonacci numbers a and b. III. Initialize count of number generated. IV. While less than n Fibonacci numbers have be generated do a. Write out nest two Fibonacci numbers b. Generate next Fibonacci number keeping a relevant. c. Generate next Fibonacci number from most recent pair keeping relevant for next computation. d. Update count of number of Fibonacci number generated, i. V. If n even then write out last two Fibonacci numbers else write out second last Fibonacci number. Program Method 1 #include<stdio.h> #include<conio.h> main() { int a=0; int b=1; int c; int i=2; int n=10; clrscr(); printf("%d%d",a,b);

while(i<=n) { c=a+b; a=b; b=c; i--; printf("%d" ,c); } }

Method 2: #include<stdio.h> #include<conio.h> void main() { int x=0, y=1; clrscr(); printf("%d, %d, ",x,y); for(i=0;i<n;i++) { f=x+y; x=y; y=f; printf("%d, ",y); }// end of for loop }//end of main ************************************************************************ Reversing the Digits of an integer Problem: Design an algorithm that accepts a positive integer and reverse the order of its digits. Example Intput 27953 Output 35972 Algorithm Description I. Establish n, the positive integer to be reversed. II. Set the initial condition for reversed integer q. III. While the integer being reversed is greater than zero do a. Use the remainder function to extract the right most digit of the number being reversed. b. Use integer division by 10 to remove the last rightmost digit from the number being reversed. program #include<stdio.h> #include<conio.h> main()

{ int n=12356; clrscr(); int q; while(n>0) { q=n%10; n=n/10; printf("%d" ,q);}} Method 2: #include<conio.h> void main() { int n,rev=0,r; clrscr(); printf("enter the number : "); scanf("%d",&n); while (n>0) { r=n%10; n=n/10; rev=rev*10+r; }// end of while loop printf("%d",rev); } Base Conversion Problem: Convert a decimal integer to its corresponding octal representation

Example 43 octal equivalent is 53 43%8=3 43/8=5 53 decimal equivalent is 43 3*80 =3 5*81 =40 program void main() { int i=0,j=0,rem=0,a[10],b[10]; long int num;

clrscr(); printf("\nEnter a number :"); scanf("%ld",&num); while(num) { if(num<8) { a[j++]=num; break; } else { a[j++]=num%8; num=num/8; } } for(i=j-1;i>=0;i--) b[rem++]=a[i]; printf("\nOctal equivalent :"); for(j=0;j<rem;j++) printf("%d",b[j]); getch(); }

Sample 2:

4.Base Conversion ________________ i) decimal to binary

#include<stdio.h> #include<conio.h> void main() { int i,k,num,arr[10],n=0; scanf("%d",&num); while(num>1) {arr[i++]=num%2; num=num/2; } arr[i]=num; } while(k=i;k>=0;k--)

n=n*10+arr[k]; prinrf("%d",n); }//end of main

ii) decimal to octal

#include<stdio.h> #include<conio.h> void main() { int i,k,num,arr[10],n=0; scanf("%d",&num); while(num>1) {arr[i++]=num%8; num=num/8; } arr[i]=num; } while(k=i;k>=0;k--) n=n*10+arr[k]; prinrf("%d",n); }//end of main

iii) decimal to Hexa

#include<stdio.h> #include<conio.h> void main() { int i,k,num,n=0; char arr[10]; scanf("%d",&num); while(num>1) { arr[i++]=num%16; num=num/16; } arr[i]=num; }

while(k=i;k>=0;k--) { switch(arr[k]) { case 10 : printf("A");break; case 11 : printf("B");break; case 12 : printf("C");break; case 13 : printf("D");break; case 14 : printf("E");break; case 15 : printf("F");break; default : printf("%d",arr[k]); } }//end of main Character to Number conversion Problem : convert character in to number (ASCII) ASCII: ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as 'a' or '@' or an action of some sort. ASCII was developed a long time ago and now the non-printing characters are rarely used for their original purpose. Below is the ASCII character table and this includes descriptions of the first 32 non-printing characters. ASCII was actually designed for use with teletypes and so the descriptions are somewhat obscure. If someone says they want your CV however in ASCII format, all this means is they want 'plain' text with no formatting such as tabs, bold or underscoring - the raw format that any computer can understand

Sample Program #include<stdio.h> #include<conio.h> void main() { char ch; clrscr(); do { printf("enter a character : "); getchar(ch); printf("%d",ch); //prints the element till new line character }while(ch!='\n'); }

You might also like