Sunteți pe pagina 1din 14

Overview of C

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 1970’s 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

The Structure of C Program


HEADER SECTION *Optional
• Contains name, short description, author of the program and date created

INCLUDE SECTION
• Contains #include statements – list of libraries

CONSTANTS AND TYPES SECTION *Optional


• Contains types and #define statements

GLOBAL VARIABLES SECTION *Optional


• Any global variables are declared here

FUNCTIONS SECTION *Optional


• User defined functions

MAIN PROGRAM SECTION


main()
{

30709916.doc/Overview of C 1
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 Related Functions


conio.h Direct console I/O functions
ctype.h Character-related functions
graphics.h Graphics-related functions
math.h Mathematical functions
stdio.h Standard I/O functions
stdlib.h Miscellaneous functions
string.h String-related functions

A Simple C program

#include <stdio.h> /* defines the routines for standard input


and output, such as printf, scanf, etc */

main() /* informs the computer as to where the program starts */


{ /* signifies the begin segment of the program */
printf("Hello World!"); /* this statement prints the word Hello World on the screen */
} /* signify the end segment of the program */

Basic Output Statements

Command Function
printf() Used to print the output to the screen and
can be used with variables
puts() Used to print a whole sentence on the
screen but cannot be used with variables
putchar() 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 Meaning
\b Backspace
\n New line
\r Carriage return
\t Horizontal tab
\<enter> Line continuation
\\ Backslash(\) character
\’ or \” Single or double quote

Identifier

A name that is used to reference variables, function, label and various other user-
defined 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

30709916.doc/Structure of C Program 2
Eg.
Num AnnualSalary
Tot_num CtrPt

C Keywords
auto enum short using
break extern signed void
case float sizeof volatile
char for static while
const goto struct
continue if switch
default int typedef
do long typeid
double register union
else return unsigned

Simple Data Types


1. Integer (int) is a whole number consisting of an optional sign (+ or -) followed
by a sequence of digits. Range: -32,768 to 32,767
Examples: 12, -128, 0, 2

• Short int – identical to an int


• Long int – takes up more space and can store large numbers.
Range: -2,147,483,648 to 2,147,483,647

2. Floating Point (float) is a number which can be written as a finite decimal, It


consists of an optional sign (+ or -), followed by one or more digits, a decimal
point and one or more further digits.
Examples: 2.255, -0.03, 325.14
3. Double Precision (double) is a special float which can store more significant
digits and have a larger exponent. It takes up more space in memory. This is
express in scientific notation (a number times a power of 10)
Examples: 9.23E+3 stands for
9.23 times 103
9.23 x 1000 = 9230.0

4. Character (char) is a single letter, digit, punctuation mark or control symbol


recognized by the computer. It is written enclosed within single quotation
marks.
Examples: ‘a’, ‘B’, ‘*’

Size and Range of Turbo C’s Basic Data Types


Type Bit Width Range
char 8 0 to 255
int 16 -32,768 to 32,767
short int 16 -32,768 to 32,767
long 32 -2,147,483,648 to 2,147,483,647
float 32 3.4E-38 to 3.4E+38
double 64 1.7E-308 to 1.7E+308

Variable Formatters
CODE DATA TYPE FORMAT
%c char A single character
%d int Whole number
%e double Scientific notation
%f float Fractional numbers
%s char[] (string) String of characters
Declaration of Variables

30709916.doc/Data Types 3
Variables (identifiers) need to be declared before you can use them in a program.

#include <stdio.h>
int x,y; /* global variables declaration */
char let='A';

main()
{
float area, pi=3.1416, radius; /* local variables declaration */
char stud_name[20];
}

Basic Input Commands

Command Function
scanf() Used to scan the keyboard for information
Usually placed after printf() statements
Used with integer, float and double data
gets() Reads a string of character entered at the
keyboard
Used with string data
getche() Reads a character from the keyboard
The key pressed is echoed to the screen
automatically
getch() 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

30709916.doc/Data Types 4
/* Prog Desc : A program that illustrates the use of scanf()
Programmer : Juan de la Cruz
Date Created: Nov. 26, 2008
*/

#include <stdio.h>
#include <conio.h>

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);
}

/* Prog Desc : A program that introduces the function of gets()


Programmer : Juan de la Cruz
Date Created: Nov. 26, 2008
*/

