Page 1 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , UNIT -I, INTRODUCTION TO COMPONENTS OF, A COMPUTER SYSTEM, , Disks primary and secondary memory, processor, operating system, compilers, creating, compiling and, executing a program etc., Number systems Introduction to Algorithms: steps to solve logical and numerical, problems. Representation of Algorithm, Flowchart/Pseudo code with examples, Program design and, structured programming. Introduction to Algorithms: steps to solve logical and numerical problems., Representation of Algorithm, Flowchart/Pseudo code with examples, Program design and structured, programming, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 1
Page 2 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , BASIC COMPONENTS OF A COMPUTER, A computer is a system made of two major components: hardware and software. The computer, hardware is the physical equipment. The software is the collection of programs (instructions) that allow, the hardware to do its job., , Computer, System, Hardware, , Software, HARDWARE, , COMPONENTS OF THE COMPUTER SYSTEM, The hardware components of the computer system consists of five parts: input devices, central, processing unit (CPU) ,primary storage, output devices, and auxiliary storage devices., , The input device is usually a keyboard where programs and data are entered into the computers., Examples of other input devices include a mouse, a pen or stylus, a touch screen, or an audio input unit., The central processing unit (CPU) is responsible for executing instructions such as arithmetic, calculations, comparisons among data, and movement of data inside the system. Today’s computers may, have one ,two, or more CPUs .Primary storage ,also known as main memory, is a place where the, programs and data are stored temporarily during processing. The data in primary storage are erased, when we turn off a personal computer or when we log off from a time-sharing system., , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 2
Page 3 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , The output device is usually a monitor or a printer to show output. If the output is shown on the, monitor, we say we have a soft copy. If it is printed on the printer, we say we have a hard copy., Auxiliary storage, also known as secondary storage, is used for both input and output. It is the place, where the programs and data are stored permanently. When we turn off the computer, or programs and, data remain in the secondary storage, ready for the next time we need them., SOFTWARE COMPONENTS OF THE COMPUTER SYSTEM, Computer software is divided in to two broad categories: system software and application software, .System software manages the computer resources .It provides the interface between the hardware and, the users. Application software, on the other hand is directly responsible for helping users solve their, problems., Software, , System, software, , Operating, Systems, , System, support, , Application, software, System, Development, , General, Purpose, , Application, Specific, , Fig: Types of software, System Software:, System software consists of programs that manage the hardware resources of a computer and, perform required information processing tasks. These programs are divided into three classes: the, operating system, system support, and system development., The operating system provides services such as a user interface, file and database access, and, interfaces to communication systems such as Internet protocols. The primary purpose of this software is, to keep the system operating in an efficient manner while allowing the users access to the system., System support software provides system utilities and other operating services. Examples of, system utilities are sort programs and disk format programs. Operating services consists of programs, that provide performance statistics for the operational staff and security monitors to protect the system, and data., last system software category ,system development software, includes the language translators, that convert programs into machine language for execution ,debugging tools to ensure that the programs, are error free and computer –assisted software engineering(CASE) systems., Application software, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 3
Page 4 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Application software is broken in to two classes: general-purpose software and application –, specific software. General purpose software is purchased from a software developer and can be used, for more than one application. Examples of general purpose software include word processors, database, management systems ,and computer aided design systems. They are labeled general purpose because, they can solve a variety of user computing problems., Application –specific software can be used only for its intended purpose., A general ledger system used by accountants and a material requirements planning system used by a, manufacturing organization are examples of application-specific software. They can be used only for the, task for which they were designed they cannot be used for other generalized tasks., The relationship between system and application software is shown in fig-2.In this figure, each, circle represents an interface point .The inner core is hard ware. The user is represented by the out layer., To work with the system,the typical user uses some form of application software. The application, software in turn interacts with the operating system ,which is apart of the system software layer. The, system software provides the direct interaction with the hard ware. The opening at the bottom of the, figure is the path followed by the user who interacts directly with the operating system when necessary., , COMPUTER LANGUAGES:, To write a program for a computer, we must use a computer language. Over the years computer, languages have evolved from machine languages to natural languages., 1940’s, 1950’s, 1960’s, , Machine level Languages, Symbolic Languages, High-Level Languages, , Machine Languages, In the earliest days of computers, the only programming languages available were machine, languages. Each computer has its own machine language, which is made of streams of 0’s and 1’s., Instructions in machine language must be in streams of 0’s and 1’s because the internal circuits, of a computer are made of switches transistors and other electronic devices that can be in one of two, states: off or on. The off state is represented by 0 , the on state is represented by 1., The only language understood by computer hardware is machine language., VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 4
Page 5 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Symbolic Languages:, In early 1950’s Admiral Grace Hopper, A mathematician and naval officer developed the, concept of a special computer program that would convert programs into machine language. The early, programming languages simply mirror to the machine languages using symbols of mnemonics to, represent the various machine language instructions because they used symbols, these languages were, known as symbolic languages., Computer does not understand symbolic language it must be translated to the machine language., A special program called assembler translates symbolic code into machine language. Because symbolic, languages had to be assembled into machine language they soon became known as assembly languages., Symbolic language uses symbols or mnemonics to represent the various ,machine language instructions., High Level Languages:, Symbolic languages greatly improved programming effificiency; they still required programmers, to concentrate on the hardware that they were using. Working with symbolic languages was also very, tedious because each machine instruction has to be individually coded. The desire to improve, programmer efficiency and to change the focus from the computer to the problem being solved led to the, development of high-level language., High level languages are portable to many different computers, allowing the programmer to concentrate, on the application problem at hand rather than the intricacies of the computer. High-level languages are, designed to relieve the programmer from the details of the assembly language. High level languages, share one thing with symbolic languages, They must be converted into machine language. The process, of converting them is known as compilation., The first widely used high-level languages, FORTRAN (FORmula TRANslation)was created by John, Backus and an IBM team in 1957;it is still widely used today in scientific and engineering applications., After FORTRAN was COBOL(Common Business-Oriented Language). Admiral Hopper was played a, key role in the development of the COBOL Business language., C is a high-level language used for system software and new application code., , CREATING AND RUNNING PROGRAMS:, Computer hardware understands a program only if it is coded in its machine language. It is the, job of the programmer to write and test the program .There are four steps in this process:1.Writing and, Editing the program2.Compiliing the program 3.Linking the program with the required library modules, 4.Executing the program., , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 5
Page 6 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Writing And Editing Programs, The software used to write programs is known as a text editor. A text editor helps us enter,, change, and store character data. Depending on the editor on our system, we could use it to write letters,, create reports, or write programs. The main difference between text processing and program writing is, that programs are written using lines of code, while most text processing is done with character and, lines., Text editor is a generalized word processor, but it is more often a special editor included with the, compiler. Some of the features of the editor are search commands to locate and replace statements, copy, and paste commands to copy or move statements from one part of a program to another, and formatting, commands that allow us to set tabs to align statements., After completing a program, we save our file to disk. This file will be input to the compiler; it is known, as a source file., , Compiling programs:, The code in a source file stored on the disk must be translated into machine language ,This is the, job of the compiler. The c compiler is two separate programs. the preprocessor and the translator., The preprocessor reads the source code and prepares it for the translator. While preparing the, code ,it scans for special instructions known as preprocessor commands. These commands tell the, preprocessor to look for special code libraries, make substitutions in the code ,and in other ways prepare, the code for translation into machine language. The result of preprocessing is called the translation unit., After the preprocessor has prepared the code for compilation, the translator does the actual work, of converting the program into machine language. The translator reads the translation unit and writes the, resulting object module to a file that can then be combined with other precompiled units to form the, final program. An object module is the code in machine language. The output of the compiler is machine, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 6
Page 7 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , language code, but it is not ready to run; that is ,it is not executable because it does not have the required, C and other functions included., , Linking Programs:, A C program is made up of many functions. We write some of these functions, and they are a, part of our source program. There are other functions, such as input/output processes and, mathematical, library functions that exist elsewhere and must be attached to our program. The linker assembles all of, these functions, ours and systems into our final executable program., , Executing Programs:, Once program has been linked, it is ready for execution. To execute a program we use an, operating system command, such as run, to load the program into primary memory and execute it., Getting the program into memory is the function of an operating system program known as the loader. It, locates the executable program and reads it into memory. When everything is loaded, the program takes, control and it begins execution., In a typical program execution, the reads data for processing ,either from the user or from a file. After, the program processes the data, it prepares the output. at output can be to the user’s monitor or to a file., When the program has finished its job, it tells the operating system ,which then removes the program, from memory., , ALGORITHM /PSEUDOCODE:, ALGORITHM:, Algorithms was developed by an Arab mathematician. It is chalked out step-by-step approach to, solve a given problem. It is represented in an English like language and has some mathematical symbols, like ->, >, <, = etc. To solve a given problem or to write a program you approach towards solution of the, problem in a systematic, disciplined, non-adhoc, step-by-step way is called Algorithmic approach., Algorithm is a penned strategy(to write) to find a solution., PSEUDOCODE:, Pseudocode is an informal way of programming description that does not require any strict, programming language syntax or underlying technology considerations. It is used for creating an outline, or a rough draft of a program. Pseudo code summarizes a program’s flow, but excludes underlying, details. System designers write pseudo code to ensure that programmers understand a software project's, requirements and align code accordingly., , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 7
Page 8 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Example1: Algorithm/pseudo code to add two numbers, Step 1: Start, Step 2: Read the two numbers in to a,b, Step 3: c=a+b, Step 4: write/print c, Step 5: Stop., Example2: Algorithm to find discount (simple if), 1. Start, 2. disc = 0, 3. Read amt, 4. if (amt >=5000) goto step5 else step6, 5. disc = amt*5/100, 6. t = amt - disc, 7. Write t,disc, 8. Stop, FLOW CHART :, A Flow chart is a Graphical representation of an Algorithm or a portion of an Algorithm. Flow, charts are drawn using certain special purpose symbols such as Rectangles, Diamonds, Ovals and small, circles. These symbols are connected by arrows called flow lines., (or), The diagrammatic representation of way to solve the given problem is called flow chart., The following are the most common symbols used in Drawing flowcharts:, , Oval, , Terminal, , start/stop/begin/end., , Parallelogram, , Input/output, , Making data available, For processing(input) or recording of, the process information(output)., , Document, , Print O ut, , show data output in, the form of document., , Rectangle, , Process, , Any processing to be, Done .A process changes or moves, data.An assignment operation., , Diamond, , Decision, (if,while & do while), , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Decision or switching, type of operations., , Page 8
Page 9 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Circle, , Connector, , Used to connect, Different parts of flowchart., , Arrow, , Flow, , Joins two symbols, and also represents, execution., , flow, , of, , PROGRAM DEVELOPMENT STEPS, Program Development is a multistep process that requires that we understand the problem, develop a, solution, write the program, and then test it., Program development steps are, , i. Understand the Problem, ii. Develop the solution, , iii. Test the Program, iv. Write the program, When we are given the assignment to develop a program, we will be given a program requirements, statement and the design of any program interfaces. We should also receive an overview of the complete, project so that we will take the inputs we are given and convert them to the outputs that have been specified., This is known as program design., Understand the Problem, The first step in solving any problem is to understand it. By reading the requirements statements, carefully, we fully understand it, we review our understanding with the user and the systems analyst to know, the exact purpose., , Develop the solution, Once we fully understand the problem we need to develop our solution. Three tools will help in this, task. 1. Structure chart, 2.Psuedocode &3.Flowcharts. Generally we will use structure chart and either, flowchart or Pseudo code, The structure chart is used to design the whole program .Pseudo code and flowcharts are used to design the, individual parts of the program., Structure chart: A structure chart, also known as hierarchy chart, shows the functional flow through our, program. The structure chart shows how we are going to break our program into logical steps each step will, be a separate module. The structure chart shows the interaction between all the parts (modules) of our, program., , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 9
Page 10 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , The structure chart to find the total flooring cost of a house, , We can use flowchart or pseudo code to complete the design of your program will depend on experience, and difficulty of the program your designing., Write the program, When we write a program, we start with the top box on the structure chart and work our way to the, bottom. This is known as top-down implementation. We will write the programs by using structure chart, and flowchart or pseudo code., , Test the Program, Program testing can be a very tedious and time- consuming part of program development. As the, programmer we are responsible for completely testing our program. In large-development projects test, engineers are responsible for testing to make sure all the programs work together., There are 2 types of testing., 1. Black box testing: This is done by the system test engineer and the user. Black box testing is the, programs are tested without knowing what is inside it, with out knowing how it works. Black box test, plans are developed by looking only the requirements statement. The test engineer uses these, requirements to develop test plans., 2. White box testing: This is the responsibility of the programmer. White box testing assumes that the, tester knows everything about the program., Except for the simplest program, one set of test data will not completely validate a program., , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 10
Page 11 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , INTRODUCTION TO C PROGRAMMING LANGUAGE, Syllabus: variables (with data types and space requirements), Syntax and Logical Errors in compilation,, object and executable code , Operators, expressions and precedence, Expression evaluation, Storage classes, (auto, extern, static and register), type conversion, The main method and command line arguments Bitwise, operations: Bitwise AND, OR, XOR and NOT operators Conditional Branching and Loops: Writing and, evaluation of conditionals and consequent branching with if, if-else, switch-case, ternary operator, goto,, Iteration with for, while, do-while loops I/O: Simple input and output with scanf and printf, formatted I/O,, Introduction to stdin, stdout and stderr. Command line arguments, , HISTORY OF C, , C is a programming language developed at AT&T’s Bell Laboratories of USA in 1972. It was, designed and developed by Dennis Ritchie., By 1960, computer languages had come into existence, almost each for specific purpose., Example, COBOL used for Commercial Applications, FORTRAN for Engineering and Scientific, Applications and so on. At this stage, people started thinking why not single language which a program, all possible applications. Therefore, a committee formed and came up with language called ALGOL 60., It is too abstract, too general. So, it was not popular. A new language called Combined Programming, Language (CPL) was developed at Cambridge University. CPL turned out to be so big, having so many, features, that it was hard to learn and difficult to implement., Basic Combined Programming Language (BCPL) aimed to solve this problem brings CPL down, to its basic good features. But unfortunately it turned out to be too less powerful and too specific., Around the same time a language called B was written by Ken Thompson at AT&T’s Bell Labs. Dennis, Ritchie inherited the features of B and BCPL; added features and developed C., C was designed as a language in which to write the UNIX operating system, it was originally, used primarily for the purpose of systems programming. Over the years, however the power and, flexibility of C have made it a popular language in industry for a wide variety of application., , Applications of C, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 11
Page 12 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , C is perfectly suited for both systems programming suited for both systems programming and, application programming. It is exclusively used for developing, General Applications, Database Systems, Spread Sheets, Graphic Packages, CAD/CAM applications, Word Processors, Scientific/Engineering applications, , Starting of C, Instead of straight-away learning how to write programs, we must first know what alphabets,, numbers and special symbols are used in C, then how using these constants, variables and keywords are, constructed and finally how are these combined to form an instruction A group of instruction would be, combined later on to form a program. This is illustrated as follows, Alphabets, Keywords, Digits, , Identifiers, , Instructions, Program, Special Symbols, Variables, Constants, Note : Keywords, Identifiers, Variables, constants can also be termed as C Tokens., , C Character Set, A character denotes any alphabet, digit or special symbol used to represent information., Following table shows the valid Alphabets, numbers and special symbols allowed in C, Alphabets, Digits, Special symbols, , A,B,…Z , a,b,…z, 0,1,2,3,4,5,6,7,8,9, ~!@#%^&*( )_ -+=| \{ } [ ] : ; “ ” ‘ ’ < > . , ? /, , C-TOKENS :, Tokens are individual words and punctuations marks in English language sentence. The smallest, individual units are known as C tokens., KEY WORDS, , IDENTIFIERS, C, TOKENS, , E.g. int, float etc, E.g. rate, no_of_hours, , CONSTANTS, , E.g. -15.4,’a’,200, , SPECIAL SYMBOLS, , E.g. [ ], { }, , OPERATORS, , E.g. +,-,*./,%, , a) Keywords, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 12
Page 13 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Keywords are the words whose meaning has already been explained to the compiler. The, keywords are reserved words. The keywords cannot be used as variable names. There are 32 keywords, available in C., auto, , break, , case, , char, , const, , continue, , default, , do, , double, , else, , enum, , extern, , float, , for, , goto, , if, , int, , long, , register, , return, , short, , signed, , sizeof, , static, , struct, , switch, , typedef, , union, , unsigned, , void, , volatile, , while, , b) Identifiers, Identifiers allow us to name data and other objects in the program. Each identified object in the, computer is stored at a unique address. Without identifiers, we would have to know and use objects, addresses., Identifiers are names given to, i) Variables, ii) Arrays, iii) Functions, iv) Structures and unions, Different programming languages use different syntactical rules. Good identifier names are, descriptive but short. C allows names to be up to 63 characters long. If the names are longer than 63, characters, then only the first 63 are used., Few rules of identifiers in C are as follows, First character must be alphabetic character or underscore., Must contain only of alphabetic characters, digits or underscores., First 63 characters of an identifier are significant., Cannot duplicate a keyword., C is case sensitive language. This means that even though two identifiers are spelled the same, if the, case of each corresponding letter doesn’t match, C thinks of them as different names. Under this rule, num, Num, NUM are three different identifiers., , Valid Names, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Invalid Names, Page 13
Page 14 :
PROGRAMMING FOR PROBLEM SOLVING, , a, student _name, _aSystemName, _Bool, INT_MIN, , //Valid but poor style, , //Boolean System Id, //System Defined Value, , UNIT -I, , $sum, 2names, Sum-salary, stdt Nmber, int, , //$ is illegal, // First char is digit, // contains hyphen, // Contains spaces, // keyword, , c) Constants, Constants are data values that cannot be changed during the execution of program., Constants, NonNumeric, , Numeric, Integer, , Real, , Character, , String, , Integer Constants, , , , , , , An integer constant must have at least one digit, It must not have a decimal point, It could be either positive or negative., If no sign precedes an integer constant it is assumed to be positive., No commas or blanks are allowed within an integer constant., Ex: 426, -7605, +782, Integer constants are 3 types, i., Decimal constants, ii., Octal constants, iii., Hexadecimal constants, , By default compiler considers integers in decimal notation.(base = 10), Decimal constants has digits from 0 to 9 (Ex: 456, 9856 etc), Octal representation of integers is done by prefixing ‘0’ before the integer.(base = 8), Octal constants have digits from 0 to 7., Ex: 045, 076, Hexa Decimal representation of integers is done by prefixing ‘0x’ or ‘0X’ before the, integer.(Base = 16), Hexa Decimal constants has digits from 0 to 9 and A to F, A = 10, B = 11 ,…F= 15, Ex: 0xAC, 0XA4, 0x34, 0X45, Real Constants, Real constants often called as Floating Point constants. The real constants can be written in two, forms, Fractional form and Exponential form., VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 14
Page 15 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Rules for decimal form:, A real constant must have at least one digit., It must have a decimal point., It could be positive or negative. Default sign is positive., No commas or blanks are allowed with in real constant., Ex: 426.0, -32.76, +67.98, The exponential form of representation consists of two parts. The part appearing before ‘e’ is, called mantissa, where as the part following ‘e’ is called exponent., Rules for exponential form:, , , , , , The mantissa part and the exponential part should be separated by letter ‘e’., The mantissa part may be positive or negative. Default sign in positive., Decimal point is allowed in the mantissa part., The exponent part must have at least one digit which may be positive or negative. Default sign in, positive., The decimal point is not allowed in the exponent part., Mantissa must have only one digit., Range of real constants expressed in exponential form is -3.4e38 to 3.4e38, Ex: +3.2e5, 3.2e-5, -4e7, -5e-6, 98.45 is represented in exponential form as 9.845e+01, Character Constants, A Character constant is either a single alphabet, a single digit or a single special symbol enclosed, within single inverted commas., Maximum length of a character constant can be 1 character. Ex. ‘A’, ‘5’, ‘=’, In addition to the character, we can also use a backslash(\) before the character., The backslash is known as the escape character., The escape character says that what follows is not the normal character but something else., \n, New Line, \b, Back Line, \‘, Single Quote, \”, Double Quotes, \\, Backslash, \0, Null, \?, Question Mark, \t, horizontal tab, String Constants, String constants are sequence of characters enclosed within a double quote marks., The string may be combination of all kinds of symbols., Ex. “Hell0”, “12345”, “a”, “a#5”, , Coding Constants, We code constants in three ways in our programs. They are as follows:, (i) Literal Constants., VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 15
Page 16 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , (ii) Defined Constants, (iii) Memory Constants, Literal Constants, A literal is an unnamed constant used to specify data., If we know that the data cannot be changed, then we can simply code the data value itself in a, statement., Literals are coded as a part of statement., Ex : 3x + y = 20 , here 3, 20 are called literal constants., Defined Constants, A constant can be designated by using preprocessor command define., The define command are placed at the beginning of the program, although they are legal, anywhere., Ex: #define MAX 50, Considering above example, while the preprocessing is being performed, each defined name MAX in, the program is replaced by value 50., Memory Constants, Memory constants use a C type qualifier const to indicate that the data cannot be changed., The format is, const data_type identifier = value;, Ex : const int a = 10;, , Variables, Variables are names given to locations in the memory of computer where different constants are, stored. These locations can contain integer, real, character or string constants. The variable value keeps, on changing during the execution of program., Rules:, A variable length varies from compiler to compiler. Generally most of compilers support up to 8, characters., The first character in variable name must be an alphabet., The variable should not be a keyword., Variable name must be without spaces and no other special character except underscore ( _ ) is, permitted., Variable names may be combination of upper and lower characters. Ex. ‘suM’ is not same as, ‘sum’., Ex: sum, total_sum, avg_2009 etc, , DATA TYPES, All C compilers support a variety of data types. This enables the programmer to select the, appropriate data type as per the need of the application, For eg:- 658 (Integer data type), D (Character data type), VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 16
Page 17 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Data types can be classified as given below:, a., b., c., d., , Primary data type (Fundamental datatype)(integer,float,character), User defined data type(typedef,enum), Derived data type(arrays,functions,structures,unions,pointers), Empty data type(void), , a. Primary (or) Fundamental data type:There are three types of fundamental data types, they arei., Integer data type, ii., Floating point data type, iii., Character data type, , i). Integer data type:They are used to represent whole numbers which are having sequence of digits. Integer data type, can be classified as signed and unsigned integers., Signed datatypes, signed Integer:- This data type is used to represent both positive and negative integer numbers., Keyword : signed int (or) int., Size : signed integer occupies 16 bits of memory., Size, : 16 bits (or) 2 bytes., Range, : -32768 to +32767, Format specifier(control string) : %d, signed short int:- This data type is used to represent the values which are less than signed integer., Keyword :, signed short int., Size :, 8 (or) 16 bits depending on compiler., Range :, If 8 bits -128 to +127, If 16 bits -32768 to +32767, Format specifier:, %d, Signed long integer:- This data type is used to represent longer values than int., VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 17
Page 18 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Keyword – Signed long int (or) long int (or) long., Size :, 32 bits (or) 4 bytes., Range :, -2, 147, 483, 648 to 2, 147, 483, 647, Format specifier:, %ld, UnSigned datatypes, Unsigned data type:- This data type is used to represent unsigned integer values., Eg- Height, Weight, Volume, Age, Unsigned integer, Keyword :, Size :, Range :, Format specifier:, , unsigned int, 16 bits (or) 2 bytes, 0 to 65535, %u, , Unsigned short integer:- This data type is used for the values of small range without sign., Keyword :, Unsigned short int, Size :, 8 (or) 16 bits depending on the computer., Range :, 0 to 255 (or) to 65535, Format specified :, %u, Unsigned long integer:- It is used to represent longer values which are not having any sign., Keyword :, unsigned long int (or) Unsigned long, Size :, 32 bits or 4 bytes, Range :, 0 to 4294967295, Format specifier: %lu, ii) Floating point data type, These data types are used to represent floating point values or real numbers., There are 3 types:, float : This is used to represent floating point values., Keyboard :, float, Size :, This data type occupies 32 bits of memory or 4 bytes, Range :, 3.4E38to 3.4 + 38 (3.4*10-38 to 3.4 * 10Format Speciifer:, %f, double:- This is used to represent floating point values of more range than float data type., Keyword :, double, Size :, 64 bits or 8 bytes, Range:, 1.7E-308 to 1.7E+308 (1.7*10308 to 1.7*10308), Format specifier:, %lf, long double:- The range of long double is more than that the double., Keyword :, long double, Size :, 80 bits (or) 10 bytes, Range –:, 3.4E -4932 to 3.4E +4932, Format specifier – : %Lf, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 18
Page 19 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , iii) Character data type, This data type used to represent single character., . Signed Character:- It is used to represent characters of both, Keyword – :, Signed char (or) char, Size – :, 8 bits (or) 1 byte, Range – :, -128 to +127, Format Specifier –: %c, Unsigned character:- This is used to represent characters with unsigned numbers., Keyword –:, Unsigned char, Size – :, 8 bits (or) 1 byte, Range – :, 0 to 255, Format Specifier –: %c, Quick Reference of Data Types, Data Type, Size (in Bytes), Char, 1, Unsigned char, 1, Int, 2, Unsinged int, 2, Long, 4, Unsigned long, 4, Float, 4, Double, 8, , Range, -128 to 127, 0 to 255, -32,768 to 32767, 0 to 655655, -2147483648 to 2147483647, 0 to 4294967295, 3.4e-38 to 3.4e3.08, 1.7e-308 to 1.7e+308, , Control String, %c, %c, %d or %i, %u, %ld, %lu, %f or %g, %lf, , Basic C Instructions, There are many instruction types. Basic two types of instructions in C:, 1. Type Declaration Instruction – to declare the type of variables used in C program., 2. Input/ Output Instruction – to perform the function of supplying input data to a program and obtaining, the output results from it., Variable Declaration Instruction, The variables must be declared before they are used in the program. Declaration provides two, things., i) Compiler obtains variable name., ii) It tells to the compiler data type of variable being declared and helps in allocating memory, Syntax:, data_type variable_name;, Example, char ch;, // Variable named ‘ch’ of character data type is declared, int age;, // variable named ‘age’ of integer data type is declared, float salary;, // variable named ‘salary’ of float data type is declared, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 19
Page 20 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , The variables can be assigned or initialized using an operation ‘=’. The declaration and, initialization can also be done in same line., Example: 1) int a;, declaration of variable ‘a’ of integer data type, a = 10; Initialization of variable ‘a’, 2), int a=10; declaration and initialization of variable ‘a’, Note : Variables are not initialized automatically. When variables are defined, they usually contain, garbage values., , Simple Input / Output Instructions(Formatted Input/Output), Mostly used output statement is printf() and mostly used input statement is scanf(). Both printf(), and scanf() are functions, which are used to write and read all types of data values respectively., a) printf() statement, The output formatting function is printf().The printf() function prints all types of data values to, the console. It can be written in two forms, i) printf(format string);, The string written in the function will be outputted on the console., Ex.: printf(“ Hai”);, ii) printf(format string, arguments);, The printf() function takes set of data values, converts them to a text stream sing, formatting instructions contained in a format control string. The format control string indicates, the data types i.e. %c for character, %d for integer, %f for float etc. The arguments represent the, variable names., Ex: printf(“%c%d%f”,ch,sum,avg);, Output Formatting Styles using printf(), A width modifier may be used to specify the minimum number of positions in the output. It is, very useful to align output in columns., Ex : %3d means 3 print positions for integer, If floating point numbers is being printed, then we may specify the number of decimal places to, be printed with the precision modifier. The precision modifier has the format .m where m is the, number of decimal digits., Ex : %8.3f means 7 print positions for float in which there are 3 digits after point i.e., nnnn.ddd, Note : If no precision is specified, printf() prints six decimal positions., b) scanf() statement, The scanf() functions reads all the data type values. It is used for runtime assignment of, variables. The syntax is as follows, scanf(format string, address of arguments);, Control string indicates the data types and the arguments represent the variable name. ‘&’ is, called address operator. ‘&arg0’ indicates the address of the variable., Ex : scanf(‘%c%d%f”,&ch,&sum, &avg);, , The Structure of C Program, Program is the collection of instructions in a particular format. Each C program contains a, number of building blocks. The structure of C program is as follows, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 20
Page 21 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Documentation, Link section, Definition section, Global Declaration Section, // Comments, main() section, {, //Comments, Declaration Part, Executable Part, -------}, User Defined Functions, a) Documentation section or Comment section: Documentation section is used to represent aim of the, program, name of the author, date of program etc. Comments are not necessary in the program., However, to understand the flow of program, programmer can include comments in the program. These, are useful for documentation. The comments can be single line or multiple lines. These comments are, not executed. Single line comments can be written by using two slashes (//) Ex : //This is a single line, comment, Multiple line comments can be written by enclosing them between /* and */ symbols., Ex : /* It is a very common type of commenting, Multiple lines of documentation*/, b) Link section: Link section is used to link our program with the library., c) Definition section: Definition section is used to define symbolic constants., d) Global declaration section: This section declares some variables that are used in more than one, function. These variables are known as global variables, e) main () section : Every C program must contain main() function. Empty parentheses after main are, necessary. The function main() is the starting point of every C Program. The execution always begin, with the function main(). The program execution starts from starting brace ‘{‘ and ends with ending, brace ‘}’. Between two braces the programmer should write the executable code., i. Declaration part: The declaration part declares all variables that are used in the executable part., Initialization can also be done in this section., ii. Executable part: This part contains single statement or set of statements for execution. All the, statements must be enclosed between braces., f) User-defined functions: The functions defined by the user are called user-defined functions. This, portion is defined after main() function. This portion is not compulsory., Programming Rules, , , , , , , All statements should be written in lowercase letters., Uppercase letters are only used for symbolic constants., Blank spaces may me inserted between the words., Every statement must end with a semi-colon (;), The opening and closing braces should be balanced., , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 21
Page 22 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Sample C Programs, 1. /*Program to print Welcome on the screen */, #include<stdio.h>, int main(), {, printf(“Welcome to C Programming”);, return 0;, }, Output : Welcome to C Programming, 2./* Program to print the values stored after initialization */, #include<stdio.h>, int main(), {, char grade= ‘A’;, int sum = 533;, float avg = 88.3;, printf(“Sum = %d, Average = %f, Grade = %c”,sum, avg, grade);, return 0;, }, Output : Sum = 533, Average = 88.3, Grade = A, 3./*Program to read the values during execution and print them */, #include<stdio.h>, int main(), {, char grade;, int sum;, float avg;, printf(“Enter the sum, avg, grade values”);, scanf(“%d%f%c”,&sum,&avg,&grade);, printf(“Sum = %d, Average = %f, Grade = %c”,sum, avg, grade);, return 0;, }, Output: Enter the sum, avg, grade values 533 88.3 A, Sum = 533, Average = 88.3, Grade = A, , Operators, To perform different kinds of operations, C uses different of operators. An operator indicates an, operation to be performed on data that yields a values., C provides different types of operators, 1) Arithmetic Operators, 2) Relational Operators, 3) Logical Operators, 4) Assignment Operators, 5) Conditional Operators, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 22
Page 23 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , 6) Bitwise Operators, 7) Increment and decrement operator, 8) Others Operators, 1) Arithmetic Operators, C provides five arithmetic operators, they are, Operator, Meaning, +, Addition, Subtraction, *, Multiplication, /, Division, %, Modulus, Example: Suppose m and n are integer variables whose values are 11 and 4 respectively, Expression, Value, m+n, 15 (11+4), m–n, 7 (11- 4), m*n, 44 (11 * 4), m/n, 2 (11/4), m%n, 3 (11%4), If both operands represent integer quantities, the result of integer division is always integer, that is the, decimal part of the result is always truncated., Example: Suppose a and b are floating variables whose values are 12.5 and 10.0 respectively, Expression, Value, a +b, 22.5 (12.5 + 10.0), a -b, 2.5, (12.5 – 10.0), a * b, 125.00 (12.5 * 10.0), a /b, 1.25 (12.5 / 10.0), If both operands represent float quantities, the result of float division is always float. The modulus, operator cannot be used with float quantities., Example: Suppose a and b are floating and integer variables respectively whose values are 14.5 and 10, respectively, Expression, Value, a +b, 24.5 (14.5 + 10), a - b, 4.5, (14.5 – 10), a*b, 145.0 (14.5 * 10), a/b, 1.45 (14.5 / 10), If one operand represent integer quantity and other represent float quantity, the result is always float., The modulus operand cannot be used with integer and float combination., Precedence( Priority of operators), * / %, Higher Precedence, + Lower Precedence, , --- They are applied from Left to Right, --- They are applied from Left to Right, , Example : If a=10, b = 16 and c=5 then find the value of n if, n= a – b / 4 + c * 2 – 3 ., VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 23
Page 24 :
PROGRAMMING FOR PROBLEM SOLVING, , Solution :, Step1, Step 2, Step 3, Step 4, Step 5, , UNIT -I, , n = 10 – 16 / 4 + 5 * 2 – 3, n = 10 – 4 + 5 * 2 – 3, n = 10 – 4 + 10 – 3, n = 6 + 10 – 3, n = 16 – 3, n = 13, , /*Program to demonstrate arithmetic operators */, #include <stdio.h>, int main(), {, int a , b;, printf("Enter two numbers :");, scanf("%d%d", &a, &b);, printf(" Sum = %d", (a+b));, printf(" Difference = %d", (a - b));, printf(" Product = %d", (a*b));, printf(" Division = %d", (a/b));, printf(" Modulus = %d",(a%b));, return 0;, }, Output:, Enter two numbers : 25 10, Sum = 35 Difference = 15 Product = 250 Division= 2 Modulus = 5, 2) Relational Operators, C supports following 6 relational operators, Operator, Meaning, >, Greater than, >=, Greater than or equal, <, Lesser than, < =, Lesser than or equal, ==, Equal, !=, Not Equal, Each of these relational operators require two operands and can be combined together to form relational, expressions, which represent conditions that are either true or false. The resulting expressions are of type, integer, since in C true is represented by integer value 1 and false is represented by integer value 0., Precedence of Operators, > >= < <=, == !=, , High Priority ---- The operator will be evaluated from Left to Right, Low Priority ---- The operator will be evaluated from Left to Right, , Examples: Suppose a is an integer whose value is 10. b is floating variable whose value is 2.5 i.e. a=, 10, b=2.5, Expression, Value, Explanation, a>5, 1, 10>5 is true, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 24
Page 25 :
PROGRAMMING FOR PROBLEM SOLVING, , (a + b) < 12, b * 6 >= a + b, a / 5 <= b – a, a * a == 10, b + a != 5, , 0, 1, 0, 0, 1, , UNIT -I, , (10+2.5)<12 i.e. 12.5<12 is false, 2.5 * 6 >= 10+2.5 i.e. 15.0 >=12.5 is true, 10 / 5 <= 2.5 – 10.0 i.e. 2 <= -7.5 is false, 10 * 10 = =10 i.e. 100 == 10 is false, 2.5 + 10.0 != 5 i.e. 12.5 != 5 is true, , /*Program to demonstrate relational operators*/, #include<stdio.h>, int main(), {, printf(“ 5>2 is %d”,5>2);, printf(“\n 5>=2 is %d”,5>=2);, printf(“\n 5<2 is %d”,5<2);, printf(“\n 5<=2 is %d”,5<=2);, printf(“\n 5==2 is %d”,5==2);, printf(“\n 5!=2 is %d”,5!=2);, }, Output, 5>2 is 1, 5>=2 is 1, 5<2 is 0, 5<=2 is 0, 5 == 2 is 0, 5 != 2 is 1, 3) Logical Operators, In addition to the relational operators discussed, C supports three logical operators that act upon, logical expressions. These are, Operator, Meaning, &&, Logical AND, ||, Logical OR, !, Logical NOT, Thus logical operators can be used to form more complex conditions that are either true or false., &&(AND) Operator, 1. Evaluates true when both the relational expression are true., 2. Evaluates false when any one of the relational expression is false., The following is truth table for AND operator, Condition1, Condition2, Output, False (0), && False (0), =, False (0), False (0), && True (1), =, False (0), True (1), && False (0), =, False (0), True (1), && True (1), =, True (1), ||(OR) Operator, 1. Evaluates false when both the relational expression are false., 2. Evaluates true when any one of the relational expression is true., VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 25
Page 26 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , The following is truth table for OR operator, Condition1, Condition2, Output, False (0), ||, False (0), =, False (0), False (0), ||, True (1), =, True (1), True (1), ||, False (0), =, True (1), True (1), ||, True (1), =, True (1), !(NOT) Operator, This is a unary operator that negates the value of a relational or logical expression., 1. Evaluates true when the relational expression is false., 2. Evaluates false when the relational expression is true., Condition, Output, !, False (0), =, True (1), !, True (1), =, False (0), Precedence of Operators, !, High Priority ---This operator evaluates from right to left, &&, Medium Priority--- These operators evaluates from left to right, ||, Low Priority ---This operator evaluates from left to right., Example : Suppose a is an integer variable whose value is 10, is a floating-point variable whose value, is 2.5 then, Expression, Value, Explanation, (a>b) &&(b>5), 0, (10>2.5) && (2.5>5) i.e. true && false = false, (a>b) || (b>5), 1, (10>2.5)|| (2.5>5) i.e. true || false = true, ! (a>b), 0, (10>2.5) is true. i.e NOT true = false, , 4) Assignment Operator ans short hand operation, Operator, Meaning, =, assign, +=, add and assign, -=, subtract and assign, *=, multiply and assign, /=, divide and assign, These operators execute from right to left. The right side expression is evaluated and assigned to left, variable., Example: Let a, b, c, d are integer variables whose values are 10, 12, 14, 16 respectively, Expression, Output, Explanation, x=10;, --Value ‘10’ is assigned to variable ‘x’, a+=10, 20, a = a+ 10 i.e. 10+10 = 20, b-=5, 7, b = b – 5 i.e 12 – 5 = 7, c*=b, 70, c = c * b i.e. 14 * 5 = 70, d/=4, 4, d = d / 4 i.e 16 / 4 = 4, /*Program to demonstrate usage of assignment operators*/, #include<stdio.h>, int main(), {, int a=7,b=5,c=2,d=3;, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 26
Page 27 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , printf(“Before operation a=%d, b=%d, c=%d, d=%d”,a,b,c,d);, a=10;, b+=a;, c-=a;, d*=b;, prinf(“\nAfter operation a=%d, b=%d, c=%d, d=%d”,a,b,c,d);, return 0;, }, Output, Before operation a=7, b=5, c=2, d=3, After operation a=10, b=15, c=-8 ,d=45, /*Program to swap two numbers without using temporary variable*/, #include<stdio.h>, int main(), {, int a,b,t;, printf(“Enter two numbers :”);, scanf(“%d%d”,&a,&b);, printf(“Before swapping a=%d, b=%d”,a,b);, a=a+b;, b=a-b;, a=a-b;, prinf(“\nAfter swapping a=%d, b=%d”,a,b);, return 0;, }, Output, Enter two numbers : 15 89, Before swapping a=15, b=89, After swapping a=89, b=15, 5) Conditional Operator, C offers a ternary operator pair ‘ ? : ’ that can be used to carry out simple conditional operations., The syntax is as follows, expression 1 ? expression 2 : expression 3, where expression 1 is logical expression, while expression 2 and expression 3 can be constants,, identifiers or other complex expressions., When a conditional operator is used, expression 1 is first evaluated. If expression 1 is true then, expression 2 is evaluated. If expression 1 is false then expression 3 is evaluated., Example : (a> b) ? 5 : 10 If the expression a>b is true then output is 5 else output is 10, /* Program to find the minimum of two numbers using conditional operator*/, #include<stdio.h>, int main(), {, int num1, num2,min;, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 27
Page 28 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , printf(“Enter two numbers :”);, scanf(“%d%d”,&num1, &num2);, min = (num1 < num2) ? num1 : num2;, printf(“\nSmallest Number = %d”,min);, return 0;, }, Output, Enter two numbers : 6 7, Smallest Number = 6, /* Program to check whether the given number is even or odd using conditional operator*/, #include<stdio.h>, int main(), {, int n;, printf(“Enter a number :”);, scanf(“%d”,&n);, (n%2 = = 0) ? printf(“Even”):printf(“Odd”);, return 0;, }, Output, Enter a number : 5, Odd, /* Program to find largest of three numbers conditional operator*/, #include<stdio.h>, int main(), {, int a,b,c;, printf(“Enter three numbers :”);, scanf(“%d%d%d”,&a,&b,&c);, (a>b && a>c)? printf(“Lagest num = %d”,a): (b>c) ? printf(“Largest numr = %d”,b) :, printf(“Largest num = %d”,c);, return 0;, }, Output, Enter three numbers : 5 6 9, Largest number = 9, 6) Bit wise Operator, C supports six bit wise operators. These operators can operate only on an integer operands such, as int, char, short, long int etc. These do not work with float operands like float, double ., Operator, Meaning, >>, Right Shift, <<, Left Shift, &, Bitwise AND, |, Bitwise OR, ~, Ones Complement (Bitwise NOT), VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 28
Page 29 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , ^, Exclusive OR, Example: Let a, b are integer variables whose values are 8,3 respectively. Then, Representation of 8 is 0000 0000 0000 1000, Representation of 3 is 0000 0000 0000 0011, 1) a >> b i.e. 8 >> 3 means right shift three bits in representation of 8, 0000 0000 0000 0001, Therefore 8 >>3 = 1, 2) a << b i.e. 8 << 3 means left shift three bits in representation of 8, 0000 0000 0100 0000, Therefore 8 << 3 = 64, 3) a & b i.e. 8 & 3, 0000 0000 0000 1000, 0000 0000 0000 0011, ------------------------------0000 0000 0000 0000, 4) a | b i.e. 8 | 3, 0000 0000 0000 1000, 0000 0000 0000 0011, --------------------------------0000 0000 0000 1011, 5) a ^ b i.e. 8 ^ 3, 0000 0000 0000 1000, 0000 0000 0000 0011, -------------------------------0000 0000 0000 1011, 6) ~a i.e. ~8, 0000 0000 0000 1000, 1111 1111 1111 0111, , 8, 3, 8&3 = 0, 8, 3, 8 |3 = 11, 8, 3, 8 ^ 3 = 11, 8, ~8, , 7) Increment and Decrement Operator, C includes two useful operators, which are generally not found in other computer languages, developed prior to C., Operator, Meaning, ++, increment by 1, -decrement by 1, To be precise, x = x+1 can be written as x++;, x = x – 1 can be written as x- -;, Example : If a = 5, then a++ =6 i.e. a= a+1 = 5+1, If a = 6, then a - - = 5 i.e. a = a – 1 = 6 – 1, Both the operators may either precede or follow the operand i.e., x = x+1 can be written as x++ or ++x, x = x – 1 can be written as x - - or - - x, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 29
Page 30 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Here, x++ is known as post increment operator, ++x is known as pre increment operator, x - - is known as post decrement operator, - - x is known as pre decrement operator., The difference between pre- and post- fixing the operator is useful when if used in an expression. When, the operator precedes the operand, C performs the increment or decrement before using the value of the, operand., Ex:, If x =5 and y = + + x then y = 6 and x = 6, If x = 8 and y = - - x then y = 7 and x = 7, When the operator follows the operand, the value of operand is used before incrementing or, decrementing the operand value., Ex:, If x =5 and y = x + + then y = 5 and x = 6, If x = 8 and y = x - - then y = 8 and x = 7, 1. /*Program to show the affect of increment operator as suffix */, #include <stdio.h>, int main(), {, int a, z, x = 10, y = 20;, z = x * y ++;, a= x*y;, printf(" z =%d, a = %d", z , a);, return 0;, }, Output, z =200, a= 210, 2. /*Program to show effect of increment operator as a prefix */, #include <stdio.h>, int main(), {, int a, z, x = 10, y = 20;, z = x * ++y ;, a= x * y;, printf(" z =%d, a = %d", z , a);, }, Output, z =210, a= 210, 8) Other Operators, a) Comma Operator (,), The comma operator is used to separate two or more expressions. The comma operator has the, lowest priority among all the operators., Example : k = (a=10, b = 20, c=a+b);, The rightmost expression value (30) is assigned to k, b) sizeof() operator, The sizeof() operator is used to find the size occupied by a particular data type. Sizeof() is a, function which takes a single parameter. It returns an integer value, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 30
Page 31 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Syntax : sizeof(data_type), Ex : sizeof(int) returns 2, /*Program to illustrate usage of sizeof() operator */, #include<stdio.h>, int main(), {, printf(“Integer = %d, Float = %d, Character = %d”,sizeof(int), sizeof(float), sizeof(char));, }, Output, Integer = 2, Float = 4, Character = 1, c) Unary Plus (+) and Unary Minus (-) Operators, ‘+’ and ‘- ’ can also be used with single operand. ‘+’ is used to indicate positive sign. ‘-’ is used, to indicate negative sign., Ex : +7 indicates positive 7, - 7 indicates negative 7, d) Address operator (&), ‘&’ symbol is termed as address operator. It is used in mostly used in scanf() statement. The, address operator is used to get the memory address location of an identifier., Ex. &a indicates address of operator, /*Program to demonstrate usage of address operator*/, #include<stdio.h>, int main(), {, int a;, float b;, printf(“Address of a = %u”,&a);, printf(“Address of b = %u”,&b);, }, Output, Address of a = 65524, Address of b = 65520, , Expressions, An expression is a sequence of operands and operators that reduces to a single value. An, operator is a syntactical token that requires an action to be taken. An operand is an object on which an, operation is performed., Expressions may be complex or simpler. A simpler expression contains only one operator. A, complex expression contains more than one operator., Expressions can be divided into six categories, 1) Primary Expressions, 2) Postfix Expressions, 3) Prefix Expressions, 4) Unary Expressions, 5) Binary Expressions, 6) Ternary Expressions, Primary Expression, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 31
Page 32 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , A primary expression consists of only one operand with no operator. In C, the operand in, primary expression may be a name, a constant or a parenthesized expression. Primary expression is, evaluated first in a complex expression., Name : A name is any identifier for a variable, a function or any other object in language., a s12 price calc INT_MAX, Literal Constants : A constant is a piece of data whose value can’t change during the execution of the, program., 5 123.98 ‘A’ “Hai”, Parenthetical Expressions : Any value enclosed in parentheses must be reducible to a single value and, is therefore a primary expression. This includes any of the complex expressions when they are enclosed, in parentheses., (2 * 3 + 5), (a=10+b), Postfix Expression, The postfix expression consists of one operand followed by one operator., Syntax : operand operator, There are several postfix expressions. Few of them are function call, postfix increment and postfix, decrement., Ex : printf(), a++, a- Function calls are postfix expressions. The function name is the operand and the operator is the, parentheses that follow the name. The parentheses may contain arguments or be empty. When present,, the arguments are part of the operators., Note : ++, - - can be called as postfix operators when used in postfix expression, Prefix Expression, The prefix expression consists of one operator followed by one operand., Syntax : operator operand, Examples for prefix expressions are prefix increment and prefix decrement., Ex : ++a, - - a, Note : ++, - - can be called as prefix operators when used in prefix expression, Unary Expressions, The unary expression, like a prefix expression, consist of one operator and one operand., Although prefix expressions and unary expressions look the same, they belong to different expression, categories because the prefix expression needs a variable as the operand while the unary expression can, have an expression or a variable as the operand., Syntax : operator operand, Example for unary expressions are positive/negative sign, sizeof operator, Logical NOT operator, etc., Ex : +5, -7, sizeof(int), !a, ~10, &c, Note : Unary Plus (+), Unary Minus ( -), Logical NOT (!), ones complement (~), address (&), sizeof(), are called as unary operators., Binary Expressions, Binary expressions are the combinations of two operands and an operator in between them., Syntax : operator operand, operator, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 32
Page 33 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Arithmetic expressions, relational expressions, logical and expression, logical OR expression,, assignment expression etc are examples of binary expressions, Ex. a+b, a – b, a * b, a/ b, a%b, a>b, a<b, a>=b, a<=b, a==b, a!=b, a&&b, a||b, a&b, a|b, a^b, a<<b,, a>>b, a=b, a+=b, a=-b, a*=b, a/=b, a%=b, Note : Addition(+), subtraction (-), multiplication (*), division (/), modulus (%), less than (<), less than, equal to (<=), greater than (>), greater than equal to (>=), equal to (==), not equal to (!=), Bitwise AND, (&), Bitwise OR (|), Bitwise XOR(^), Logical AND(&&), Logical OR(||), assignment (=) are called, binary operators., Ternary Expression, Ternary Expression is an expression which consists of three operands and a pair of operator., Condition expression is an example for ternary expression., Ex: (a>b) ? a: b, Note : Conditional operator(?:) is called ternary operator, Precedence and Associativity, Precedence is used to determine the order in which different operators in a complex expression, are evaluated. Associativity is used to determine the order in which operators with the same precedence, are evaluated in a complex expression. Precedence is applied before associativity to determine the order, in which expressions are evaluated. Associativity is then applied, if necessary. The following table, determines the Precedence and associativity of operators., , Operators, (), [], ->, ., +, ++, -!, _, *, &, *, /, %, +, <<, >>, <, <=, >, >=, , Operation, Function Call, Array expression, Structure Operator, Structure Operator, Unary Plus, Unary Minus, Increment, Decrement, Logical NOT, One’s complement, Pointer Operator, Address Operator, Multiplication, Division, Modular Division, Addition, Subtraction, Left Shift, Right Shift, Less than, Less than or equal, Greater than, Greater than or equal, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Associativity, , Precedence, , Left to Right, , 1, , Right to Left, , 2, , Left to Right, , 3, , Left to Right, , 4, , Left to Right, , 5, , Left to Right, , 6, , Page 33
Page 34 :
PROGRAMMING FOR PROBLEM SOLVING, , ==, !=, &, ^, |, &&, ||, ?:, = += -= *= /= &=, |=, ^= <<= >>=, ,, , UNIT -I, , Equality, Not Equality, Bitwise AND, Bitwise XOR, Bitwise OR, Logical AND, Logical OR, Conditional Operator, Assignment Operator, , Left to Right, , 7, , Left to Right, Left to Right, Left to Right, Left to Right, Left to Right, Right to Left, Right to Left, , 8, 9, 10, 11, 12, 13, 14, , Comma Operator, , Left to Right, , 15, , Side Effect, A side effect is an action that results from the evaluation of an expression. For example, in an, assignment, C first evaluates the expression on the right of the assignment operator and then places the, value in the left variable. Changing the value of the left variable is called side effect., Example expression without side effects, a*4+b/2–c*b, Example expression with side effects, - - a * (3 + b) / 2 – c ++ * b, , Type Conversion, Type conversion is needed when the expression has the operands of different data types., If we write an expression that involves two different data types, to perform these evaluations,, one of the types must be converted into other type., Ex:, , In above program, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 34
Page 35 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , , , , , Variable a is integer it needs 2 bytes of memory., Variable b is float and it needs 4 bytes of memory., Variable b is highest data element between a and b. so Result(a+b)will be in highest type, (float).The result is 67.96., There are two types of type conversions., a) Implicit Type Conversion, b) Explicit Type Conversion, , a) Implicit Type Conversion, When the types of the two operands in a binary expression are different, C automatically, converts one type to another. This is known as implicit type conversion. For implicit type conversion, C, has several complicated rules., In C, we can assign a rank to the integral and floating-point arithmetic types., Example : char (rank 1), int (rank 2), long (rank 3), float (long 4), double (rank 5), Ranks are given based on the size.(Rank 1 means less size), Let us consider a simple assignment involves an assignment operator and two operands., Depending on the difference in the rank, C tries to either promote or demote the right expression to, make it the same rank as the left variable., Promotion occurs if the right expression has lower rank. There is normally no problem with, promotion. Example of promotions, char c= ‘A’;, int i= 124;, double d = 345.236;, i = c; // value of i is 65, d = i; // value of d is 124.0, Demotion occurs if the right expression has higher rank. It may or may not create problems., When an integer or a real is assigned to a variable of type character, the least significant byte of the, number is converted to a character and stored. When a real is stored in an integer, the fraction part is, dropped. However, if the integral part is larger than the maximum value that can be stored, the results, are invalid and unpredictable. Examples of demotions are, char c = ‘A’;, int k = 65;, c=k+1;, //value of c is ‘b’, Explicit Type Conversion(type casting), Rather than let the compiler implicitly convert data, we can convert data from one type to, another yourself using explicit type conversion. Explicit conversion uses the unary cast operator, which, has a precedence of 14. To cast data from one type to another, we specify the new type in parenthesis, before the value., Ex:, (float) a/10, // converting the ‘a’ to float data type, avg = (float) sum/6, // converting the sum value into float, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 35
Page 36 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , CONTROL (STRUCTURES) STATEMENTS, Control statements are used to represent the flow of execution of statements in the program., There are 3 types, , a) Decision making(selection) statements, b) Iterative/repetitive/looping statements, c) Jump statements, a)Decision making (selection) Statements, A program is nothing but the execution of sequence of one or more instructions. In the, monolithic program the sequences of instructions are executed in the same order as they appear in the, program. In practical applications, there are a number of situations where one has to change the order of, the execution of statements based on the conditions. This involves decision making condition to see, whether a particular condition is satisfied or not., The conditions can be placed in the program using decision – making statements. C Language, supports the control statements as listed below, i) If statements, ii) Switch statements, i) If statements, It has 4 forms, I.The simple if Statement, II.The if – else Statement, III.The nested if Statement, IV.The if – else - if Statement(else if ladder), I. Simple if, Simple if has only one option. The set of statements are executed when the logical condition is, true, Otherwise the if statement is skipped., Syntax :, Flow chart, , if(condition), {, Statements;, }, , Example:, 1. /* Program to find discount */, #include<stdio.h>, int main(), {, float p,d = 0,t;, printf("Enter the purchased amount:");, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 36
Page 37 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , scanf("%f",&p);, if(p>=5000), {, d = p*(10.0/100);, }, t = p - d;, printf("Discount = %.2f",d);, printf("\nTotal amount = %.2f",t);, return 0;, }, Output, Enter the purchased amount:6000, Discount = 600.00, Total amount = 5400.00, II. If…. Else Statement, If else is two way decision making statement. It has two options. One choice will be selected out, of two options. It has two blocks. One block is for if and other block is for else. If the condition is true,, the if block statements are executed, and if the condition is false, else block statements are executed., Syntax:, Flow chart, if(condition), {, Statements A;, }, else, {, Statements B;, }, , NOTE: if else is alternative to conditional operator, 1./*Program to verify whether given character is vowel or not*/, #include <stdio.h>, int main(), {, char ch;, printf("Enter an alphabet (a-z):");, scanf("%c",&ch);, if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u'), printf("Vowel");, else, printf("consonats");, }, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 37
Page 38 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Output, Enter an alphabet(a-z) : e, Vowel, 2./* Program to check entered year is a leap year or not */, #include<stdio.h>, int main(), {, int leap;, printf("Enter year :");, scanf("%d", &leap);, if(((y%4==0)&&(y%100!=0))||(y%400==0)), printf("%d is a leap year",leap);, else, printf("%d is not a leap year",leap);, return 0;, }, Output:, Enter year : 2003, 2003 is not a leap year, 3. /* Program to find the roots of a Quadratic Equation ax2+bx+c */, #include<math.h>, #include<stdio.h>, int main(), {, int a,b,c,dis;, float r1,r2;, printf("Enter values of a,b,c :");, scanf("%d%d%d",&a,&b,&c);, dis= b*b - (4*a*c);, if(dis<0), printf("Roots are imaginary");, else, {, r1=(-b+sqrt(dis))/(2*a);, r2=(-b-sqrt(dis))/(2*a);, printf("Root1=%f\n",r1);, printf("Root2=%f",r2);, }, return 0;, }, III. Nested if statement, In this kind of statements number of logical conditions is checked for executing various, statements. if… consists of another if …else. If the condition is true control passes to inner if block, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 38
Page 39 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , where condition again checked . If the inner condition is true the statements in the inner if are executed, otherwise inner else is executed. if the outer condition is false the outer else part is executed., In nested if ,Multiple conditions must be satisfied to execute a statement, Syntax:, Flowchart, if(condition 1), {, if(condition 2), {, statements;, }, else if(condition 3), {, statements;, }, }, else, {, statements;, }, //program to check whether the student is pass or failed, #include<stdio.h>, int main(), {, int x,y,t;, printf("Enter internal marks:");, scanf("%d",&x);, printf("Enter External marks:");, scanf("%d",&y);, t=x+y;, if(t>=40), {, if(y>=26), {, printf("Student is passed");, }, else, {, printf("Student is failed");, }, }, else, {, printf("Student is failed");, }, return 0;, }, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 39
Page 40 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , IV. If.. Else.. If Statement(else if ladder), Else if ladder is multiway decision making statement. It has many options. Only one choice will, be selected among different options., In this kind of statements number of logical conditions is checked for executing various statements., If…else…if can be chained with one another. If the condition is false control passes to else block where, condition again checked with the if statement. This process continues if there is no if statement in the, last else block. If one of the if statement satisfies the condition, other else..if will not be executed., , Syntax:, , flowchart, , if(condition 1), {, statements;, }, else if(condition 2), {, statements;, }, else, {, statements;, }, 1. /* Program to find the largest of three numbers */, #include <stdio.h>, int main(), {, int a,b,c;, printf("Enter three numbers :");, scanf("%d%d%d",&a, &b, &c);, if(a>b && a>c), printf("Largest Number = %d",a);, else if(b>a && b>c), printf("Largest Number = %d",b);, else, printf("Largest Number = %d", c);, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 40
Page 41 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , }, Output, Enter three numbers : 20 24 16, Largest Number = 24, 2. /* Program to find the average of six subjects and display the results as follows, AVERAGE, RESULT, >70, Distinction, >60 and <70, First Division, >50 and <60, Second Division, >40 and <50, Third Division, <40, Fail, */, #include<stdio.h>, int main(), {, int m1,m2,m3,m4,m5,m6, sum = 0;, float avg;, printf("Enter 6 subject marks :");, scanf("%d%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5,&m6);, sum= m1+m2+m3+m4+m5+m6;, avg = sum/6;, printf("Total : %d\n Average : %f",sum,avg);, if(avg>=70), printf(“Distinction”);, else if(avg>=60 && avg<70), printf("\nFirst Division");, else if(avg>=50 && avg<60), printf("\nSecond Division");, else if(avg>=40 && avg<50), printf("\nThird Division");, else, printf("\nFail");, }, Output, Enter 6 subject marks : 40 50 60 70 80 90, Total : 390, Average : 65.000000, First Division, 3./Program to calculate energy bill. Read the starting and ending meter reading. The charges are, as follows :, No. of units consumed, Rate per Unit, <100, 1.50, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 41
Page 42 :
PROGRAMMING FOR PROBLEM SOLVING, , 100 – 200, 200 – 300, > 300, , UNIT -I, , 2.00, 2.50, 3.00 */, , #include<stdio.h>, int main(), {, int initial, final, consumed;, float bill;, printf("Enter Initial & final Readings :");, scanf("%d%d",&initial, &final);, consumed = final - initial;, if(consumed>0 && consumed <=100), bill = consumed * 1.50;, else if(consumed>100 && consumed<=200), bill = consumed * 2.00;, else if(consumed>200 && consumed <=300), bill = consumed * 2.50;, else, bill = consumed * 3.00;, printf("\nBill Amount = %f", bill);, }, Output, Enter Initial & Final Readings : 40 90, Bill Amount = 75.000000, ii) Switch Case, Switch is a multi-way decision-making statement that tests whether an expression matches one, of a number of alternate values and braches accordingly., It has many options. Only one choice will be selected among different options., The switch statement requires only one argument expression which is checked with number of, case options. The data type of the expression must be either int or char. The switch statement evaluates, expression and then looks for its value among the case constants. If the value matches with case, constant, this particular case statement is executed. If not, default is executed., NOTE: Switch is alternative to else if ladder, , , , , , , Points to Remember, switch, case, and default are keywords., Every case statement terminates with ‘:’, No semicolon is used after switch statement., The break statement is used to exit from current case structure., If no break statements are given all the cases following it will be executed, , Syntax :, switch (expression), {, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 42
Page 43 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , case constant_value : statement;, break;, case constant_value : statement;, break;, case constant_value : statement;, break;, default, : statement;, }, , Sailent Features, 1. Each case labeled by integer or character constant., 2. Cases and default may occur in any order., 3. Cases must all be different., 4. After the code for one case is done, execution falls through to the next unless you take explicit, action to escape., , 1. /* Program to check given alphabet is vowel or consonant */, #include<stdio.h>, int main(), {, char ch;, printf("Enter a character (a-z or A-Z) :");, scanf("%c",&ch);, switch(ch), {, case 'a' :, case 'e' :, case 'i' :, case 'o' :, case 'u' :, case 'A' :, case 'E' :, case 'I' :, case 'O' :, case 'U' :, default :, , printf("\nVowel");, break;, printf("\nConsonant");, , }, }, Output :, Enter an character (a-z or A – Z) : Z, Consonant, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 43
Page 44 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , 2./* Program to provide arithmetic functions by using switch */, #include<stdio.h>, int main(), {, int a,b,ch;, printf("\n MENU\n 1. Addition \n 2.Subtraction \n 3.Multiplication\n 4.Division\n 5.Remainder, ");, printf("Enter two numbers :");, scanf("%d%d",&a, &b);, printf("\n Enter your choice :");, scanf("%d",&ch);, switch(ch), {, case 1 :, printf("Addition = %d", (a+b));, break;, case 2 :, printf("Subtraction = %d", (a-b));, break;, case 3 :, printf("Multiplication = %d", (a*b));, break;, case 4 :, printf("division = %d", (a/b));, break;, case 5 :, printf("Remainder = %d", (a%b));, break;, default : printf("Selected Wrong Choice");, }, return 0;, }, Output, Menu, 1.Addition, 2.Subtraction, 3.Multiplication, 4.Division, 5.Remainder, Enter two numbers : 33 10, Enter your choice : 4, Remainder = 3, Nested switch() Case, , , , , , C supports the nested switch() statements., The inner switch() can be a part of an outer switch()., The inner and outer switch() case constants may be same., No conflict arises even if they are same., , b) Iterative statements / Repetitive Statements (Loops), VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 44
Page 45 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Loop is defined as a block of statements which are repeatedly executed for certain number of, times., Steps in Loop, 1) Initialization : It is used to initialize the starting value of loop control variable, 2) Test Condition: Each time the updated value is checked by the condition., 3) Increment/decrement: It is the numerical value added or subtracted to the loop control variable, in each round of the loop., The C language supports three types of loop control statements. They are, a) while, b) do while, c) for, , a. The while Loop, While loop is entry control loop(pre test loop). The test condition is checked at the beginning of, the loop. The test condition may be any expression., The loop statements will be executed till the condition is true i.e. the test condition is evaluated, and if the condition is true, then the body of the loop is executed. When the condition becomes false the, execution will be out of the loop., Syntax, Flow chart, , Initialization;, while(test- condition), {, Statements;, Updation ;, (loop control variable), }, , The loop may contain a single statement or multiple statements. The braces are needed only if, the body of the loop contains more than one statement. However, it is a good practice to use braces even, if the body of the loop contains only one statement., `, Steps of while loops, 1. The test condition is evaluated and if it is true, the body of the loop is executed., 2. On execution of the body, test condition is repetitively checked and if it is true the body is, executed., 3. The process of execution of the body will be continuing till the test condition becomes false., 4. The control is transferred out of the loop., VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 45
Page 46 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , 1./* Program to print 1 to 10 numbers */, #include<stdio.h>, int main(), {, int i = 1;, while(i<=10), {, printf("%d ",i);, i++;, }, }, Output, 1 2 3 4 5 6 7 8 9 10, In above program i is loop control variable. i is initialized with 1 . The loop will be executed 10, times., 2. /* Program to find the sum of digits in a given number */, #include<stdio.h>, int main(), {, Sum = 0 n = 568, int n,k,sum=0;, printf("Enter a number :");, scanf("%d",&n);, k, sum, n, while(n!=0), {, 8, 8, 56, k= n%10;, 6, 14, 5, sum = sum+k;, 5, 19, 0, n = n/10;, }, printf("Sum of digits = %d",sum);, }, Output, Enter a number : 568, Sum of digits = 19, Explaination:, The variable sum is initialized with 0(sum = 0), The value of n is entered as 568 (n = 568), i. In while statement condition (n!=0) is checked., (n!=0) is true because n is 568, The following statements are evaluated, k= n%10;, sum = sum+k;, n = n/10;, i.e k = 8, sum = 8, n = 56 then goto step ii, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 46
Page 47 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , ii. (n!=0) is true because n is 56 now., Here k = 6,sum = 14, n = 5 then goto step iii, iii. (n!=0) is true because n is 5 now., Here k = 5,sum = 19, n = 0 then goto step iv, iv. (n!=0) is false because n is 0 now then goto step v, v. printf("Sum of digits = %d",sum); is executed, , The output is, Sum of digits = 19, , 3. /*Program to print the reverse of a given number */, #include<stdio.h>, int main(), {, int n,k,rev=0;, printf("Enter a number :");, scanf("%d",&n);, while(n!=0), {, k= n%10;, rev = (rev*10)+k;, n = n/10;, }, printf("Reverse Number = %d",rev);, }, Output, Enter a number : 5896, Reverse Number = 6985, 4. /* Program to find factorial of a given number */, #include<stdio.h>, int main(), {, int n,fact=1;, printf("Enter a number :");, scanf("%d",&n);, while(n>1), {, fact = fact * n;, n - -;, }, printf("Factorial = %d",fact);, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 47
Page 48 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , return 0;, }, Output, Enter a number : 5, Factorial = 120, 5./*Program to convert binary number to equivalent decimal number*/, #include<stdio.h>, int main(), {, long n;, int r,s=0,p=1;, printf("Enter a binary number :");, scanf("%ld",&n);, while(n!=0), {, r=n%10;, if(r>1 || r<0), {, printf("Invalid Binary Number");, break;, }, s = s+r*p;, p = p*2;, n=n/10;, }, printf("\nEquivalent Decimal = %d",s);, return 0;, }, Output, Enter a binary number : 1100, Equivalent decimal number : 12, b) The do – while Loop, syntax, , Flowchart, , Intialisation;, do, {, Statements;, Updation ;, (loop control variable);, }, while(condition);, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 48
Page 49 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Do-while is exit control(post test loop).The condition will be checked at end of the loop., The do-while executes until the condition becomes false., The difference between the while and do-while loop is in the place where the condition is to be, tested. In while loops the condition is tested first and then executes the body of loop if the condition is, true. Where as in the do-while, the condition is checked at the end of the loop. The do-while loop will, execute at least one time even if the condition is false initially, 1./*Program to print 1 to 10 numbers*/, #include<stdio.h>, int main(), {, int i=1;, do, {, printf("%d ",i);, i++;, }, while(i<=10);, return 0;, }, Output, 1 2 3 4 5 6 7 8 9 10, 2./* Program to check whether given number is prime or not */, #include<stdio.h>, int main(), {, int i=2,n,flag = 1;, printf("Enter a number :");, scanf("%d",&n);, do, {, if(n%i==0), {, flag = 0;, break;, }, i++;, }, while(i<n);, if(flag==1), printf("Prime Number");, else, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 49
Page 50 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , printf("Not Prime Number");, return 0;, }, Ouptut, Enter a number : 5, Prime Number, , Note:, The do-while can be used with multiple while statement loop. The sample format of do-while with, multiple while statement is as follows, Syntax :, do, {, while(condition), {, statements;, }, }, while(condition);, Difference between while and do..while, while, Entry control(pretest) loop, Test condition is checked at beginning, of the loop., Syntax:, Initialization;, while(test- condition), {, Statements;, Updation ;, (loop control variable), }, , do..while, Exit control(post test) loop, Test condition is checked at end of the loop, , Flow diagram:, , Flow diagram:, , Syntax:, Intialisation;, do, {, Statements;, Updation ;, (loop control variable);, }, while(condition);, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 50
Page 51 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , If the condition is true , the statements If the condition is true , the statements in the, in the loop are executed until condition loop are executed until condition is false., is false., If condition is false loop will not be Loop will be executed at least once even, executed at least once, though condition is false, c)The ‘for’ Loop, The for loop allows to execute a set of instructions until a certain condition is satisfied., Condition may be predefined or open-ended., Syntax :, for(initialization; test condition; increment/decrement), {, Statements;, }, Flow diagram, , Inc/dec, , Initializa tion, condition, , false, ?, , True, statements, , Explanation :, The initialization is used to initialize loop control variable. This statement is executed only once., The test condition is a relational expression that determines the number of iterations desired or it, determines when to exit from the loop. The ‘for’ loop continues to execute as long as conditional, test is satisfied. When the condition becomes false the control of the program exits from the body, of the ‘for’ loop and executes next statement after the body of the loop., , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 51
Page 52 :
PROGRAMMING FOR PROBLEM SOLVING, , , , UNIT -I, , Increment/decrement is used to update loop control variable. The body of the loop may contain, either a simple statement or multiple statements. In case there is only one statement after for, loop braces may not be necessary. In such a case only one statement is executed till the condition, is satisfied. It is good practice to use braces even for single statement following the for loop., , Various Forms of ‘for’ loop, Syntax, 1) for (;;), 2) for (a=0; a<=20; ), 3) for (; a<=10; a++), 4) for(a=1; ; a++), 5) for( a=1; a<10; a++), , Output, Infinite Loop, Infinite Loop, Blank, Infinite Loop, Prints 1 to 9, , Remarks, No arguments, ‘a’ is neither increased or decreased, ‘a’ is not initialized, No condition is specified, ‘a’ is increased from 1 to 9, , 1./* Program to print 1 to 10 numbers */, #include<stdio.h>, int main(), {, int i;, for(i=1; i<=10; i++), printf(“%d\t”,i);, }, Output, 1 2 3 4 5 6 7 8 9 10, 2./* Program to find sum of 1 to 100 numbers */, #include<stdio.h>, int main(), {, int i, sum=0;, for(i=1; i<=100; i++), sum = sum + i;, printf(“Sum = %d’,sum);, return 0;, }, Output, Sum = 5050, 3./* Program to print multiplication table for a given number */, #include<stdio.h>, int main(), {, int i,num,pro;, printf("Enter a number :");, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 52
Page 53 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , scanf("%d",&num);, for(i=1; i<=10; i++), {, pro=num*i;, printf("%d x %d = %d\n",num,i,pro);, }, return 0;, }, Output, Enter a number : 5, 5x1=5, 5 x 2 = 10, 5 x 3 = 15, 5 x 4 = 20, 5 x 5 = 25, 5 x 6 = 30, 5 x 7 = 35, 5 x 8 = 40, 5 x 9 = 45, 5 x 10 = 50, 4./* Program to find the value of where, X = 1 + 1/4 + 1/9 + 1/16……… + 1/n2 ., Y = 1 + 1/8 + 1/27 + 1/64……… + 1/n3, Prompt the user to enter the value */, #include<math.h>, #include<stdio.h>, int main(), {, int i,n;, float x=0,y=0;, printf("Enter a number :");, scanf("%d",&n);, for(i=1; i<=n; i++), {, x = x +(1/pow(i,2));, y = y +(1/pow(i,3));, }, printf("x = %f\t y=%f",x,y);, return 0;, }, Output, Enter a number : 2, x = 1.250000 y = 1.125000, 5. /* Program to print Fibonacci series */, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 53
Page 54 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , #include<stdio.h>, int main(), {, int a,b,c,n,i;, printf("Enter n value:");, scanf("%d",&n);, a = 0;, b = 1;, printf("Fibonacci series:");, for(i=1;i<=n;i++), {, printf("%4d",a);, c = a+b;, a = b;, b = c;, }, return 0;, }, Output, Enter series number : 6, Fibonacci Series : 0 1 1 2 3 5, 6./*Program to print pascal triangle*/, #include<stdio.h>, int main(), {, int a=1,r=0,i,j,n;, printf("Enter the no. of rows : ");, scanf("%d",&n);, while(r<n), {, for(i=30-3*r; i>0; i--), printf(" ");, for(j=0; j<=r; j++), {, if(j==0||r==0), a=1;, else, a=(a*(r-j+1)/j);, printf("%6d",a);, }, printf("\n");, r++;, }, return 0;, }, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 54
Page 55 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Output, Enter no. of rows : 3, 1, 1, 1, , 1, 2, , 1, , Nested ‘for’ Loop, We can also use loop within loops. In nested for loops one or more for statements are included, in the body of the loop. In other words C allows multiple for loops in the nested forms. The number of, iterations in this type of structure will be equal to the number of iterations in the outer loop multiplied by, the number of iterations in the inner loop., , 1./*Program to print prime numbers from 1 to 20 */, #include<stdio.h>, int main(), {, int i,j,n,flag;, printf("Enter n value:");, scanf("%d",&n);, for(i=2;i<=n;i++), {, flag = 1;, for(j=2;j<=i/2;j++), {, if(i%j==0), {, flag = 0;, break;, }, }, if(flag==1), printf("%3d",i);, }, return 0;, }, Output, Enter a number : 20, 2 3 5 7 11 13 17 19, 2./* Program to print the following pattern, 1, 12, 123, */, #include<stdio.h>, int main(), VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 55
Page 56 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , {, int i,j;, for(i=1; i<=4; i++), {, for(j=1; j<=i; j++), {, printf("%d",j);, }, printf("\n");, }, }, , Output, 1, 12, 123, 3./* Program to print pyramid of numbers */, #include<stdio.h>, int main(), {, int i,j,n,x,k;, printf("Enter a number :");, scanf("%d",&n);, for(i=0; i<=n; i++), {, for(k=n; k>i; k--), printf(" ");, for(j=i; j>=0; j--), printf("%d",j);, for(x=1; x<=i; x++), printf("%d",x);, printf("\n");, }, }, Output, Enter a number : 2, , 2, , 1, 1, , 0, 0, 0, , 1, 1, , 2, , 4./* Program to calculate Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10! */, #include<stdio.h>, int main(), VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 56
Page 57 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , {, int i,f = 1,n;, float x,s=0,p=1;, printf("Enter x,n values:");, scanf("%f%d",&x,&n);, for(i=1;i<=n;i++), {, s = s+p/f;, p = -p*x*x;, f = f*(2*i-1)*2*i;, }, printf("The sum of the series = %f",s);, return 0;, }, Output, Enter x,n values:2 3, The sum of the series = -0.333333, JUMP STATEMENTS, a) break, b) continue, c) goto, d) return, a) The ‘break’ Statement, The keyword ‘break’ is used to terminate the loop. The break skips from loop or block in which, it is defined. The control then automatically goes to the first statement after the loop or block. The break, can be associated with the conditional statements like switch. The break can be used to stop the infinite, loop execution., We can also use break statements in the nested loops. If we use statement in the innermost loop, then the control of the program is terminated only from the inner most loop., , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 57
Page 58 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , Program to print sum of positive integers until negative number occurs, #include<stdio.h>, int main(), {, int i,x,s = 0;, printf("Enter 10 values:");, for(i = 1;i<=10;i++), {, scanf("%d",&x);, if(x<0), break;, s = s+x;, }, printf("The sum = %d",s);, }, OUTPUT, Enter 10 values:33 44 22 -88, The sum = 99, In above program break is used to terminate the loop if you enter negative value., b) The ‘continue’ Statement, The continue statement is exactly opposite to break. The continue is used to skip all the, statements which are followed by it and continues its execution from next iteration of the loop. When it, occurs in the loop it does not terminate, but it skips the statements after this statement. It is useful when, we want to continue the program without executing any part of the program., , Program to find sum of odd integers., #include<stdio.h>, int main(), {, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 58
Page 59 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , int i,x,s = 0;, printf("Enter 5 values:");, for(i = 1;i<=5;i++), {, scanf("%d",&x);, if(x%2 == 0), continue;, s = s+x;, }, printf("The sum of odd integers = %d",s);, }, Enter 5 values:11 22 33 44 55, The sum of odd integers = 99, -------------------------------In above program continue statement skips the statements after it in the loop if x is even number., If x is odd we will get sum., Deference between break and continue, SNO, , BREAK, , CONTINUE, , 1, , Break is used to terminate the execution, of loop where it is defined., , Continue is used to skip all the statements which are, followed by it and continuous its execution from, next iteration, , 2, , Break is used to leave from a case in, switch statement, , Continue is not allowed to use in switch statement, , 3, , Break is used in loops (while, do..while,, for) and case statements in switch, , Continue is use in loops(while, do..while, for) only., , 4, , Ex: Add positive integers, break at, negative, , Ex: Sum of odd integers, printf("Enter 5 values:");, for(i = 1;i<=5;i++), {, scanf("%d",&x);, if(x%2 == 0), continue;, s = s+x;, }, printf("The sum of odd integers = %d",s);, , printf("Enter 10 values:");, for(i = 1;i<=10;i++), {, scanf("%d",&x);, if(x<0), break;, s = s+x;, }, printf("The sum = %d",s);, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 59
Page 60 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , c) The ‘goto’ Statement, The goto statement does not require any condition. This statement passes control anywhere in the, program i.e. control is transferred to another part of the program without testing any condition. The user, has to define goto statement as follows:, goto label ;, where label name must start with any character. Label is the position where the control is to be, transferred., goto is two types, 1. forward goto, 2. backward goto, forward goto, This statement passes control to a particular statement in forward direction, Syntax:, goto label;, .., ., label: statement;, Example : program to find quotient of two numbers(division), Note: here the condition is denominator should not equal to zero., #include<stdio.h>, int main(), {, int a,b,s;, printf("Enter two values:");, scanf("%d%d",&a,&b);, if(b == 0), goto XYZ;, s = a/b;, printf("The result = %d",s);, XYZ: return 0;, }, Output 1, Enter two values:55 22, The result = 2, -------------------------------Output 2, Enter two values:55 0, -------------------------------Here if denominator (b) is zero control is passing to the lable XYZ;, backward goto, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 60
Page 61 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , This statement passes control to a particular statement in backward direction, Syntax:, label;, …, …, goto label:, Example : program to find quotient of two numbers(division), Note: here the condition is denominator should not equal to zero., #include<stdio.h>, int main(), {, int a,b,s;, XYZ:printf("Enter two values:");, scanf("%d%d",&a,&b);, if(b == 0), {, printf("Denominator is zero Enter values again\n");, goto XYZ;, }, s = a/b;, printf("The result = %d",s);, return 0;, }, , Output, Enter two values:33 0, Denominator is zero Enter values again, Enter two values:55 22, The result = 2, -------------------------------d)The ‘return’ Statement, The return statement transfers control from a function back to the activator of the function. For, the function main, control is transferred back to the operating system. The syntax of return is as follows, return expression;, expression is not mandatory in the syntax. Simple return also works., /* Program to check whether given number is even or odd using goto and return */, #include<stdio.h>, int main(), {, int x;, printf("Enter a number :");, VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 61
Page 62 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , scanf("%d",&x);, if(x%2==0), goto even;, else, goto odd;, even :, printf("Even number");, return;, odd :, printf(“Odd number”);, }, Output, Enter a number : 6, Even number, -o0o-, , Previous Questions, Theoretical Questions, 1., 2., 3., 4., 5., 6., 7., , What is an identifier? What are the naming rules for identifiers in C?, Explain different types of coding constants in a C?, List the basic data types, their sizes and range of values supported by ‘C’ language?, What are the differences between signed and unsigned data types, list out them?, Describe the purpose of commonly used conversion characters in scanf() function?, Explain the structure of a C program?, List different categories of C operators based on their functionality? Give examples?, (or), Explain the types of operators available in C?, 8. What are unary operators and their uses? Describe logical operators with their return values?, 9. What are various bitwise operations in ‘C’, explain them with an example?, (or), List and give examples for different bitwise operators available in ‘C’?, 10. What are various relational operators in ‘C’, explain them with an example., 11. Explain the only ternary operator available in ‘C’ with illustrative example?, 12. What do you mean by operator precedence and associativity? How one can override the, precedence defined by C language? Give illustrative examples?, 13. What is the implicit type conversion hierarchy that is applied while evaluating expressions?, (or), What is type conversion? Explain briefly about implicit and explicit type conversion, 14. Differentiate between if-else-if ladder and switch statement?, 15. Explain the control statements in ‘C’ language with an example?, 16. Explain various looping statements in ‘C’ language with example?, , Programming Questions, 1. Write a C program with Exclusive OR operation between the two integers and display the result?, 2. Write a C program to shift inputted data by 2 bits left?, , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 62
Page 63 :
PROGRAMMING FOR PROBLEM SOLVING, , UNIT -I, , 3. Write a complete C Program to print all the prime numbers between 1 and n. Where ‘n’ is the, value supplied by the user., 4. Write a complete C program that reads a value in the range 1 to 12 and print the name of that, month and the next month: Print error for any other input value. (For example, print “May, followed by June” if the input is 5. Note that December is followed by January)., 5. Write a complete C Program to read ten integers and find:, a. The number of even integers and their sum, and, b. The number of odd integers and their sum., 6. An integer is divisible by 9 if the sum of its digit is also divisible by 9. Write a C program that, prompts the user to input an integer. The program should then output the number and a message, stating whether it si divisible by 9., , Expression based Questions, 1. Write minimal C expressions for the following:, 4, , 3, , 2, , a. 2x + 3x - 4x + 7x -10, b. Digit at the 10's place of the given positive integer x (for example, digit at the 10's place, in 3458 is 5), c. True if the given positive integer x is odd, false otherwise, d. Add x to y, and then decrement x, e. True if 5 <= a <= 10, false otherwise, f. Fourth bit from the right if the number x is treated in binary representation., 2. Write minimal C expressions for the following:, 4, , 3, , 2, , a. 3x + x - 4x + 7x, b. Maximum of the values of three variables a, b and c, c. Digit at the 100's place of the given positive integer x (for example, digit at the 100's, place in 3458 is 4), d. True if the given positive integer x is even, false otherwise, e. Increment x, and then add to z, f. True if the given positive integer x is a multiple of 3 and 7, false otherwise., 3. Write minimal C expressions for the following:, a., b., c., d., e., f., , 3, , 2, , x - 4x + 7x -12, Absolute value of (a-b), Remainder when unsigned integer variable x is divided by 8, using bitwise operators., True if the given positive integer x is even and is also a multiple of 7, false otherwise., Minimum of the values of three variables a, b and c., True if the given character variable c represents a numeral (that is '0'...'9'), false, otherwise., 4. Write minimal C expressions for the following:, 3, , 2, , a. x -3x + 3x -1, b. Digit at the 10's place of the given positive integer x (for example, digit at the 10’s place, in 3458 is 5), c. True if the given positive integer x is a multiple of both 17 and 11, false otherwise., d. Remainder when unsigned integer variable x is divided by 8, using bitwise operators., e. True if 25 > a ≥ 10, false otherwise, f. Second bit from the right if the number x is treated in binary representation., , VIGNANA BHARATHI INSTITUTE OF TECHNOLOGY, , Page 63