Professional Documents
Culture Documents
Turbo C Lecture
Turbo C Lecture
C evolved from two previous programming languages, BCPL (Basic Combined Programming Language) and B. BCPL developed in 1967 by Martin Richard as a language for writing operating systems software and compilers for operating system. B, a descendant of BCPL, developed by Ken Thompson in 1970 at Bell Laboratories used to create early versions of the UNIX OS. C is a general-purpose, procedural programming language. It was first devised by Dennis Ritchie in the 1970s at AT & T bell Lab for the purpose of implementing the UNIX OS. It initially became widely known as the development language of this OS. Today, most operating systems are written in C and one of its major uses today is in programming embedded systems. It is also used to write programs such as powerful word processor, database and graphics applications. C over C++ C - a procedural language Support of numerical analysis and computer-based modelling in a wide range of engineering and other scientific disciplines, where the priority is to solve equations as quickly as possible C++ - an object-oriented language Provides interactive software Procedural languages are typically more appropriate than object-oriented languages for engg and scientific calculations because the resulting programs can make more efficient use of the relevant hardware resources C++ is C with added functionality and that around 90% of any C++ program is actually C
160101734.doc/Overview of C
Header File It contains definitions of functions and variables which can be incorporated into any C program by using the pre-processor #include statement. Standard header files are provided with each compiler, and cover a range of areas, string handling, mathematical, data conversion, printing and reading of variables. File Name conio.h ctype.h graphics.h math.h stdio.h stdlib.h string.h A Simple C program #include <conio.h>
#include <stdio.h> main() { printf("Hello World!"); getch(); }
/* defines the routines for standard input and output, such as printf, scanf, etc */ /* informs the computer as to where the program starts */ /* signifies the begin segment of the program */ /* this statement prints the word Hello World on the screen */ /* signify the end segment of the program */
Related Functions Direct console I/O functions Character-related functions Graphics-related functions Mathematical functions Standard I/O functions Miscellaneous functions String-related functions
Basic Output Statements Command printf() puts() putchar() Function Used to print the output to the screen and can be used with variables Used to print a whole sentence on the screen but cannot be used with variables Prints a single character on the screen
Controlling the Cursor position The following characters, placed after the \ character in a printf() or puts() statement, have the following effect. Code \b \n \r \t \<enter> \\ \ or \ Identifier A name that is used to reference variables, function, label and various other userdefined objects. It should be 1 to 32 characters First character must be a letter and subsequent characters being either letters, numbers or underscore(_) Composed of one-word Should not be a Turbo C keyword Meaning Backspace New line Carriage return Horizontal tab Line continuation Backslash(\) character Single or double quote
160101734.doc/Structure of C Program
AnnualSalary CtrPt
160101734.doc/Data Types
Variables (identifiers) need to be declared before you can use them in a program.
#include <stdio.h> int x,y; /* char let='A';
global variables declaration */
Basic Input Commands Command scanf() gets() getche() getch() Function Used to scan the keyboard for information Usually placed after printf() statements Used with integer, float and double data Reads a string of character entered at the keyboard Used with string data Reads a character from the keyboard The key pressed is echoed to the screen automatically Operates like getche() except that the character typed is not echoed to the screen
Format: scanf(var_for, &var_name); where: var_for - %d for int, %c for char, %f for float, %e for double var_name name of the variable (identifier) gets(string_var_name); where: string_var_name a variable used in the program which is of string type var_name=getche(); where: var_name the variable where the keypressed will be stored or getche(); /* this will cause the program to pause and wait until a key is pressed getch();
Sample Programs
160101734.doc/Data Types
main() { int num1,num2,sum; clrscr(); printf("Enter the first number:"); scanf("%d", &num1); printf("Enter the second number:"); scanf("%d", &num2); sum=num1+num2; printf("The sum of %d and %d is %d.", num1,num2,sum); }
main() { char sname[20]; clrscr(); printf("ENter your name:"); gets(sname); printf("\n\nHello %s. Good Day!", sname); }
/* Prog Desc : A program that introduces the use of getche() Programmer : Juan de la Cruz Date Created: 2012 */ #include <stdio.h> #include <conio.h> main() { char let; clrscr(); printf("Enter a letter:"); let=getche(); printf("\n\nThe letter you have entered is %c", let); }
/* Prog Desc
160101734.doc/Data Types
main() { char let; clrscr(); printf("Enter a letter:"); let=getche(); printf("\n\nThe letter you have entered is %c", let); getch(); }
ARITHMETIC OPERATORS Operation Addition Subtraction Multiplication Division Increment Decrement Modulus Operato r + * / ++ -%
Modulus Operator is used to get the remainder. Eg. 5%3=2 10 % 5 = 0 3 % 6 = 3 Precedence of the Arithmetic Operators: Highest Precedence /*% Lowest Precedence + Eg. 1. A = 2 * 5 + 5 * 3 + 4 * 10; A = 65; 2. B = 4 % 3 + 6 4 * 5; B = -13; Equation with Parentheses: 1. A = 2 * (5 + %) * (3 + 4) * 10; A = 1400; 2. B = 4 % (3 + 6 4) * 5; B = 20; Combined Operators Long Hand Notation Equiv. Combined Expression x = x + y; x += y; x = x - y; x -= y; x = x * y; x *= y; x = x / y; x /= y; x = x % y; x %= y; Eg. What are the values of num1 and num2 after executing the following statements? num1 = 3; num2 = 1; num1 -= num2; num2 += 2; Increment and Decrement Operators INCREMENT Pre-increment
160101734.doc/Data Types
++x
z = x + y; x = x + 1;
z = y + ++x; value and stores the means increments x, then adds to y the new x result in z
x = x + 1; z = x + y;
Exercises: 1. What is the value of x after the following statements are executed? x= 1; y = 5; x += y; x /= 2; 2. What are the values of x and y after executing the following statements? a. x = 1; y = x++; b. x = 1; y = ++x; c. x = 1; y = x++ * (x+1); Relational and Logical Operators Relational refers to the relationships values can have with one another. Logical the ways these relationships can be connected together using the rules of formal logic. The key to the concepts of relational and logical operators is the idea of true and false. In Turbo C, expressions that use relational or logical operators will return 0 for false and 1 for true. The Relational Operators Operator > >= < <= == != Meaning Greater than Greater than or equal to Less than Less than or equal to Equal to Not equal to
Example: Evaluate the following expression if TRUE or FALSE 1. A=5; B=3; --A > ++B 2. x=2; y=1; x -= y; y = ++x; x != y
160101734.doc/Data Types
The Logical Operators Operat or && || ! ^ Truth table P 0 0 1 1 Action AND OR NOT EOR Meaning Requires all conditions to evaluate as TRUE (non-zero) Will be executed if any ONE of the conditions is TRUE (non-zero) Negates a condition (changes from TRUE to FALSE and vice versa Will be executed if either condition is TRUE, but not if they are all TRUE. P && Q 0 0 0 1 P || Q 0 1 1 1 P^Q 0 1 1 0 !P 1 1 0 0 !Q 1 0 1 0
Q 0 1 0 1
Precedence of Relational and Logical Operators Highest ! < <= > >= == != ^ && ||
Lowest Example:
Evaluate the following expressions if TRUE or FALSE. 1. A=5; (A>0) && (A<10) 2. A=5; (A>0) || (A<10) 3. x=7; y=2; z=5 x -= ++y; y %= z; x > z || y <= x && !(y == z) ^ (x+y) != (z+2) Control Structure (Logic Structure) - controls the logical sequence in which computer program instructions are executed Three (3) Control Structures: 1. Sequence Control Structure - one program statement follows another in logical order - there are no decisions to make; no choices between YES or No 2. Selection Control Structure - represents choice - it offers two paths to follow when a decision must be made by a program Case Control Structure - offers more than a single yes-or-no decision - allows several alternatives 3. Iteration or Loop Control Structure - process may be repeated as long as a certain condition remains true. Control Statements: 1. Conditional/Decision Statements 2. Loop Statements
160101734.doc/Data Types
Conditional Statements a. ifelse statement - allows branching (decision making) depending upon the value or state of variables. Formats: a. Sample program:
if (condition) statement;
#include <stdio.h> main() { int magic=123, guess; printf(Enter your guess: ); scanf(%d, &guess); if (guess==magic) printf(**RIGHT!**); getch(); }
b.
Sample program:
#include <stdio.h> main() { int magic=123, guess; printf(Enter your guess: ); scanf(%d, &guess); if (guess==magic) { printf(**RIGHT!**); printf(\n%d is the magic number., guess); } getch(); }
c.
Sample program:
#include <stdio.h> main() { int magic=123, guess; printf(Enter your guess: ); scanf(%d, &guess); if (guess==magic) printf(**RIGHT!**); else printf(**WRONG!**); getch(); }
d.
if (condition1) Statement1; else if(condiiton2) Statement; else if (condition3) Statement; else Statement;
Sample program:
#include <stdio.h> main() { int magic=123, guess; printf(Enter your guess: ); scanf(%d, &guess); if (guess==magic) { printf(**RIGHT!**); printf(\n%d is the magic number., guess); } else if (guess>magic) printf(..Wrong..Too High!); else printf(..Wrong..Too Low!); getch(); }
Sample program:
#include <stdio.h> main() { int magic=123, guess; printf(Enter your guess: ); scanf(%d, &guess); if (guess!=magic) { if(guess>magic) printf(..too high..); else printf(..too low..); } else printf(Its correct!); getch(); }
b. switchcase statement - allows the program to choose among a series of actions based on the value of an expression. Format:
switch (variable) { case value1: program statement; program statement; break; case value2: program statement; program statement; break; default: program statement; break; }
Where: Value the value of the variable Default statements are to be executed if no matches are found. optional and if not present, no action takes place if all matches fail.
It is
when a match is found, the statement associated with that case is executed until the break is reached. Note: 1. the switch statement can only test for equality while the if statement can evaluate a relational or logical expression 2. in switch statement, you cannot use expressions or ranges 3. the variable is either an integer or character only 4. no two case constants in the same switch block can have identical values 5. the order of the case statement is unimportant
10
#include <stdio.h> #include <conio.h> main() { int num1,num2,total,menu; char operator; clrscr(); printf(Enter two whole numbers separated by a space --> ); scanf(%d %d, &num1,&num2); printf(\n\nSelect what operation to perform\n); printf(by pressing the corresponding number.\n); printf(\t\t1 - Addition\n); printf(\t\t2 - Subtraction\n); printf(\t\t3 - Multiplication\n); printf(\t\t4 - Division\n); printf(\t\t>> ); scanf(%d,&menu); switch(menu) { case 1:operator=+; total=num1+num2; break; case 2:operator=-; total=num1-num2;break; case 3:operator=*; total=num1*num2;break; case 4:operator=/; total=num1/num2; break; default:printf(\n\nInvalid choice!);exit();getch(); } printf(\n\nResult : ); printf(%d %c %d = %d, num1,operator,num2,total); getch(); }
2. using character
#include <stdio.h> #include <conio.h> main() { int num1,num2,total; char menu; clrscr(); printf(Enter two whole numbers separated by a space --> ); scanf(%d %d, &num1,&num2); printf(\n\nSelect what operation to perform\n); printf(by pressing the corresponding number.\n); printf(\t\t+ - Addition\n); printf(\t\t- - Subtraction\n); printf(\t\t* - Multiplication\n); printf(\t\t/ - Division\n); printf(\t\t>> ); menu=getche(); switch(menu) { case +:total=num1+num2; break; case -:total=num1-num2; break; case *:total=num1*num2; break; case /:total=num1/num2; break; default:printf(\n\nInvalid choice!);exit();getch(); } printf(\n\nResult : ); printf(%d %c %d = %d, num1,menu,num2,total); getch(); }
Loop Statements a. for loop (iteration) - an iteration statement that performs its own loop maintenance. Formats: a. Sample programs:
for (initialization; condition; increment) statement;
160101734.doc/Data Types
11
#include <stdio.h> #include <conio.h> main() { int i; clrscr(); for(i=0; i<10; i++) printf(i = %d \n, i); getch(); } #include <stdio.h> #include <conio.h> main() { int count; clrscr(); for(count=0; count<=10; count += 1) printf(%d, count); printf(\n); getch(); }
b.
Sample program:
#include <stdio.h> #include <conio.h> main() { int count; clrscr(); for(count=0; count<=10; count += 1) { printf(%d, count); printf(\n); } getch(); }
Note: 1. The three main parts of for statement a. the initialization statement is executed before the loop starts. This is used to initialize the loop control variable or any other variable needed within the loop b. the condition is a relational expression that determines when the loop will exit. This is used to limit the number of times the loop will execute. If the condition is TRUE the loop continues to execute. c. The increment is executed at the end of each traversal through the loop. It defines how the loop control variable will change each time the loop is repeated. 2. these three major sections must be separated by semicolons 3. the for loop continues to execute as long as the condition is true. Once the condition becomes false, program execution resumes on the statement following the for loop.
#include <stdio.h> #include <conio.h> main() { int x,y,z; Exercises: clrscr(); 1. Trace they=2; program x=2; z=3; and for(x=1; x<=6; x++) { printf(%d, y); y=y+1; 160101734.doc/Data Types } printf(\n%d,z); getch(); }
12
2. Write a program that will produce the following output. (hint: use two nested for loops) 1 22 333 4444 55555 b. while statement - executes a statement repeatedly as long as the controlling expression is true Format: The concept behind the WHILE loop can be thought
while (condition) { Statement1; Statement2; }
of like this:
WHILE this condition is true perform these statements END of WHILE loop
Note: 1. the loop iterates while the condition is true. When the condition becomes false, the program control passes to the line after the loop code. 2. as with the for loop, while loop checks the test condition at the top of the loop which means that the loop codes may not be executed at all. Sample program:
#include <stdio.h> #include <conio.h> main() { int loop=0; clrscr(); while(loop <= 10) { printf(%d, loop); loop++; } getch(); }
b. dowhile statement
160101734.doc/Data Types
13
- tests the loop-continuation condition after the loop body executes; therefore, the loop body always executes at least once. Format: The concept behind the DO..WHILE loop can be
do { Statement1; Statement2; } while (condition)
Note: The target statement(s) in the loop will be executed at least once. Then, if the condition is TRUE, the program will go back to the top of the loop (right after the do statement) and execute the target statements again. When the condition becomes FALSE, the program will no longer return to the top of the loop, instead will continue on to the next statement in the program. Sample program:
#include <stdio.h> #include <conio.h> main() { int loop=0; clrscr(); do { printf(%d, loop); loop++; } while(loop <= 10) getch(); }
2. Write a program using the nested while or do/while statement to produce the following output. 1 22 333 4444 55555
160101734.doc/Data Types
14