Unit 2 Notes PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document is a collection of notes from a unit on programming concepts, including algorithms, flowcharts, and C programming examples. It includes instructions on how to write algorithms and solve problems, and features exercises involving basic concepts in areas of C programming.
Full Transcript
Unit 2: Syllabus Steps for Problem Solving: Flowcharts, Algorithms; Examples of flow charts and algorithms- Largest of three numbers, Reversing the digits of an integer, GCD of two integers, Generating prime numbers, Computing n Fibonacci numbers. Introduction to C Programmi...
Unit 2: Syllabus Steps for Problem Solving: Flowcharts, Algorithms; Examples of flow charts and algorithms- Largest of three numbers, Reversing the digits of an integer, GCD of two integers, Generating prime numbers, Computing n Fibonacci numbers. Introduction to C Programming: Features of C Structure of a C Program with Examples; Creating and Executing a C Program; Compilation process in C. C Programming Basic Concepts: C Character Set; C tokens- keywords, identifiers, constants, and variables; Data types; Declaration & initialization of variables; Symbolic constants. Planning Computer Program Programs must be planned before they are written Algorithm Flowchart Purpose of Program Planning To write a correct program, a programmer must write each and every instruction in the correct sequence Logic (instruction sequence) of a program can be very complex Hence, programs must be planned before they are written to ensure program instructions are: ◦ Appropriate for the problem ◦ In the correct sequence In order to solve a problem by the computer, one has to pass though certain stages or steps. They are: 1. Understanding the problem 2. Analysing the problem 3. Developing the solution 4. Coding and implementation. Algorithm Refers to the logic of a program and a step-by-step description of how to arrive at the solution of a given problem In order to qualify as an algorithm, a sequence of instructions must have following characteristics: Each and every instruction should be precise and unambiguous Each instruction should be such that it can be performed in a finite time One or more instructions should not be repeated infinitely. This ensures that the algorithm will ultimately terminate After performing the instructions, that is after the algorithm terminates, the desired results must be obtained Advantages of an algorithm 1. It is a step-by-step representation of a solution to a given problem ,which is very easy to understand 2. It has got a definite procedure. 3. It is independent of programming language. 4. It is easy to debug as every step got its own logical sequence. Disadvantages of an algorithm 1. It is time consuming process. 2. It is difficult to show branch and looping in the algorithm. Type1(Input and Output) Example 1: Write an algorithm to find area of a rectangle. Step 1: Start Step 2: Take length and breadth and store them as L and B? Step 3: Multiply by L and B and store it in area Step 4: Print area Step 5: Stop Type 2 (based on conditional statements) Example 2: Write an algorithm to check whether he is eligible to vote? (More than or equal to 18 years old). Step 1: Start Step 2: Take age of the user and store it in age Step 3: Check age value, if age >= 18 then go to step 4 else step 5 Step 4: Print “Eligible to vote” and go to step 6 Step 5: Print “Not eligible to vote” Step 6: Stop Type 3 (Based on Looping statements) Example 3: Write an algorithm to print all natural numbers up to n‟. Step 1: Start Step 2: Take any number and store it in n. Step 3: Store 1 in I Step 4: Check I value, if I=18) printf("Eligible for voting\n"); else printf("Not eligible\n"); } Example 3: Print all natural numbers up to n C Program #include void main() { int i, n; printf("Enter value for n: \n"); scanf("%d", &n); i=1; while(i B then go to step 6 Step 4: Compare B and C if C > B then go to step 8 Step 5: print “B is largest” go to step 9 Step 6: Compare A and C if C > A then go to step 8 Step 7: Print “A is largest” go to step 9 Step 8: Print “C is largest” Step 9: Stop Flowchart: Program: #include void main() { int a, b, c; printf("Enter values for a, b and c :\n"); scanf("%d%d%d",&a,&b,&c); if (a>b) { if (a>c) printf("%d is the largest",a); else printf("%d is the largest",b); } else { if (b>c) printf("%d is the largest",b); else printf("%d is the largest",c); } } 2) Reversing the digits of an Integer Algorithm: Step 1: Start Step 2: Input number Step 3: Isolate the last digit in number Step 4: Append last Digit to reverse Step 5: Remove last digit from number Step 6: Repeat step 3 to step 5 until number is reduced to zero and reverse is completed. Step 7: End Flowchart: Program: #include void main() { int n, reverse=0, rem; printf("Enter a number: "); scanf("%d", &n); while(n!=0) { rem=n%10; reverse=reverse*10+rem; n=n/10; } printf("Reversed Number: %d", reverse); } 3) GCD of two Integers Algorithm Step 1: Start Step 2: Declare a variable result and initialize it with the minimum of a and b. Step 3: Run a while loop till the result > 0. Step 4: Check if both a and b are divisible by result by using the modulo operator (%), and break the loop. Step 5: Otherwise, decrement result by 1 in each iteration until a common divisor is found or the result becomes 0. Step 6: After the while loop, the result variable will hold the gcd of two numbers. Return the value of the result. Step 7: End Flowchart: Program: #include int main() { int a, b; printf("Enter two numbers: \n"); scanf("%d%d", &a, &b); int result = ((a < b) ? a : b); while (result > 0) { if (a % result == 0 && b % result == 0) { break; } result = result - 1; } printf("GCD of %d and %d is %d ", a, b, result); } 4) Generating prime numbers Algorithm: Step 1: Start Step 2: Input value for N Step 3: Iterate I from 2 to N Step 4: Iterate J from 2 to sqrt(N) and check if the number(I) is divisible by any of the values(J) other than itself. Step 5: If it is not divisible by any number, it means the number is prime, print the number. Step 6: Stop Flowchart: Program: #include #include void main(){ int i, num, n, flag; printf("Enter the range: "); scanf("%d",&n); printf("The prime numbers in between the range 1 to %d:\n",n); for(num=2; num 65, B-> 66.......Z-> 90 a-> 97, b->98, z->122 Tokens A token in C can be defined as the smallest individual element of the C programming language that is meaningful to the compiler. It is the basic component of a C program. 1) Keywords The keywords are pre-defined or reserved words in a programming language. Each keyword is meant to perform a specific function in a program. Since keywords are referred names for a compiler, they can’t be used as variable names because by doing so, we are trying to assign a new meaning to the keyword which is not allowed. You cannot redefine keywords. However, you can specify the text to be substituted for keywords before compilation by using C preprocessor directives. C language supports 32 keywords which are given below: 2)Identifiers Identifiers are used as the general terminology for the naming of variables, functions, and arrays. These are user-defined names consisting of an arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Once declared, you can use the identifier in later program statements to refer to the associated value. A special identifier called a statement label can be used in goto statements. Rules for Naming Identifiers Certain rules should be followed while naming c identifiers which are as follows: 1. They must begin with a letter or underscore(_). 2. They must consist of only letters, digits, or underscore. No other special character is allowed. 3. It should not be a keyword. 4. It must not contain white space. 5. It should be up to 31 characters long as only the first 31 characters are significant. Note: Identifiers are case-sensitive so names like variable and Variable will be treated as different. 3)Constants The constants refer to the variables with fixed values. They are like normal variables but with the difference that their values can not be modified in the program once they are defined. Constants may belong to any of the data types. Examples of Constants in C const int a = 20; const char ch = 'A'; Variable A variable in C is a memory location with some name that helps store some form of data and retrieves it when required. We can store different types of data in the variable and reuse the same variable for storing some other data any number of times. Variable Syntax: data_type variable_name = value; Here, data_type: Type of data that a variable can store. variable_name: Name of the variable given by the user. value: value assigned to the variable by the user. Example: int a = 10; char ch = 'A'; float n = 14.101; Data Types Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning as well as its characteristics. Note: The long, short, signed and unsigned are datatype modifier that can be used with some primitive data types to change the size or length of the datatype. Integer Data Type The integer datatype in C is used to store the integer numbers(any number including positive, negative and zero without decimal part). Octal values, hexadecimal values, and decimal values can be stored in int data type in C. Range: -2,147,483,648 to 2,147,483,647 Size: 4 bytes Format Specifier: %d Syntax of Integer We use int keyword to declare the integer variable: int var_name = 123; Character Data Type Character data type allows its variable to store only a single character. The size of the character is 1 byte. It is the most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers. Range: (-128 to 127) or (0 to 255) Size: 1 byte Format Specifier: %c Syntax of char The char keyword is used to declare the variable of character type: char var_name = 'A'; Float Data Type In C programming float data type is used to store floating-point values. Float in C is used to store decimal and exponential values. It is used to store decimal numbers (numbers with floating point values) with single precision. Range: 1.2E-38 to 3.4E+38 Size: 4 bytes Format Specifier: %f Syntax of float The float keyword is used to declare the variable as a floating point: float var_name = 1.11; Double Data Type A Double data type in C is used to store decimal numbers (numbers with floating point values) with double precision. It is used to define numeric values which hold numbers with decimal values in C. The double data type is basically a precision sort of data type that is capable of holding 64 bits of decimal numbers or floating points. Since double has more precision as compared to that float then it is much more obvious that it occupies twice the memory occupied by the floating-point type. It can easily accommodate about 16 to 17 digits after or before a decimal point. Range: 1.7E-308 to 1.7E+308 Size: 8 bytes Format Specifier: %lf Syntax of Double The variable can be declared as double precision floating point using the double keyword: double var_name = 5.11111111133333; Variable Declaration Variable declaration in C tells the compiler about the existence of the variable with the given name and data type.When the variable is declared, an entry in symbol table is created and memory will be allocated at the time of initialization of the variable. Ex: int a; float b; double c; char d; Variable Initialization Initialization of a variable is the process where the user assigns some meaningful value to the variable when creating the variable. Ex: //Declaration int a; float b; double c; char d; //initialization a=1; b=2.1; c=2.22222; d='c'; //Declaration and Initialization int a=1; float b=2.1; double c=2.22222; char d='c'; Symbolic constants Symbolic Constant is a name that substitutes for a sequence of characters or a numeric constant, a character constant or a string constant. When program is compiled each occurrence of a symbolic constant is replaced by its corresponding character sequence. The C language's "#define" command is used to declare symbolic constants. Syntax #define name text Example: #define MAX 50 #define TRUE 1 #define FALSE 0 #define SIZE 15 #define PI 3.14