Problem Solving Using C Notes PDF
Document Details
Sapthagiri NPS University
2024
Tags
Summary
These notes provide a comprehensive overview of problem-solving using the C programming language. The document is structured into modules covering various aspects such as data types, operators, input/output, arrays, strings, and memory management. The content is suitable for students in the School of Engineering and Technology at Sapthagiri NPS University.
Full Transcript
Problem Solving Using C Course Code: 24BTPHY104 02/08/2024 School of Engineering and Technology, Sapthagiri NPS University Problem Solving Using C TABLE OF CONTENT...
Problem Solving Using C Course Code: 24BTPHY104 02/08/2024 School of Engineering and Technology, Sapthagiri NPS University Problem Solving Using C TABLE OF CONTENTS Module 1................................................................................................................................................................. 4 1. INTRODUCTION TO PROGRAMMING CONCEPTS......................................................................... 4 1.1 Computer Languages................................................................................................................................ 4 1.2 Programming Language Translators....................................................................................................... 6 1.3 Software....................................................................................................................................................... 6 1.4 Modular Approach in Programming......................................................................................................... 8 1.5 Structured programming............................................................................................................................ 9 1.6 Algorithm.................................................................................................................................................... 10 1.7 Flowchart.................................................................................................................................................... 16 1.8 Overview of C Language......................................................................................................................... 20 1.9 History of C................................................................................................................................................ 20 1.10 Character set of C language................................................................................................................. 22 1.11 C Tokens.................................................................................................................................................. 23 1.12 Keywords................................................................................................................................................. 23 1.13 Identifiers................................................................................................................................................. 24 1.14 Constants................................................................................................................................................. 24 1.15 Data types................................................................................................................................................ 27 1.16 Variables.................................................................................................................................................. 30 1.17 Format Specifiers................................................................................................................................... 33 1.18 Operators and Expressions.................................................................................................................. 38 1.19 C Operators............................................................................................................................................. 40 1.20 Type Conversion.................................................................................................................................... 59 1.21 Library functions in C............................................................................................................................. 62 Module 2............................................................................................................................................................... 65 2. MANAGING INPUT AND OUTPUT OPERATIONS.............................................................................. 65 2.1 Unformatted I/O statements................................................................................................................ 65 2.2 Formatted I/O Functions...................................................................................................................... 68 2.3 Decision Making Statements.............................................................................................................. 72 2.4 Ternary operator................................................................................................................................... 90 2.5 Looping structure in C.......................................................................................................................... 91 2.6 Break statement.................................................................................................................................... 97 2.7 Continue statement.............................................................................................................................. 97 2.8 Goto statement...................................................................................................................................... 98 2.9 C Programs.......................................................................................................................................... 99 School of Engineering and Technology, Sapthagiri NPS University 1 Problem Solving Using C Module 3............................................................................................................................................................. 102 3.ARRAYS – STRINGS – STORAGE CLASSES.................................................................................... 102 3.1 Arrays................................................................................................................................................... 102 3.2 Single Dimensional Array.................................................................................................................. 103 3.3Two Dimensional arrays (Multidimensional array).......................................................................... 109 3.4 Strings.................................................................................................................................................. 115 3.5 Storage Classes............................................................................................................................ 121 Module 4............................................................................................................................................................. 125 4.FUNCTIONS AND POINTERS................................................................................................................ 125 4.1 Function Definition.............................................................................................................................. 127 4.2 Function Prototyping.......................................................................................................................... 128 4.3 Types of functions.............................................................................................................................. 130 4.4 Passing arguments to functions....................................................................................................... 134 4.5 Passing arrays to functions............................................................................................................... 134 4.6 Passing strings to functions.............................................................................................................. 137 4.7 Nested Functions................................................................................................................................ 139 4.8 Call by value........................................................................................................................................ 140 4.9 Call by reference................................................................................................................................. 141 4.10 Recursive functions.......................................................................................................................... 142 4.11 Pointers.............................................................................................................................................. 145 4.12 Pointers and Arrays.......................................................................................................................... 158 4.13 Arrays of Pointers............................................................................................................................. 161 4.14 Pointers and Structures................................................................................................................... 163 4.15 Meaning of static and dynamic memory allocation..................................................................... 164 4.16 Memory Allocation Functions......................................................................................................... 165 4.17 Macros................................................................................................................................................ 176 Module 5............................................................................................................................................................. 184 5. STRUCTURES AND UNIONS................................................................................................................ 184 5.1 Structures............................................................................................................................................. 184 5.2 Unions.................................................................................................................................................. 186 5.3 Nested Structures in C....................................................................................................................... 188 5.4 Arrays of Structures in C................................................................................................................... 191 5.5 Passing structures to functions......................................................................................................... 195 5.6 typedef in C.......................................................................................................................................... 199 5.7 Enum (Enumerated Data type) in C................................................................................................. 201 School of Engineering and Technology, Sapthagiri NPS University 2 Problem Solving Using C 5.8 Bit Fields in C...................................................................................................................................... 203 5.9 Command Line arguments................................................................................................................ 205 5.10 C pre-processor directives.............................................................................................................. 206 5.11 Files in C............................................................................................................................................ 208 5.11.3 Text and Binary File...................................................................................................................... 218 School of Engineering and Technology, Sapthagiri NPS University 3 Problem Solving Using C Course: Problem Solving Techniques using C Course Code: 24BTPHY104 Module 1 1. INTRODUCTION TO PROGRAMMING CONCEPTS Programming Language A language that is acceptable to a computer system is called a computer language or programming language and the process of creating a sequence of instructions in such a language is called programming or coding. A program is a set of instructions, written to perform a specific task by the computer. A set of large programs is called software. To develop software, one must have knowledge of a programming language. A programming language is a set of symbols, grammars and rules with the help of which one is able to translate algorithms to programs that will be executed by the computer. The programmer communicates with a machine using programming languages. Before moving on to any programming language, it is important to know about the various types of languages used by the computer. Let us first know what the basic requirements of the programmers were & what difficulties they faced while programming in that language. 1.1 Computer Languages Languages are a means of communication. Normally people interact with each other through a language. On the same pattern, communication with computers is carried out through a language. This language is understood both by the user and the machine. Just as every language like English, Hindi has its own grammatical rules; every computer language is also bounded by rules known as syntax of that language. The user is bound by that syntax while communicating with the computer system. Computer languages are broadly classified as: 1.1.1 Low Level Language: The term low level highlights the fact that it is closer to a School of Engineering and Technology, Sapthagiri NPS University 4 Problem Solving Using C language which the machine understands. The low-level languages are classified as: Machine Language: This is the language (in the form of 0’s and 1’s, called binary numbers) understood directly by the computer. It is machine dependent. It is difficult to learn and even more difficult to write programs. Assembly Language: This is the language where the machine codes comprising of 0’sand 1’s are substituted by symbolic codes (called mnemonics) to improve their understanding. It is the first step to improve programming structure. Assembly language programming is simpler and less time consuming than machine level programming, it is easier to locate and correct errors in assembly language than in machine language programs. It is also machine dependent. Programmers must have knowledge of the machine on which the program will run. 1.1.2 High Level Language: Low level language requires extensive knowledge of the hardware since it is machine dependent. To overcome this limitation, high level language has been evolved which uses normal English, which is easy to understand to solve any problem. High level languages are computer independent and programming becomes quite easy and simple. Various high-level languages are given below: a. BASIC (Beginners All Purpose Symbolic Instruction Code): It is widely used, easy to learn general purpose language. Mainly used in microcomputers in earlier days. b. COBOL (Common Business Oriented language): A standardized language used for commercial applications. c. FORTRAN (Formula Translation): Developed for solving mathematical and scientific problems. One of the most popular languages among scientific community. d. C: Structured Programming Language used for all purpose such as scientific application, commercial application, developing games etc. e. C++: Popular object-oriented programming language, used for general purpose. School of Engineering and Technology, Sapthagiri NPS University 5 Problem Solving Using C 1.2 Programming Language Translators As you know that high level language is machine independent and assembly language though it is machine dependent yet mnemonics that are being used to represent instructions are not directly understandable by the machine. Hence to make the machine understand the instructions provided by both the languages, programming language instructors are used. They transform the instruction prepared by programmers into a form which can be interpreted & executed by the computer. Flowing are the various tools to achieve this purpose: 1.2.1 Compiler: The software that reads a program written in high level language and translates it into an equivalent program in machine language is called as compiler. The program written by the programmer in high level language is called source program and the program generated by the compiler after translation is called as object program. 1.2.2 Interpreter: it also executes instructions written in a high-level language. Both complier & interpreter have the same goal i.e. to convert high level language into binary instructions, but their method of execution is different. The complier converts the entire source code into machine level program, while the interpreter takes 1 statement, translates it, executes it & then again takes the next statement. 1.2.3 Assembler: The software that reads a program written in assembly language and translates it into an equivalent program in machine language is called as assembler. 1.2.4 Linker: A linker or link editor is a computer program that takes one or more object files generated by a compiler and combines them into a single executable file, library file, or another object file. 1.3 Software Software is a set of instructions, data or programs used to operate computers and execute specific tasks. It is the opposite of hardware, which describes the physical aspects of a computer. Software is a generic term used to refer to applications, scripts and programs that run on a device. This software is further classified as system software & application software School of Engineering and Technology, Sapthagiri NPS University 6 Problem Solving Using C 1.3.1 Classification of software System Software: System Software is necessary to manage computer resources and support the execution of application programs. Software like operating systems, compilers, editors and drivers, etc., come under this category. A computer cannot function without the presence of these. Operating systems are needed to link the machine-dependent needs of a program with the capabilities of the machine on which it runs. Compilers translate programs from high-level language to machine language. Application Software: Application software is designed to fulfill the user’s requirement by interacting with the user directly. It could be classified into two major categories are generic or customized. Generic Software is software that is open to all and behaves the same for all of its users. Its function is limited and not customized as per the user’s changing requirements. However, on the other hand, customized software is the software products designed per the client’s requirement, and are not available for all. School of Engineering and Technology, Sapthagiri NPS University 7 Problem Solving Using C System Software Application Software System software is used for operating the The user uses application software to computer hardware. perform a specific task. System software is installed on the computer Application software is installed according when the operating system is installed. to user requirements. System software provides the platform for Application software cannot run without the running application software. presence of system software. System software works/runs independently. At the same time, application software cannot work or run independently. The user does not interact with system In the application software, the user software because it works in the background. interacts directly. System software runs automatically when the Application software runs when the user computer is turned ON and STOP when the requests it. computer shutdown. 1.4 Modular Approach in Programming Modular programming is the process of subdividing a computer program into separate sub- programs. A module is a separate software component. It can often be used in a variety of applications and functions with other components of the system. Some programs might have thousands or millions of lines and to manage such programs it becomes quite difficult as there might be too many of syntax errors or logical errors present in the program, so to manage such type of programs concept of modular programming approached. School of Engineering and Technology, Sapthagiri NPS University 8 Problem Solving Using C Each sub-module contains something necessary to execute only one aspect of the desired functionality. Modular programming emphasis on breaking large programs into small problems to increase the maintainability, readability of the code and to make the program handy to make any changes in future or to correct the errors. Points which should be taken care of prior to modular program development: Limitations of each and every module should be decided. In which way a program is to be partitioned into different modules. Communication among different modules of the code for proper execution of the entire program. Advantages of Using Modular Programming Approach – Ease of Use: This approach allows simplicity, as rather than focusing on the entire thousands and millions of lines of code in one go we can access it in the form of modules. This allows ease in debugging the code and is prone to less error. Reusability: It allows the user to reuse the functionality with a different interface without typing the whole program again. Ease of Maintenance: It helps in less collision at the time of working on modules, helping a team to work with proper collaboration while working on a large application. 1.5 Structured programming Structured programming, or modular programming, is a programming paradigm that facilitates the creation of programs with readable code and reusable components. All modern programming languages support structured programming, but the mechanisms of support -- like the syntax of the programming languages -- vary. In Structured Programming, the code is divided into functions or modules. It is also known as modular programming. Modules or functions are a set of statements which performs a sub task. As each task is a separate module, it is easy for the programmer to test and debug. It is also easy to do modifications without changing the whole program. School of Engineering and Technology, Sapthagiri NPS University 9 Problem Solving Using C When changing the code, the programmer has to concentrate only on the specific module. C and Pascal are some examples of Structural Programming languages. Unstructured Programming In Unstructured Programming, the code is written as a single whole block. The whole program is taken as a single unit. It is harder to do changes in the program. This paradigm was used in earlier versions of BASIC, COBOL, and FORTRAN. Unstructured programming languages have a limited number of data types like numbers, arrays, strings. 1.6 Algorithm The word “algorithm” relates to the name of the mathematician Al-khowarizmi, which means a procedure or a technique. Software Engineer commonly uses an algorithm for planning and solving the problems. An algorithm is a sequence of steps to solve a particular problem or algorithm is an ordered set of unambiguous steps that produces a result and terminates in a finite time School of Engineering and Technology, Sapthagiri NPS University 10 Problem Solving Using C Algorithm has the following characteristics. Input: An algorithm may or may not require input Output: Each algorithm is expected to produce at least one result Definiteness: Each instruction must be clear and unambiguous. Finiteness: If the instructions of an algorithm are executed, the algorithm should terminate after finite number of steps The algorithm and flowchart include following three types of control structures. 1. Sequence: In the sequence structure, statements are placed one after the other and the execution takes place starting from up to down. 2. Branching (Selection): In branch control, there is a condition and according to a condition, a decision of either TRUE or FALSE is achieved. In the case of TRUE, one of the two branches are explored; but in the case of FALSE condition, the other alternative is taken. Generally, the ‘IF-THEN’ is used to represent branch control. 3. Loop (Repetition): The Loop or Repetition allows a statement(s) to be executed repeatedly based on certain loop condition e.g. WHILE, FOR loops. School of Engineering and Technology, Sapthagiri NPS University 11 Problem Solving Using C Advantages of algorithm It is a step-wise representation of a solution to a given problem, which makes it easy to understand. An algorithm uses a definite procedure. It is not dependent on any programming language, so it is easy to understand for anyone even without programming knowledge. Every step in an algorithm has its own logical sequence so it is easy to debug. Before writing an algorithm for a problem, one should find out what is/are the inputs to the algorithm and what is/are expected output after running the algorithm. Now let us take some exercises to develop an algorithm for some simple problems: While writing algorithms we will use following symbol for different operations: ‘+’ for Addition ‘-’ for Subtraction ‘*’ for Multiplication ‘/’ for Division and ‘ ’ for assignment. For example, A X*3 means A will have a value of X*3. Example of Algorithm Problem 1: Find the area of a Circle of radius r. Inputs to the algorithm: Radius r of the Circle. Expected output: Area of the Circle Algorithm: Step1: Read\input the Radius r of the Circle Step2: Area PI*r*r // calculation of area Step3: Print Area Step4: End School of Engineering and Technology, Sapthagiri NPS University 12 Problem Solving Using C Problem2: Write an algorithm to read two numbers and find their sum. Inputs to the algorithm: First num1. Second num2. Expected output: Sum of the two numbers. Algorithm: Step1: Start Step2: Read\input the first num1. Step3: Read\input the second num2. Step4: Sum num1+num2 // calculation of sum Step5: Print Sum Step6: End Problem3: Write an algorithm to find the largest of three numbers. Inputs to the algorithm: First num1. Second num2. Third num3. Expected output: Largest of three numbers. Algorithm: Step1: Start Step2: Read\input the first num1. Step3: Read\input the second num2. Step4: Read\input the third num3. Step5: If a>b If a>c Display a is the largest number. School of Engineering and Technology, Sapthagiri NPS University 13 Problem Solving Using C Else Display c is the largest number. Else If(b>c) Display b is the largest number Else Display c is the largest number Step5: Stop Problem 4: An algorithm to calculate even numbers between 0 and 99 1. Start 2. I ← 0 3. Write I in standard output 4. I ← I+2 5. If (I ‘ Single. Dot = Assignment quote , Comma \ backslash / Division School of Engineering and Technology, Sapthagiri NPS University 22 Problem Solving Using C 1.11 C Tokens ⮚ Tokens are the smallest or basic units of a C program. ⮚ One or more characters are grouped in sequence to form meaningful words. These meaningful words are called tokens. ⮚ A token is a collection of characters. ⮚ Tokens are classified in to 5 types as below: 1.12 Keywords ⮚ The tokens which have predefined meaning in C language are called keywords. ⮚ They are reserved for specific purposes in C language they are called Reserved Words. ⮚ There are totally 32 keywords supported in C they are: Auto double if Static Break else int Struct Case enum long Switch Char extern near Typedef Const float register Union Continue for return Unsigned Default volatile short Void Do goto signed While Rules for keywords 1. Keywords should not be used as variables, function names, array names etc. 2. All keywords should be written in lowercase letters. Keywords meaning cannot be changed by the users. School of Engineering and Technology, Sapthagiri NPS University 23 Problem Solving Using C 1.13 Identifiers Definition: ⮚ Identifiers are the names given to program elements such as variables, constants, function names, array names etc. ⮚ It consists of one or more letters or digits or underscores. Rules for identifiers 1. The First character should be an alphabet or an underscore _ Then the First character is followed by any number of letters or digits. No extra symbols are allowed other than letters, digits and Underscore 2. Keywords cannot be used as an identifier 3. The length can be 31 characters for external, 63 for internal. 4. Identifiers are case sensitive Identifier Reasons for invalidity india06 Valid _india Valid india_06 Valid india_06_king Valid india valid 06india not valid as it starts from digits int not valid since int is a keyword india 06 not valid since there is space between india and 06 india@06 not valid since @ is not allowed 1.14 Constants Definition: Constants refers to fixed values that do not change during the execution of a program The different types of constants are: School of Engineering and Technology, Sapthagiri NPS University 24 Problem Solving Using C 1. Integer constant 2. Real constant/Floating Pointing constant 3. Enumeration constant 4. Character constant 5. String constant Integer constant ⮚ Definition: An integer is whole number without any decimal point.no extra characters are allowed other than + or _. Three types of integers ⮚ Decimal integers: are constants with a combination of digits 0 to 9, optional + or - Ex: 123, -345, 0, 5436, +79 ⮚ Octal integers: are constants with a combination of Digits from 0 to 7 but it has a prefix of 0 Ex: 027, 0657, 0777645 ⮚ Hexadecimal integers: Digits from 0 to 9 and characters from a to f, it has to start with 0X or 0x Ex: 0X2 0x56 0X5fd 0xbdae Real constants/Floating point Floating point constants are base 10 numbers that are represented by fractional parts, such as 10.5. They can be positive or negative. Two forms are: i. Fractional form: ⮚ A floating-point number represented using fractional form has an integer part followed by dot and a fractional part. Ex: 0.0083 ⮚ 215.5 ⮚ -71. ⮚ +0.56 etc... ii. Exponential form: School of Engineering and Technology, Sapthagiri NPS University 25 Problem Solving Using C ⮚ A floating-point number represented using Exponent form has 3 parts ⮚ mantissa e exponent ⮚ Mantissa is either real number expressed in decimal notation or integer. ⮚ Exponent must be integer with optional + or – ⮚ Ex 9.86 E 3 => 9.86*103 ⮚ Ex 9.86 E -3 => 9.86*10-3 Enumeration constant A set of named integer constants defined using the keyword enum are called enumeration constants. Syntax: enum identifier{enum list}; enum Boolean{NO,YES}; NO is assigned with 0 YES is assigned with value 1 enum days{ mon,tue.wed}; mon is assigned with 0 tue is assigned with 1 wed is assigned with 2 Character constant A symbol enclosed within pair of single quotes is called character constant. Each character is associated with unique value called ASCII value. Ex: ‘9’ ‘$’ Backslash constants (Escape sequence character) ⮚ Definition: An escape sequence character begins with backslash and is followed by one character. ⮚ A backslash along with a character give rise to special print effects. ⮚ It always starts with backslash; hence they are called as backslash constants. Character Name Meaning \a Bell Beep sound School of Engineering and Technology, Sapthagiri NPS University 26 Problem Solving Using C \b Backspace Cursor moves towards left by one Position \n Newline Cursor moves to next line \t Horizontal tab Cursor moves towards right by 8 Position \r Carriage return Cursor moves towards beginning of the same line \” Double quotes Double quotes \’ Single quotes Single quotes \? Question mark Question mark \\ Backslash Backslash \0 NULL String constant A sequence of characters enclosed within pair of double quotes is called string constant. The string always ends with a NULL character. Ex: “9” “SNPS” 1.15 Data types Definition: The data type defines the type of data stored in memory location or the type of data the variable can hold. ⮚ The classification of data types are: School of Engineering and Technology, Sapthagiri NPS University 27 Problem Solving Using C ⮚ There are few basic data types supported in C. 1. int 2. float 3. double 4. char 5. void Integer data type(int) ⮚ It stores an integer value or integer constant. ⮚ An int is a keyword using which the programmer can inform the compiler that the data associated with this keyword should be treated as integer. ⮚ C supports 3 different types of integer: o short int, o int, o long int n-bit Type Size Range of Range of signed machi unsigned int int ne 0 to 2n-1 be -2n to +2n -1 16- bit short int 2 0 to 216-1 -215 to +215 -1 bytes Machin 0 to 65535 -32768 to +32767 e School of Engineering and Technology, Sapthagiri NPS University 28 Problem Solving Using C Int 2 0 to 216-1 -215 to +215 -1 bytes 0 to 65535 -32768 to +32767 long int 4 0 to 232-1 -231 to +231 -1 bytes 0 to 4294967295 -2147483648 to + 2147483647 Floating data type (float) A float is a keyword using which the programmer can inform the compiler that the data associated with this keyword should be treated as floating point number. The size is 4 bytes. The range is -3.4e38 to +3.4e38. Float can hold the real constant accuracy up to 6 digits after the decimal point. Double data type (double) A double is a keyword using which the programmer can inform the compiler that the data associated with this keyword should be treated as long floating-point number. The size is 8 bytes. The range is from 1.7e-308 to 1.7 e+308. Double can hold real constant up to 16 digits after the decimal point. Character data type (char) Char is a keyword which is used to define single character or a sequence of character in c language capable of holding one character from the local character set. The size of the character variable is 1 byte. The range is from -128 to +127. Each character stored in the memory is associated with a unique value termed as ASCII (American Standard Code for Information Interchange). It is used to represent character and strings. School of Engineering and Technology, Sapthagiri NPS University 29 Problem Solving Using C n-bit Type size Range of Range of machi unsigned char signed ne 0 to 2n-1 char be -2n to +2n -1 16- short int 2 0 to 28-1 -27 to +27 -1 bytes 0 to 255 -128 to +127 bit machi ne void data type (void) It is an empty data type. No memory is allocated. Mainly used when there are no return values. 1.16 Variables ⮚ A variable is a name given to memory location where data can be stored. ⮚ Using variable name data can be stored in a memory location and can be accessed or manipulated very easily. Rules for variables ⮚ The First character should be an alphabet or an underscore _ ⮚ Then the First character is followed by any number of letters or digits. ⮚ No extra symbols are allowed other than letters, digits and Underscore ⮚ Keywords cannot be used as an identifier Example: Sum – valid For1- valid for -invalid (it is a keyword) Declaration of variables: ⮚ Giving a name to a memory location is called declaring a variable. ⮚ Reserving the required memory space to store the data is called defining a variable. ⮚ General Syntax: School of Engineering and Technology, Sapthagiri NPS University 30 Problem Solving Using C data type variable; (or) datatype variable1, variable2,… variableN; example: int a; float x, y; double sum; From the examples we will come to know that “a” is a variable of type integer and allocates 2 bytes of memory. “x” and “y” are two variables of type float which will be allocated 4 bytes of memory for each variable. “sum” is a double type variable which will be allocated with 8 bytes of memory for each. Variable Initialization ⮚ Variables are not initialized when they are declared and defined, they contain garbage values (meaningless values) ⮚ The method of giving initial values for variables before they are processed is called variable initialization. ⮚ General Syntax: Var_name = expr; Where, Var_name is the name of the variable. expr is the value of the expression. ⮚ The “expr” on the right-hand side is evaluated and stored in the variable name (Var_name) on the left-hand side. ⮚ The expression on the right-hand side may be a constant, variable or a larger formula built from simple expressions by arithmetic operators. Examples: int a=10; // assigns the value 10 to the integer variable a float x; x=20; // creates a variable y of float type and assigns value 20 to it. School of Engineering and Technology, Sapthagiri NPS University 31 Problem Solving Using C int a=10,b,b=a; // creates two variables a and b. “a” is assigned with value 10, the value of “a” is assigned to variable “b”. Now the value of b will be 10. price = cost*3; //assigns the product of cost and 3 to price. Square = num*num; // assigns the product of num with num to square. OUTPUT FUNCTION Displaying Output using printf ⮚ printf is an output statement in C used to display the content on the screen. ⮚ print: Print the data stored in the specified memory location or variable. ⮚ Format: The data present in memory location is formatted in to appropriate data type. ⮚ There are various forms of printf statements. Method 1: printf(“ format string”); ⮚ Format string may be any character. The characters included within the double quotes will be displayed on the output screen ⮚ Example: printf(“Welcome to India”); Output: Welcome to India Method 2: printf(“ format string”, variable list); ⮚ Format string also called as control string. ⮚ Format string consist of format specifier of particular data type School of Engineering and Technology, Sapthagiri NPS University 32 Problem Solving Using C ⮚ Format specifiers start with % sign followed by conversion code. ⮚ variable lists are the variable names separated by comma. ⮚ Example: int a=10; float b=20; printf(“ integer =%d, floating=%f”,a,b); output: integer=10, floating=20.00000 ⮚ Number of format specifiers must be equal to the number of variables. ⮚ While specifying the variable name make sure that it matches the format specifiers within the double quotes. 1.17 Format Specifiers ⮚ Format specifiers are the character string with % sign followed with a character. ⮚ It specifies the type of data that is being processed. ⮚ It is also called conversion specifier or conversion code. ⮚ There are many format specifiers defined in C. Symbols Meaning %d Decimal signed integer number %f float point number %c Character %o octal number %x hexadecimal integer (Lower case letter x) School of Engineering and Technology, Sapthagiri NPS University 33 Problem Solving Using C %X hexadecimal integer (Upper case letter X) %e floating point value with exponent (Lower case letter e) %E floating point value with exponent (Upper case letter E) %ld long integer %s String %lf Double Input Function (scanf) Inputting Values Using scanf ⮚ To enter the input through the input devices like keyboard we make use of scanf statement. General Syntax: scanf(“format string”, list of address of variables); Where, Format string consists of the access specifiers/format specifiers. ⮚ Format string also called as control string. ⮚ Format string consist of format specifier of particular data type ⮚ Format specifiers starts with % sign followed by conversion code. ⮚ List of addresses of variables consist of the variable name preceded with & symbol (address operator). Example: int a; float b; scanf(“%d%f”,&a,&b); Rules for scanf No escape sequences or additional blank spaces should be specified in the format specifiers. Ex: scanf(“%d %f”,&a,&b); //invalid scanf(“%d\n%f”,&a,&b); //invalid & symbol is must to read the values, if not the entered value will not be stored in the variable specified. Ex: scanf(“%d%f”,a,b);//invalid. School of Engineering and Technology, Sapthagiri NPS University 34 Problem Solving Using C A Simple C Program Example 1: Let us discuss a simple program to print the Hello SNPS #include void main( ) { printf (“Hello SNPS”); } Output: Hello SNPS Example 2: Consider another example program to find the simple interest #include void main ( ) { float p,t,r; float si; printf (“enter the values of p,t,r\n”); scanf(“%f%f%f”,&p,&t,&r); si = (p*t*r)/100; printf ("Simple Interest=%f",si); } The above program illustrates the calculation of simple interest. ⮚ Firstly, we have declared the header files stdio.h for including standard input and output which will be printf and scanf statements. ⮚ Next, we start with the main program indicated by void main( ) ⮚ Within the main program we declare the required variables for calculating the simple interest. So, we declare p, t and r as float type and si as float type. ⮚ After which the values to p, t and r are read from keyboard using scanf. ⮚ Computed the simple interest by the formula (p*t*r)/100 and the result is assigned to si. ⮚ Display the result si. School of Engineering and Technology, Sapthagiri NPS University 35 Problem Solving Using C Structure of C Program Comments/Documentation Section Preprocessor Directives Global declaration section void main( ) [Program Header] { Local Declaration part Execution part Statement 1 ------------ ------------ Statement n } User defined Functions Comments/Documentation Section ⮚ Comments are short explaining the purpose of the program or a statement. ⮚ They are non-executable statements which are ignored by the compiler. The comment begins with. ⮚ The symbols are called comment line delimiters. ⮚ We can put any message we want in the comments. Example: Note: Comments are ignored by C compiler, i.e. everything within comment delimiters Preprocessor Directives ⮚ Preprocessor Directives begins with a # symbol ⮚ Provides instructions to the compiler to include some of the files before compilation starts. ⮚ Some examples of header files are School of Engineering and Technology, Sapthagiri NPS University 36 Problem Solving Using C #include #include #include #include #include Etc… Global Declaration Section ⮚ There will be some variable which has to be used in anywhere in program and used in more than one function which will be declared as global. The Program Header ⮚ Every program must contain a main () function. ⮚ The execution always starts from main function. ⮚ Every C program must have only one main function. Body of the program ⮚ Series of statements that performs specific task will be enclosed within braces { and } ⮚ It is present immediately after program header. It consists of two parts 1. Local Declaration part: Describes variables of program Ex:int sum = 0; int a , b: float b; 2. Executable part: Task done using statements. 3. All statements should end with semicolon(;) Subroutine Section: All user defined functions that are called in main function should be defined.. School of Engineering and Technology, Sapthagiri NPS University 37 Problem Solving Using C 1.18 Operators and Expressions Operators: “An operator is a symbol that specifies the operation to be performed on various types of operands”. Or in other words “An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations”. Operators are used in programs to manipulate data and variable. Example: +, - ,* Operand: The entity on which a operator operates is called an operand. Here the entity may be a constant or a variable or a function. An operator may have one or two or three operands. Example: a+b-c*d/e%f In this example there are 6 operands ie a, b, c, d, e, f and 5 operators i.e +,-,*,/ and %. Expression: A combination of operands and operators that reduces to a single value is called an expression. Eg:a+b/d School of Engineering and Technology, Sapthagiri NPS University 38 Problem Solving Using C Classification of operators Classification of operators based on operands ⮚ The Operators are classified into four major categories based on the number of operands as shown below: ⮚ Unary Operators 1) Binary Operators 2) Ternary Operators 3) Special Operators 1. Unary Operators: An operator which acts on only one operand to produce the result is called unary operator. The Operators precede the operand. Examples: -10 -a --b 2. Binary Operators: An operator which acts on two operands to produce the result is called a binary operator. In an expression involving a binary operator, the operator is in between two operands. Examples: a + b a*b School of Engineering and Technology, Sapthagiri NPS University 39 Problem Solving Using C 3. Ternary Operator: An operator which acts on three operands to produce a result is called a ternary operator. ⮚ Ternary operator is also called a conditional operator. Example: a ?b : c ⮚ Since there are three operands a, b and c (hence the name ternary) that are associated with operators? and it is called ternary operator. 1.19 C Operators C operators can be classified based on type of operation 1. Arithmetic operators 2. Relational operators 3. Logical operators 4. Assignment operators 5. Increment and decrement operators 6. Conditional operators 7. Bitwise operators 8. Special operators Arithmetic operators ⮚ C provides all basic arithmetic operators. The operators that are used to perform arithmetic operation such as addition, subtraction, multiplication, division etc are called arithmetic operators. ⮚ The operators are +, - ,* , / , %. ⮚ Let a=10, b=5. Here, a and b are variables and are known as operands. Description Symbo Example Res Priorit Associativity l ult y Addition + a+b = 10 + 5 15 2 L-R Subtraction - a-b = 10 – 5 5 2 L-R School of Engineering and Technology, Sapthagiri NPS University 40 Problem Solving Using C Multiplication * a* b = 10 * 5 50 1 L-R Division (Quotient) / a/b = 10/5 2 1 L-R Modulus % a % b = 10 % 5 0 1 L-R (Remainder) #include void main() { int a, b, sum,diff,mul,divres,modres; printf(“enter a and b value\n”); scanf(“%d %d”,&a,&b); sum=a+b; diff=a-b; mul=a*b; divres=a/b; modres=a% b; printf(“%d, %d, %d ,%d ,%d\n”, sum,diff,mul,divres,modres); } Output: 35,25,150,6,0 Converting Mathematical Expression into C Expression Mathematical C expression Expression a÷b a/b S=a+b+c S=(a+b+c)/2 2 Area=√s(s-a)(s-b)(s-c) Area=sqrt(s*(s-a) *(s-b) *(s-c)) ax2+bx+c a*x*x+b*x+c e|a| exp(abs(a)) School of Engineering and Technology, Sapthagiri NPS University 41 Problem Solving Using C Relational Operators ⮚ We often compare two quantities depending on their relation, take certain decisions. ⮚ For example, we compare the age of two persons, or the price of two items, and so on. These comparisons can be done with the help of relational operators. ⮚ The operators that are used to find the relationship between two operands are called as relational expression. ⮚ An expression such as a10 T >= is greater than or 1 L->R 20>=10 T equal to == is Equal to 2 L->R 20==10 F != is not equal to 2 L->R 20!=10 T Logical Operators ⮚ The operator that are used to combine two or more relational expression is called logical operators. ⮚ Result of logical operators is always true or School of Engineering and Technology, Sapthagiri NPS University 42 Problem Solving Using C false. Logical Operators in C are: Operator Meaning Precedence Associativity && logical AND 2 L->R || logical OR 3 L->R ! logical NOT 1 L->R Logical AND (&&) The output of logical operation is true if and only if both the operands are evaluated to true. operand AND operand result 1 2 True (1) && True(1) True(1 ) True (1) && False(0) False( 0) False(0) && True(1) False( 0) False(0) && False(0) False( 0) Example: 36 && 0 =1 && 0 =0(False) Logical OR (||) The output of logical operation is false if and only if both the operands are evaluated to false. School of Engineering and Technology, Sapthagiri NPS University 43 Problem Solving Using C operand OR operand Result 1 2 True (1) || True(1) True(1 ) True (1) || False(0) True(1 ) False(0) || True(1) True(1 ) False(0) || False(0) False( 0) Example: 36 || 0 =1 || 0 =0(True) Logical NOT It is a unary operator. The result is true if the operand is false and the result is false if the operand is true. operand ! operand True (1) False(0) False(0) True (1) Example: (a) !0=1 (b) !36 !1=0 NOTE: The logical operators && and | | are used when we want to test more than one condition and make decisions. An example: a>b && x==10 The above logical expression is true only if a>b is true and x==10 is true. If either (or School of Engineering and Technology, Sapthagiri NPS University 44 Problem Solving Using C both) of them are false, the expression is false. Assignment Operators An operator which is used to assign the data or result of an expression into a variable is called Assignment operators. The usual assignment operator is =. Types of Assignment Statements: 1. Simple assignment statement 2. Short Hand assignment statement 3. Multiple assignment statement 1. Simple assignment statement Syntax: Variable=expression; Ex: a= 10; //RHS is constant a=b; // RHS is variable. a=b+c; //RHS is an expression So, 1. A expression can be a constant, variable or expression. 2. The symbol = is assignment operator 3. The expression on right side of assignment is evaluated and the result is converted into type of variable on left hand side of Assignment operator. 4. The converted data is copied into variable which is present on left hand side (LHS) of assignment operator. Example: int a; a=100; // the value 100 is assigned to variable a int a=100; School of Engineering and Technology, Sapthagiri NPS University 45 Problem Solving Using C int b; b=a; // a value i.e 100 is assigned to b 2. Short Hand assignment Statement C has a set of “shorthand‟ assignment operators of the form. var op = exp; where v is a variable, exp is an expression and op is a C library arithmetic operator. The operator op= is known as the shorthand assignment operator. The assignment statements var op= exp; is equivalent to v= var op (exp). with var evaluated only once. The operators such as +=, -=, *=,/= are called assignment operators. Example: The statement x = x+ 10; can be written as x + = 10; Example: Solve the equation x*=y+z when x=10, y=5 and z=3 Solution: x*=y+z can be written as x=x*(y+z) x =10*(5+3) x=10*8 x=80 shorthand Meaning Description assignment a+=2 a=a+2 Find a+2 and store result in a School of Engineering and Technology, Sapthagiri NPS University 46 Problem Solving Using C a-=2 a=a-2 Find a-2 and store result in a a*=2 a=a*2 Find a*2 and store result in a a/=2 a=a/2 Find a/2 and store result in a 3. Multiple Assignment Statement A statement in which a value or set of values are assigned to more than one variable is called multiple assignment statement. Example: i=10; j=10; k=10; can be written as: i=j=k=10; //Multiple assignment statement Note: Assignment operator is right associative operator. Hence in the above statement 10 is assigned to k first, the k is assigned to j and j is assigned to i. Increment and Decrement Operators ⮚ C allows two very useful operators not generally found in other languages. These are the increment and decrement operators: ++ and -- ⮚ The operator ++ adds 1 to the operand, while -- subtracts 1. The increment and decrement operators are Unary operators. ⮚ The increment and decrement operators are classified into two categories: 1. Post Increment and Post Decrement: ⮚ If increment or decrement operator is placed immediately after the operand is called Post Increment and Post Decrement. ⮚ As the name indicates Post Increment and Post Decrement means increment or School of Engineering and Technology, Sapthagiri NPS University 47 Problem Solving Using C decrement the operand value is used. ⮚ So, operand value is used first and then the operand value is incremented or decremented by 1. Example: Post Increment: a++ equivalent to a=a+1 Post Decrement: a— equivalent to a=a-1 Post Increment: Eg1: #include Output:21 void main() Description: Initial value of a is 20 after { int a=20; execution of a++, the value of a will be 21. a++; printf(“%d”,a); } Eg2: #include Output : a= 21 void main( ) b=20 { int a=20,b; b=a++; printf(“a=%d”,a); printf(“b=%d”,b); } Post Decrement: Eg 1: #include Output:19 void main() Description: Initial value of a is 20 after { int a=20; execution of a--, the value of a will be School of Engineering and Technology, Sapthagiri NPS University 48 Problem Solving Using C 19. a--; printf(“%d”,a); } 2. Pre-Increment and Pre-Decrement ⮚ If increment or decrement operator is placed before the operand is called Pre Increment and Pre Decrement. ⮚ As the name indicates Pre-Increment and Pre-Decrement means increment or decrement before the operand value is used. ⮚ So, the operand value is incremented or decremented by 1 first then operand value is used. Example: Post Increment: ++a equivalent to a+1=a Post Decrement: a-- equivalent to a-1=a Pre-Increment: Eg 1: #include Output:21 void main() Description: Initial value of a is 20 after { int a=20; execution of ++a, the value of a will be 21. ++a; printf(“%d”,a); } Pre-Decrement: Eg 1: #include Output:19 void main() Description: Initial value of a is 20 after { int a=20; execution of --a, the value of a will be 19. --a; School of Engineering and Technology, Sapthagiri NPS University 49 Problem Solving Using C printf(“%d”,a); } Consider the following (let a=20) Post increment b=a++ current value of a used, b=a //b=20 a is incremented by 1 a=a+1 //a=21 Pre-increment b=++a a is incremented by 1, a=a+1 //a=21 incremented value of a used, b=a //b=21 Post Decrement (let a=10) b=a-- current value of a used, b=a //b=10 a is decremented by 1 a=a-1 //a=9 Pre-decrement (let a=10) b=--a a is decremented by 1, a=a-1 // a=9 decremented value of a used, b=a // b=9 Conditional Operator (OR) Ternary Operator The operator which operates on 3 operands are called Ternary operator or conditional operator. Syntax: (exp1)? exp2: exp3 where exp1, exp2, and exp3 are expressions and ⮚ exp1 is an expression evaluated to true or false ⮚ if exp1 is evaluated to true exp2 is executed ⮚ if exp1 is evaluated false exp3 is executed For example, consider the following statements. a=10; b=15; Max = (a>b)? a:b; School of Engineering and Technology, Sapthagiri NPS University 50 Problem Solving Using C In this example, Max will be assigned the value of b i.e b=15. This can be achieved using the if… else statements as follows: if (a>b) x=a; else x=b; Bitwise Operators Bitwise operators are used to manipulate the bits of given data. These operators are used for testing the bits, or shifting them right or left. Bitwise operators may not be applied to float or double. Operator Meaning Preceden Associativi ce ty ~ Bitwise Negate 1 R->L R >> Bitwise Right Shift 2 L->R & Bitwise AND 3 L->R ^ Bitwise XOR (exclusive OR) 4 L->R | Bitwise OR 5 L->R 1) Bitwise AND (&) If the corresponding bit positions in both the operand are 1, then AND operation results in 1; otherwise 0. operand AND operand result 1 2 0 & 0 0 0 & 1 0 1 & 0 0 1 & 1 1 School of Engineering and Technology, Sapthagiri NPS University 51 Problem Solving Using C a=10 00001010 b=6 00000110 (a&b) c=2 00000010 2)Bitwise OR (|) If the corresponding bit positions in both the operands are 0, then OR operation results in 0; otherwise 1. operand OR operand Result 1 2 0 | 0 0 0 | 1 1 1 | 0 1 1 | 1 1 a=10 00001010 b=6 00000110 (a|b) c=2 00001110 Bitwise XOR (^) If the corresponding bit positions in both the operand are different, then XOR operation results in 1; otherwise the result is 0. operand XOR operand result 1 2 0 ^ 0 0 0 ^ 1 1 1 ^ 0 1 1 ^ 1 0 School of Engineering and Technology, Sapthagiri NPS University 52 Problem Solving Using C a=10 00001010 b=6 00000110 (a^b) c=12 00001100 Left shift operator (1=%d”,a,b); } Bitwise negate: The operator that is used to change every bit from 0 to 1 and 1 to 0 in the specified operand is called bitwise negate operator. It is used to find one’s compliment of an operand. Example: #include void main() {int a=10,b; b=~a; printf(“Negation of a is %d”,b); } Tracing: a=10 00001010 School of Engineering and Technology, Sapthagiri NPS University 54 Problem Solving Using C b=245 11110101 Special Operators C supports some special operators of interest such as comma operator, sizeof operator. The Comma Operator ❖ The comma operator can be used to link the related expressions together. A comma- linked list of expressions are evaluated from left to right. The comma operator has least precedence among all operator. ❖ It is a binary operator which is used to: 1. Separate items in the list. E.g. a=12,35,678; 2. Combine two or more statements into a single statement. E.g. int a=10; int b=20; int c=30; can be combined using comma operator as follows: int a=10, b=20, c=30; Example, the statement: value = (x=10, y=5, x+y) first assigns the value 10 to x, then assigns 5 to y, and finally assigns 15 to value. Since comma operator has the lowest precedence of all operators, the parentheses are necessary. The sizeof () Operator The sizeof () is a compile time operator and, when used with an operand, it returns the number of bytes the operand occupies. The operand may be a variable, or a constant or a data type qualifier. Syntax: sizeof(operand) School of Engineering and Technology, Sapthagiri NPS University 55 Problem Solving Using C Examples: 1. sizeof(char); Output:1 Byte 2 int a; Output:2 Byte sizeof(a) Precedence [Priority] It is the rule that specifies the order in which certain operations need to be performed in an expression. For a given expression containing more than two operators, it determines which operations should be calculated first. Associativity If all the operators in an expression have equal priority then the direction or order chosen left to right or right to left to evaluate an expression is called associativity. Associativity Left associativity Right associativity Left associativity: In an expression if two or more operators having same priority are evaluated from left to right then the operators are called left to right associative operator, denoted as L->R Right associativity: In an expression if two or more operators having same priority are evaluated from left to right then the operators are called right to left associative operator, denoted as R->L BODMAS Rule can be used to solve the expressions, where B: Brackets O: Operators D: Division M: Multiplication A: Addition S: Subtraction School of Engineering and Technology, Sapthagiri NPS University 56 Problem Solving Using C The Precedence (Hierarchy) of Operator Operators in Order of Precedence Operator Category Associativity (Highest to Lowest) Innermost (), [], {} Left to Right(L->R) brackets/Array elemen ts Reference Unary Operators ++, --, sizeof(), ~, +, - Right to Left(R->L) Member Access -> or * L->R Arithmetic Operators *, /, % L->R Arithmetic Operators -, + L->R Shift Operators L->R Relational Operators = L->R Equality Operators ==, != L->R Bitwise AND & L->R Bitwise XOR ^ L->R Bitwise OR | L->R Logical AND && L->R Logical OR || L->R Conditional Operator ?: R->L Assignment Operator =, +=, -=,*=, /=, %= R->L Comma Operator , L->R Modes of Arithmetic Expressions An expression is a sequence of operands and operators that reduces to a single value. Expressions can be simpler or complex. An operator is a syntactical token that requires an action to be taken. An operand is an object on which an operation is performed. School of Engineering and Technology, Sapthagiri NPS University 57 Problem Solving Using C Arithmetic expressions are divided into 3 categories: 1. Integer Expressions 2. Floating Point Expressions 3. Mixed mode Expressions 1. Integer Expressions ⮚ If all the operands in an expression are integers then the expression is called Integer Expression. ⮚ The result of integer expression is always integer. Ex: 4/2=2 2. Floating Point Expressions If all the operands in an expression are float numbers then the expression is called floating point Expression. ⮚ The result of floating-point expression is always float Ex: 4.0/3.0=1.3333 3. Mixed Mode Expressions ⮚ An expression that has operands of different types is called Mixed Mode Expression. Ex: 4.0/2 i.e float/int Evaluation of Expressions involving all the operators The rules to be followed while evaluating any expressions are shown below. Replace the variables if any by their values. Evaluate the expressions inside the parentheses Rewrite the expressions with increment or decrement operator as shown below: a) Place the pre-increment or pre-decrement expressions before the expression being evaluated and replace each of them with corresponding variable. b) Place the post-increment or post- decrement expressions after the expression being evaluated and replace each of them with School of Engineering and Technology, Sapthagiri NPS University 58 Problem Solving Using C corresponding values. Evaluate each of the expression based on precedence and associativity. 1.20 Type Conversion The process of converting the data from one data type to another data type is called Type conversion. Type conversion is of two types (i) Implicit type conversion (ii) Explicit type conversion i). Implicit Conversion C can evaluate the expression if and only if the data types of two operands are same. If operands are of different type, it is not possible to evaluate expression. In such situation to ensure that both operands are of same type, C compiler converts data from lower rank to higher rank automatically. This process of converting data from lower rank to higher rank is called as Implicit type conversion (ITC). For example, If one operand type is same as other operand type, no conversion takes place and type of result remains same as the operands i.e int + int = int, float + float = float etc. If one operand type is int and other operand type is float, the operand with type int is promoted to float. School of Engineering and Technology, Sapthagiri NPS University 59 Problem Solving Using C Promotion of hierarchy is as follows: Higher rank datatype double float unsigned long int long int unsigned int int Short int char Lower rank datatype Examples: i. 5+3=8 int + int = int ii. 5 + 3.5 = 8.5 int + float = float ii) Explicit type conversion If the operands are of same datatype no conversion takes place by compiler. Sometimes the type conversion is required to get desired results. In such situation programmer himself has to convert the data from one type to another. This forcible conversion from one datatype to another is called as explicit type conversion (ETC). Syntax: Example: (int) 9.93=9 The data conversion from higher data type to lower data type is possible using explicit type conversion. The following example gives the explicit type conversion. School of Engineering and Technology, Sapthagiri NPS University 60 Problem Solving Using C “What is type casting? Explain with example?” Definition: C allows programmers to perform typecasting by placing the type name in parentheses and placing this in front of the value. x=(int) 7.5 7.5 is converted to integer by truncation a=(int)21.3 / (int) 4.5 Evaluated as 21/4 and the result would be 5. b=(double) sum/n Division is done in floating point mode y=(int)(a+b) The result a + b is converted to integer z=(int)a +b a is converted to integer and then added to b main() { float a; a = (float)5 / 3; } Gives result as 1.666666. This is because the integer 5 is converted to floating point value before division and the operation between float and integer results in float. School of Engineering and Technology, Sapthagiri NPS University 61 Problem Solving Using C Difference between ITC and ETC ITC ETC 1. It is performed by Compiler. 1. It is performed by programmer. 2. ITC performs only lower to 2. ETC perform both lower to higher and higher data conversion higher to lower. 3. ITC is performing when 3. ETC is performed when both the both the operands are of different operands are of same type. type. 4. Example 4. Example float 2+3.4=5.4 a=10.6 (int)a; Ans:10 1.21 Library functions in C Library functions in C are also inbuilt functions in C language. These inbuilt functions are located in some common location, and it is known as the library. All the functions are used to execute a particular operation. These library functions are generally preferred to obtain the predefined output. C Standard library functions or simply C Library functions are inbuilt functions in C programming. The prototype and data definitions of these functions are present in their respective header files. To use these functions, we need to include the header file in our program. For example, If you want to use the printf() function, the header file should be included. #include int main() { printf("Catch me if you can."); } If you try to use printf() without including the stdio.h header file, you will get an error. School of Engineering and Technology, Sapthagiri NPS University 62 Problem Solving Using C Example: Square root using sqrt() function Suppose, you want to find the square root of a number. To compute the square root of a number, you can use the sqrt() library function. The function is defined in the math.h header file. #include #include int main() { float num, root; printf("Enter a number: "); scanf("%f", &num); // Computes the square root of num and stores in root. root = sqrt(num); printf("Square root of %.2f = %.2f", num, root); return 0; //program to illustrate Pow() function #include #include // Driver code int main() { double base, power, result; base = 10.0; power = 2.0; // Calculate the result result = pow(base, power); printf("%.1lf^%.1lf = %.2lf", base, power, result); return 0; } Output 10.0^2.0 = 100.00 // program to illustrate log() functions #include #include // Driver code int main() { School of Engineering and Technology, Sapthagiri NPS University 63 Problem Solving Using C double num = 5.6, result; result = log(num); printf("log(%.1f) = %.2f", num, result); return 0; } Output log(5.6) = 1.72 S No. Header Files Description 1 It checks the value of an expression that we expect to be true under normal circumstances. If the expression is a nonzero value, the assert macro does nothing. 2 A set of functions for manipulating complex numbers. 3 Defines macro constants specifying the implementation-specific properties of the floating-point library. 4 These limits specify that a variable cannot store any value beyond these limits, for example- An unsigned character can store up to a maximum value of 255. 5 The math.h header defines various mathematical functions and one macro. All the Functions in this library take double as an argument and return double as the result. 6 The stdio.h header defines three variable types, several macros, and various function for performing input and output. 7 Defines date and time handling functions. 8 Strings are defined as an array of characters. The difference between a character array and a string is that a string is terminated with a special character ‘\0’. School of Engineering and Technology, Sapthagiri NPS University 64 Problem Solving Using C Course: Problem Solving Techniques using C Course Code: 24BTPHY104 Module 2 2. MANAGING INPUT AND OUTPUT OPERATIONS Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data. We have two methods of providing data to the program variables. One method is to assign values to variables through the assignment statements like x=5, a=0 and so on. Another method is to use the input function scanf, which can read data from a keyboard. We have used both the methods in programs. For outputting results, we have used extensively the function printf, which sends results out to a terminal. Input – Output functions: The program takes some I/P- data, process it and gives the O/P. We have two methods for providing data to the program i) Assigning the data to the variables in a program. ii) By using I/P-O/P statements. C language has 2 types of I/O statements; all these operations are carried out through function calls. 1. Unformatted I/O statements 2. Formatted I/O statements 2.1 Unformatted I/O statements getchar( ):- It reads single character from standard input device. This function donot require any arguments. Syntax: - char variable_name = getchar( ); Ex: - char x; x = getchar( ); putchar (): - This function is used to display one character at a time on the standard output School of Engineering and Technology, Sapthagiri NPS University 65 Problem Solving Using C device. Syntax:- putchar(char_variable); Ex:- char x; putchar(x); program: main( ) { char ch; printf(―enter a char‖); ch = getchar( ); printf(―entered char is‖); putchar(ch); } Output: enter a char a entered char is a getc() :- This function is used to accept single character from the file. Syntax: char variable_name = getc(); Ex:- char c; c = getc(); putc():- This function is used to display single character. Syntax :- putc(char variable_name); Ex:- char c; putc(c); These functions are used in file processing. gets( ):- This function is used to read group of characters(string) from the standard I/P device. Syntax:- gets(character array variable); Ex:- gets(s); puts( ):- This function is used to display string to the standard O/P device. Syntax:- puts(character array variables); Ex:- puts(s); School of Engineering and Technology, Sapthagiri NPS University 66 Problem Solving Using C program: main() { char s; puts(―enter name‖); gets(s); puts(―print name‖); puts(s); } Output: enter name ramu print name ramu getch(): - This function reads a single character directly from the keyboard without displaying on the screen. This function is used at the end of the program for displaying the output (without pressing (Alt-F5). Syntax: char variable_name = getch(); Ex: - char c c = getch(); getche(): - This function reads a single character from the keyboard and echoes(displays) it to the current text window. Syntax:- char variable_name = getche(); Ex:- char c c = getche(); program: main() { char ch, c; printf(―enter char‖); ch = getch(); printf(―%c‖, ch); printf(―enter char‖); c = getche(); printf(―%c‖,c); School of Engineering and Technology, Sapthagiri NPS University 67 Problem Solving Using C } Output: - enter character a enter character b b Character test functions: - Function Test isalnum(c) -Is c an alphanumeric character? isalpha(c) -Is c an alphabetic character isdigit(c)- Is c a digit? islower(c) -Is c a lower-case letter? isprint(c) -Is c a character? ispunct(c) -Is c a punctuation mark? isspace(c) -Is c a white space character? isupper(c)- Is c an upper-case letter? tolower(c) -Convert ch to lower case toupper(c) -Convert ch to upper case program: main() { char a; printf(―enter char‖); a = getchar(); if (isupper(a)) { x= tolower(a); putchar(x); } else putchar(toupper(a)); } Output: - enter char A a 2.2 Formatted I/O Functions Formatted I/O refers to input and output that has been arranged in a particular format. School of Engineering and Technology, Sapthagiri NPS University 68 Problem Solving Using C Formatted I/P functions scanf( ) , fscanf() Formatted O/P functions--- printf() , fprintf() scanf( ) : -scanf() function is used to read information from the standard I/P device. Syntax: - scanf(―controlstring‖, &variable_name); Control string (also known as format string) represents the type of data that the user is going to accept and gives the address of variable. (char-%c , int-%d , float - %f , double- %lf).Control string and variables are separated by commas. Control string and the variables going to I/P should match with each other. Ex: - int n; scanf(―%d‖,&n); Inputting Integer Numbers: The field specification for reading an integer number is: %w d The percentage sign (%) indicates that a conversion specification follows. w is an integer number that specifies the field width of the number to be read and d known as data type character indicates that the number to be read is in integer mode. Ex: - scanf(―%2d,%5d‖,&a&b); The following data are entered at the console: 50 31426 Here the value 50 is assigned to a and 31426 to b Inputting Real Numbers: The field width of real numbers is not to be specified unlike integers. Therefore, scanf reads real numbers using the simple specification %f. School of Engineering and Technology, Sapthagiri NPS University 69 Problem Solving Using C Ex: scanf(―%f %f‖,&x,&y); Suppose the following data are entered as input: 23.45 34.5 The value 23.45 is assigned to x and 34.5 is assigned to y. Inputting character strings: The field specification for reading character strings is %ws or %wc %c may be used to read a single character. Ex: scanf(―%s‖,name1); Suppose the following data is entered as input: Griet Griet is assigned to name1. Formatted Output: printf( ): This function is used to output any combination of data. The outputs are produced in such a way that they are understandable and are in an easy to use form. It is necessary for the programmer to give clarity of the output produced by his program. Syntax:- printf(―control string‖, var1,var2……); Control string consists of 3 types of items 1. Characters that will be printed on the screen as they appear. 2. Format specifications that define the O/P format for display of each item. 3. Escape sequence chars such as \n, \t and \b…... The control string indicates how many arguments follow and what their types are. The var1, var2 etc... are variables whose values are formatted and printed according to the specifications of the control string. School of Engineering and Technology, Sapthagiri NPS University 70 Problem Solving Using C The arguments should match in number, order and type with the format specifications. School of Engineering and Technology, Sapthagiri NPS University 71 Problem Solving Using C Decision making, Branching and Looping 2.3 Decision Making Statements If and Switch Statements We have a number of situations where we may have to change the order of execution of statements based on certain conditions or repeat a group of statements until certain specified conditions are met. 2.3.1The if Statement This is basically a “one-way” decision statement. This is used when we have only one School of Engineering and Technology, Sapthagiri NPS University 72 Problem Solving Using C alternative. The syntax is shown below: if(expression) { statement1; } Firstly, the expression is evaluated to true or false. If the expression is evaluated to true, then statement1 is executed. If the expression is evaluated to false, then statement1 is skipped. The flow diagram is shown below: Example 1: Program to illustrate the use of if statement #include main() { int a,b; printf(“Enter two numbers”); scanf(“%d%d”,&a,&b): if a>b printf(“ a is greater”); if b>a printf(“b is greater”); } Example 2: Program to illustrate the use of if statement. #includevoid main() { int n; printf(“Enter any non-zero integer: \n”); scanf(“%d”, &n) if(n>0) printf(“Number is positive number” );if(n0) printf(“Number is positive number”); else School of Engineering and Technology, Sapthagiri NPS University 74 Problem Solving Using C } printf(“Num ber is negative number”) School of Engineering and Technology, Sapthagiri NPS University 75 Problem Solving Using C Output: Enter any non-zero integer:7 Number is positive number Example 2: Program to illustrate if else statement to find greatest of two numbers. #include main() { int a,b; printf(“Enter two numbers”); scanf(“%d%d”,&a,&b): if a>b printf(“a is greater”) else printf(“b is greater”); } Example 3: program to check whether an integer is odd or even #include int main() { int number; printf("Enter an integer: "); scanf("%d", &number); // True if the remainder is 0 if (number%2 == 0) { printf("%d is an even integer.",number); } else { printf("%d is an odd integer.",number); } return 0; } Output: Enter an integer: 7 7 is an odd integer. School of Engineering and Technology, Sapthagiri NPS University 76 Problem Solving Using C Example 4: Program to check vowel or consonant #include int main() { char c; int lowercase_vowel, uppercase_vowel; printf("Enter an alphabet: "); scanf("%c", &c); // evaluates to 1 if variable c is a lowercase vowel lowercase_vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); // evaluates to 1 if variable c is a uppercase vowel uppercase_vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'); // evaluates to 1 (true) if c is a vowel if (lowercase_vowel || uppercase_vowel) printf("%c is a vowel.", c); else printf("%c is a consonant.", c); return 0; } OUTPUT: Enter an alphabet: G G is a consonant. Example 5: Program to Find the Largest Number Among Three Numbers #include int main() { double n1, n2, n3; printf("Enter three different numbers: "); scanf("%lf %lf %lf", &n1, &n2, &n3); // if n1 is greater than both n2 and n3, n1 is the largest if (n1 >= n2 && n1 >= n3)