#include <stdio.h>
#include <conio.h>

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: Nov. 26, 2008
*/
#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 : A program that introduces the use of getch()

30709916.doc/Data Types 5
Programmer : Juan de la Cruz
Date Created: Nov. 26, 2008
*/
#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);
getch();
}

ARITHMETIC OPERATORS

Operation Operato
r
Addition +
Subtraction -
Multiplication *
Division /
Increment ++
Decrement --
Modulus %

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 ++x

30709916.doc/Data Types 6
Post Increment x++
DECREMENT Pre-increment --x
Post Increment x--
Eg.
z = y + x++;  means to add y and x, store the result in z, and
then increment x by 1

z = x + y;
x = x + 1;

z = y + ++x;  means increments x, then adds to y the new x


value and stores the
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

30709916.doc/Data Types 7
The Logical Operators

Operat Action Meaning


or
&& AND Requires all conditions to evaluate as TRUE (non-zero)
|| OR Will be executed if any ONE of the conditions is TRUE
(non-zero)
! NOT Negates a condition (changes from TRUE to FALSE and
vice versa
^ EOR Will be executed if either condition is TRUE, but not if
they are all TRUE.

Truth table
P Q P && Q P || Q P^Q !P !Q
0 0 0 0 0 1 1
0 1 0 1 1 1 0
1 0 0 1 1 0 1
1 1 1 1 0 0 0

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

30709916.doc/Data Types 8
Conditional Statements
a. if…else statement
- allows branching (decision making) depending upon the value or state of
variables.
Formats:
a. Sample program:
if (condition)
#include <stdio.h>
statement; main()
{
int magic=123, guess;
printf(“Enter your guess: “);
scanf(“%d”, &guess);
if (guess==magic)
printf(“**RIGHT!**”);
getch();
}

b. if (condition)
Sample program:
{ #include <stdio.h>
Statement1; main()
Statement2; {
} 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:
if (condition)
Statement1; #include <stdio.h>
else main()
Statement; {
int magic=123, guess;
printf(“Enter your guess: “);
scanf(“%d”, &guess);
if (guess==magic)
printf(“**RIGHT!**”);
else
printf(“**WRONG!**”);
getch();
}

d. if (condition1) Sample program:


Statement1; #include <stdio.h>
else if(condiiton2) main()
Statement; {
int magic=123, guess;
else if (condition3)
printf(“Enter your guess: “);
Statement; scanf(“%d”, &guess);
else if (guess==magic)
Statement; {
printf(“**RIGHT!**”);
printf(“\n%d is the magic number.”, guess);
}
else if (guess>magic)
printf(“..Wrong..Too High!”);
else
printf(“..Wrong..Too Low!”);
getch();
}

if (condition)
{
e. if(condition) Sample program:
Statement;
else
30709916.doc/Data Types 9
Statement;
}
else
Statement;
#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(“It’s correct!”);
getch();
}

b. switch…case 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. It is
optional and if not
present, no action takes place if all matches fail.

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

Sample program:
1. using integer

30709916.doc/Data Types 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;
30709916.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:
for (initialization; condition; increment) #include <stdio.h>
{ #include <conio.h>
statement1; main()
statement2; {
} 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;
x=2; program
z=3; and write the output
for(x=1; x<=6; x++)
{
printf(“%d”, y);
y=y+1;
30709916.doc/Data Types
}
12
printf(“\n%d”,z);
getch();
}
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)
{ of like this:
Statement1; WHILE this condition is true
Statement2;
} 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. do…while statement

30709916.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
{ thought of like this:
Statement1; DO
Statement2;
} while (condition) The following statements
WHILE the condition is TRUE

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();
}

Exercises:
1. Trace the program and write the output
#include <stdio.h>
#include <conio.h>
main()
{
int n=1;
clrscr();
printf(“By ones:\n”);
while(n<=10)
{
printf(“%d\n”, n);
n++;
}
printf(“\nBy twos:\n”);
n=0;
do{
n=n+2;
printf(“%d\n”,n);
} while(n!=12);
getch();
}
2. Write a program using the nested while or do/while statement to produce the
following output.

1
22
333
4444
55555

30709916.doc/Data Types 14

S-ar putea să vă placă și