Computer Hardware Key board Mouse Input Devices Input
Computer -- Hardware Key board Mouse Input Devices Input Storage Area Program Storage Area Working Storage Area Output Storage Area Primary or Main Memory (RAM) Register 1 Register 2 …… …… Register N Arithmetic and Logic Unit Micro Processor Secondary Storage Devices Monitor Printer Output Devices
Algorithm: Step by step procedure of solving a particular problem. Pseudo code: Artificial informal language used to develop algorithms. Flow chart: Graphical representation of an algorithm. Algorithm to find whether a number even or odd: Step 1: Begin Step 1: START Step 2: Take a number Step 2: Read num Step 3: if the number is divisible by 2 then Step 3: if(num%2=0) then print that number is even print num is even otherwise print that number is odd otherwise print num is odd Step 4: End Step 4: STOP (Algorithm in natural language) (Algorithm by using pseudo code) #include<stdio. h> #include<conio. h> main() { int num; printf(“Enter any number”); scanf(“%d”, &num); if(num%2==0) printf(“%d is even”, num); else printf(%d is odd”, num); } (Program in C language) start Flow chart: Yes read num If num%2=0 No print num is odd print num is even stop
Flow chart symbols Oval Terminal Parallegram Input/output Rectangle Process Document Hard copy Diamond Decision Circle Connector Double sided Rectangle Sub program Hexagon Iteration Trapezoid Manual Operation Cylinder Magnetic Disk Storage
Machine Language – Assembly Language – High-Level Language 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8 9 1 0 0000 01011110 00001100 111011111000 10101101 01100010 11101111 00000010 11110100 10101101 00000011 10100010 11101111 00000010 01111110100 11111000 10101110 00000110 10100010 11101111 00000010 010100000100 11000010110 10111110 11011111011 11011111 10101101 11000101 11111011 11010100 000000000010 00000001011 00000010010 00000010101 00000010111 00000011110 00000100001 00000100100 00000101011 00000110001 00000110100 00000111011 00000111101 #include<stdio. h> int main(void) { int n 1, n 2, product; printf(“Enter two numbers : “); scanf(“%d %d”, &n 1, &n 2); product = n 1 * n 2; printf(“%d”, product); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 entry main, ^m<r 2> sub 12 #12, sp jsb C$MAIN_ARGS moveb $CHAR_STRING_CON pusha 1 calls mull 3 pusha calls clrl ret -8(fp) (r 2) #2, SCANF -12(fp) 3(r 2) #2, SCANF -8(fp), -12(fp), 6(fp) #2, PRINTF r 0 The only language the computer can understand is machine language (binary language). A high level language is an English like language where one instruction typically translates into a series of machinelanguage instructions. A low level language corresponds closely to machine code so that a single low-level language instruction translates to a single machine language instruction.
Structure of C program /*Program to find area and perimeter of Circle */ #include<stdio. h> #define PI 3. 1415 float radius; float area(); float perimeter(); int main() { float a, p; printf(“Enter radius : “); scanf(“%f”, &radius); a = area(); p = perimeter(); printf(“Area of Circle : %f”, a); printf(“Perimeter : %f”, p); } float area() { return (PI * radius); } float perimeter() { return (2 * PI * radius); } Documentation Section Linkage Section Definition Section Global Declaration Section Main Function Section Local Declaration Part Executable Code Part Sub Program Section Function 1() Function 2() …………… Function. N()
Program Development Steps 1)Statement of Problem a) Working with existing system and using proper questionnaire, the problem should be explained clearly. b) What inputs are available, outputs are required and what is needed for creating workable solution should be understood clearly. 2)Analysis a) The method of solutions to solve the problem can be identified. b) We also judge that which method gives best results among different methods of solution. 3)Designing a) Algorithms and flow charts will be prepared. b) Keep focus on data, architecture, user interfaces and program components. 4)Implementation The algorithms and flow charts developed in the previous steps are converted into actual programs in the high level languages like C. 4. a)Compilation Translate the program into machine code. This process is called as Compilation. Syntactic errors are found quickly at the time of compiling the program. These errors occur due to the usage of wrong syntaxes for the statements. Eg: x=a*y+b There is a syntax error in this statement, since, each and every statement in C language ends with a semicolon (; ). 4. b)Execution The next step is Program execution. In this phase, we may encounter two types of errors. Runtime Errors: these errors occur during the execution of the program and terminates the program abnormally. Logical Errors: these errors occur due to incorrect usage of the instructions in the program. These errors are neither detected during compilation or execution nor cause any stoppage to the program execution but produces incorrect ouz
Executing a C program Text Editor #include<stdio. h> int main() { ……. prog 1. c compiles C-compiler Yes Syntax Errors? 010110 100 ……………. 01011 101 No Object machine code Linker 00101010 …………. 0101 prog 1. obj adds Executable machine code of library file C-Runtime prog 1. exe Executes Feeds Input Runtime or Logic Errors ? Output Yes Translators are system software used to convert high-level language program into machine-language code. Compiler : Coverts the entire source program at a time into object code file, and saves it in secondary storage permanently. The same object machine code file will be executed several times, whenever needed. Interpreter : Each statement of source program is translated into machine code and executed immediately. Translation and execution of each and every statement is repeated till the end of the program. No object code is saved. Translation is repeated for every execution of the source program.
Character Set of C-Language Alphabets : A-Z and a-z Digits : 0 -9 Special Symbols : ~ ! @ # $ % ^ & ( ) _ - + = | { } [ ] : ; “ ‘ <>, . ? / White Spaces : space , Horizontal tab, Vertical tab, New Line Form Feed. C-Language Keywords(C 99) auto break case char const continue default do _Bool inline double else enum extern float for goto if _Imaginary int long register return short signed sizeof static restrict struct switch typedef union unsigned void volatile while _Complex
C-Tokens : The smallest individual units of a C- program are called Tokens. Key words, Identifiers, Constants, Operators, Delimiters. Key words : have a predefined meaning and these meanings cannot be changed. All keywords must be written in small letters (except additional c 99 keywords). Identifiers : names of variables, functions, structures, unions, macros, labels, arrays etc. , Rules for define identifiers : a) First character must be alphabetic character or under score b) Second character onwards alphabetic character of digit or under score. c) First 63 characters of an identifier are significant. d) Cannot duplicate a key word. e) May not have a space or any other special symbol except under score. f) C – language is Case-sensitive.
C-Tokens Constants : fixed values that do not change during execution of a program. Boolean constants : 0 ( false) and 1 (true) Character constants : only one character enclosed between two single quotes ( except escape characters ). wide character type - wchar_t - for Unicode characters. Integer constants : +123, -3454 , 0235 (octal value), 0 x 43 d 98 ( hexa - decimal value) 54764 U, 124356578 L, 124567856 UL Float constants : 0. 2 , 876. 345, . 345623 , 23. 4 E+8, 47. 45 e+6 String Constants : “Hello world” , “Have a nice day!” Complex Constants : real part + imaginary part * I ex : 12. 3 + 3. 45 * I Operators : a symbol, which indicates an operation to be performed. Operators are used to manipulate data in program. Delimiters : Language Pattern of c-language uses special kind of symbols : (colon, used for labels) ; (semicolon terminates statement ) ( ) parameter list [ ] ( array declaration and subscript ), { } ( block statement ) # ( hash for preprocessor directive ) , (comma variable separator )
Data Types ( pre defined ) Type Typical Size in Bits char 8 unsigned char 8 int 16 or 32 unsigned int 16 or 32 short int 16 unsigned short int 16 long int 32 long int 64 signed long int 32 unsigned long int 64 float 32 double 64 long double 80 void -- Minimal Range – 127 to 127 0 to 255 – 127 to 127 – 32, 767 to 32, 767 0 to 65, 535 Same as int – 32, 767 to 32, 767 0 to 65, 535 Same as short int – 2, 147, 483, 647 to 2, 147, 483, 647 –(263) to 263 – 1 (Added by C 99) Same as long int 0 to 4, 294, 967, 295 264 – 1 (Added by C 99) 3. 4 e-38 to 3. 4 e+38 1. 7 e-308 to 1. 7 e+308 3. 4 e-4932 to 1. 1 e+4932 data type that not return any value
Conversion Specifiers Code %a %s %c %d %f %e %g %u %o %x %i %p %n %hd %lf %% Format Hexa decimal output in the form of 0 xh. hhhhp+d(C 99 only) String of characters (until null zero is reached ) Character Decimal integer Floating-point numbers Exponential notation floating-point numbers Use the shorter of %f or %e Unsigned integer Octal integer Hexadecimal integer Signed decimal integer Display a pointer The associated argument must be a pointer to integer, This sepecifier causes the number of characters written in to be stored in that integer. short integer long double Prints a percent sign (%)
Back Slash ( Escape Sequence) Characters Code b f n r t " ' \ v a ? N x. N Meaning Backspace Form feed New line Carriage return Horizontal tab Double quote Single quote Backslash Vertical tab Alert Question mark Octal constant (N is an octal constant) Hexadecimal constant (N is a hexadecimal constant)
Increment and Decrement Operators prefix increment (++a) postfix increment (a++) prefix decrement(- -a) postfix decrement (a- -) Executes all Prefix Operations Before evaluation of expression Executes all Postfix Operations /* prefix operators */ #include<stdio. h> int main() { int a = 7, b = 12, c; c = b * (++a) + 5 * (++a); printf(“ a = %d”, a); printf(“n b = %d”, b); printf(“n c = %d”, c); } Output: a=9 b = 12 c = 153 ( 12 * 9 + 5 * 9) After evaluation of expression and before leaving the statement /* prefix and postfix operators */ #include<stdio. h> int main() { int a = 7, b = 12, c; c = b * (a++) + 5 * (++a); printf(“ a = %d”, a); printf(“n b = %d”, b); printf(“n c = %d”, c); } Output: a=9 b = 12 c = 136 ( 12 * 8 + 5 * 8) /* postfix operators */ #include<stdio. h> int main() { int a = 7, b = 12, c; c = b * (a++) + 5 * (a++); printf(“ a = %d”, a); printf(“n b = %d”, b); printf(“n c = %d”, c); } Output: a=9 b = 12 c = 119 ( 12 * 7 + 5 * 7)
Bitwise Logical Operators & -- Bitwise AND A B A&B A|B A^B ~A | -- Bitwise OR 1 1 0 0 1 1 0 ^ -- Bitwise XOR 0 1 1 1 ~ -- Bitwise NOT 0 0 0 1 Bitwise AND Bitwise OR A (42) : 0000 00101010 B (15) : 00001111 -----------------& (10) : 00001010 ------------------ A (42) : 0000 00101010 B (15) : 00001111 -----------------| (47) : 0000 00101111 ------------------ Bitwise XOR Bitwise NOT A (42) : 0000 00101010 B (15) : 00001111 -----------------& (37) : 0000 00100101 ------------------ A (42) : 0000 00101010 -----------------~ (-43) : 1111 11010101 ------------------
BITWISE SHIFT OPERATORS Bitwise Right Shift ( >> ) (positive values) (negetive values) A (43) : 00000000 00101011 A (-44) : 1111 11010100 ---------------------------------------------------A >> 2 : 00001010 A << 2 : 0000 10101100 A >> 2 : 11110101 ---------------------------------------------------Note : Right shift operator fills the left vacant fields with ‘zeros’ for positive numbers, with ‘ones’ for negative numbers. Bitwise Left Shift ( << ) Opposite To Gravity TYPE CONVERSION 1. bool (forcible). . . (natural) Gravity 2. char Explicit Type Conversion (casting) (forcible) 3. short int 4. int 5. long int 6. long int . . . 7. float 8. double 9. long double (automatic) Implicit Type Conversion (automatic)
Precedence and Associativity of Operators Precdence Group (Highest to Lowest ) (param) subscript etc. , Unary operators Multiplicative Additive Bitwise shift Relational Equality Bitwise AND Bitwise exclusive OR Bitwise OR Logical AND Logical OR Conditional Assignment Comma Operators Associativity ( ) [ ] –>. - + ! ~ ++ – – (type) * & sizeof */% +– << >> < <= > >= = = != & ^ | && || ? : = += –= *= /= %= &= ^= |= <<= >>= , L R R L L R L R L R R L L R
simple if: Test Expression ? False Entry if-else: Entry True Statement-block True-block Statements False Test Expression ? False-block Statements Next statement /* check a citizen is eligible for voting */ #include<stdio. h> int main() { int age; printf(“Enter the age : ”); scanf(“%d”, &age); if(age >= 18) printf(“Eligible for voting…”); getch(); } /* print a number is even or odd */ #include<stdio. h> int main() { int number; printf(“Enter a number : “); scanf(“%d”, &number); if((number %2) == 0) printf(“%d is even number. ”, number); else printf(“%d is odd number. ”, number); }
/* check whether a year is leap year or not */ #include<stdio. h> int main() { int year; printf("Enter the year ? "); True scanf("%d", &year); if((year %100) == 0) { Test True if((year % 400) == 0) condition 2 printf("%d is leap year. ", year); ? else printf("%d is not leap year. ", year); Statement-1 } else { if((year % 4) == 0) printf("%d is leap year. ", year); else printf("%d is not leap year. ", year); } getch(); } nested if…else: Entry False Test condition 1 ? False Statement-3 Statement-2 Next statement
if…else…if : Entry Test condition 1 ? True Statement-1 False Test condition 2 ? True Statement-2 False Test condition. N ? True Statement-N Next statement /* program to print the grade of student */ #include<stdio. h> int main() { int marks; printf("Enter marks ? "); scanf("%d", &marks); if(marks >= 75) printf("Distinction"); else if(marks >= 60) printf("First class"); else if(marks >= 50) printf("Second class"); else if(marks >= 35) printf("Third class"); else printf("Failed"); }
switch statement : Entry switch expression ? value 1 value 2 value. N ……. . . associate statement Exit Next statement /* program to simulate a simple calculator */ #include<stdio. h> int main() { float a, b; char opr; printf("Enter number 1 operator number 2 : "); scanf("%f %c %f", &a, &opr, &b); switch(opr) default { case '+': printf("Sum : %f", (a + b)); associate break; statement case '-': printf("Difference : %f", (a - b)); break; case '*': printf("Product : %f", (a * b)); break; case '/': printf("Quotient : %f", (a / b)); break; default: printf("Invalid Operation!"); } }
Loop Statements while – (Entry controlled ) Entry Test Condition ? true do-while – (Exit controlled ) Entry False Body of The loop Following Statement /* sum of 1 to 10 numbers */ #include<stdio. h> int main() { int i = 1, sum = 0; while(i<=10){ sum = sum + i; i = i + 1; } printf(“Total : %d “, sum); } Body of The loop Test Condition ? True False Following Statement /* average of 5 numbers */ #include<stdio. h> int main() { int count = 1; float x, sum = 0; do { printf(“x = “); scanf(“%f”, &x); sum += x; ++ count; } while(count <= 5); printf(“Average = %f “, (sum/5)) }
for -- Statement Entry Initialization Statement False Following Statement Increment Statement Test Condition ? True Body of The loop /* check whether a number is prime or not */ #include<stdio. h> int main() { int n, i, factors = 0; printf("Enter a number : "); scanf("%d", &n); for(i = 1; i <= n; i++) { if((n % i)==0) ++factors; } if (factors == 2) printf("%d is prime number. ", n); else printf("%d is not prime number. ", n); }
Important Functions in math. h abs(x) ceil(x) floor(x) log(x) pow(x, y) sqrt(x) exp(x) sin(x) cos(x) tan(x) fmod(x, y) hypot(x, y) log 10(x) absolute value of integer x rounds up and returns the smallest integer greater than or equal to x rounds down and returns the largest integer less than or equal to x returns natural logarithm returns the value of xy returns square root of x returns natural anti logarithm returns sine value where x in radians returns cosine value where x in radians returns tangent values where x in radians calculate x modulo y, where x and y are double calculate hypotenuse of right angle where x, y are sides. returns logarithm base 10
- Slides: 24