Professional Documents
Culture Documents
Page
INTRODUCTION
C is a general-purpose programming language, which features economy of
expression, modern control flow and data structures and a rich set of operations. It
has been called as system programming language because it is useful for writing
compilers and operating systems.
BRIEF HISTORY
1.
2.
3.
4.
5.
6.
OF
an expansion of B.
a programming language designed by Dennis Ritchie in 1972 at AT and T Bell
Laboratories.
C was originally designed for and implemented on the UNIX operating system
on the DEC PDP II.
DEFINITION
OF TERMS
Interpreters reads the source code of your program one line at a time and performs
the specific instructions contained in that line.
Compilers reads the entire program and converts it into object code, which is a
translation of the program source code into a form that can be directly executed by
the computer.
Compile Time refers to the events that occur during the compilation process.
Object Code is also referred to as binary or machine code
a translation of the source code of a program into machine code, which
the computer can read and execute directly.
Object code is the input to the linker
Source Code the text of a program that a user can read, commonly thought of as
program.
The source code is the input into the C compiler.
Run Time refers to the events that occur while the program is actually executing.
Library collection of pre-written.
Syntax errors that are detected during compiled time.
Semantic/ Run-time errors that are detected during execution time.
C Language Programming
Page
Make/Edit the
source code
Source code
Pre - processing
Compiler
(compilation)
Object Code
Linker
(Linking)
Executable
Code
COMPONENTS
OF TURBO
Turbo C is more than just a version of the C language. Rather, it includes a complete
environment in which to create, test, and run program. This programming environment
consists of a number of components:
1. Editor used to create program source code.
2. Extended C Language this version o C is significantly extended from the base bones
language of Ritchies specifications. The extension includes enhancement which
make the Turbo C compatible with the new proposed and ANSI Standard.
3. Compiler used to convert source code into machine code or binary code.
4. Debugger used for testing program and locating programming errors.
5. Run-Time Environment the capability for running programs within the Turbo C system.
C Language Programming
Page
6. User Interface the various of Turbo C are integrated into a single program which allows
you to smoothly from source code entry to compilation to debugging to running
without ever leaving the Turbo C environment.
FEATURES
AND
CHARACTERISTICS
OF
1.
2.
Portable Program
it is possible to adapt software written for one type of computer for use on
another
Ex. Program written for an Apple II+ can be easily moved to an IBM PC.
3.
4.
5.
C allows manipulation of bit, bytes and addresses (basic elements which the
computer functions). Can manipulate data using arrays and pointers.
6.
USES
OF
C was used for systems programming. A system program is part of a large class of
programs that form a portion of the operating system of the computer or its support
utilities. For example the following are commonly called systems programs
Operating System
Interpreters
Editors
Assemblers
Compilers
Database Managers
C PROGRAM STRUCTURE
_____________________________________________________________________
<preprocessor directive>
<declaration section>
main( )
{
/* refers to the beginning of the program */
statement;
...
statement;
}
/* refers to the end of the program */
______________________________________________________________________
C Language Programming
Page
1.
/* ... */ Comment
2.
Preprocessor Directive
Contains information needed by the program to ensure the correct operation of
Turbo Cs standard library functions.
a. #include directive (commonly know as macro include) is a
preprocessing directive that causes a copy of the file to included at this
point in the file when compilation occurs.
a #include line can occur anywhere in a file, though it is typically at the
head of the file. The quotes surrounding the name of the file are
necessary.
an include file, is also called header file, can contain # define lines and
other lines. By convention, the names of header files end in .h.
Examples:
#include
#include
#include
#include
stdio.h
<stdio.h>
<string.h>
<math.h>
Declaration Section
syntax: <data type> <identifier>
ex. int x, y, z;
float f=5.67;
char g;
char name[10];
int x=10;
A. Data Types
a. int contain integral values only, that is values that do not contain
decimal places.
C Language Programming
Page
variables of type int, can hold integer quantities that do not require a
fractional component. Variables of this type are often used for controlling
loops and conditional statements.
a whole number consisting of an optional sign (+ or -) followed by a
sequence of digit.
occupies two bytes in the address.
can contain no decimal point or fractional part.
cannot contain commas.
ranges from 32768 to +32767
Types of int
short int identical with int
ranges from 32768 to +32767
occupies two bytes
2. long int takes up more space and can store large number
ranges from 2147483648 to +2147483647
occupies 4 bytes
3. unsigned int cannot be negative from 0 to 65536
4. unsigned long int
1.
b.
c.
double is a special float which can store more significant digits and
have longer exponent.
occupies 8 bytes in the memory
ranges from 1.7E-308 to 1.7E+308 with 15 digits accuracy.
e.
Ex.: char
char
char
char
c;
B = *;
a[30];
a = apple;
void
valueless
Three uses of void:
1.
2.
3.
B. Identifiers
The names that are used to reference variables, functions, labels and
various other user-defined objects.
C Language Programming
Page
In C, upper and lower case are treated as different and distinct from one
another.
Ex.: studname, Studname, StudName are three separate identifiers.
An identifier may not be the same as a Turbo C keyword, and it should not
have the same name as a function.
Correct
count
test123
4.
Incorrect
1count
hi!there
NOTES:
All C keywords must be lowercase. It may not be used for any other purpose in a C
program.
KEYWORDS/RESERVED WORDS
Words that have a special meaning in C and cannot be used for other purposes.
All upper in lowercase.
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
interrupt
_cs
_es
cdecl
near
huge
_ds
far
C Language Programming
Page
VARIABLES
variable-name = expression
x = -10;
ch = A;
scanf(%d, &x);
scanf(%lf, &y);
int x = 13;
char y = a;
double a, b = 120.00;
CONSTANTS
C Language Programming
Page
char ch = a;
int num = 0;
float bal = 123.3;
2.
3.
floating-point constant are required the use of decimal point followed by the numbers
fractional components.
Example:
12.134
4.
char
int
float
double
string
a
10.1
123.23
123.23
Elsa
9
123
12323333
Declared Constants constants which are assigned a name declared constant are
defined using a # defined declaration at the beginning of the program. This
declaration is introduced by the word # define followed by a constant name and its
value.
Examples:
#
#
#
#
#
define
define
define
define
define
total amount
grapes
titik
m
salita
1000
90.00
E
14
good day
Access Modifiers
C has two type of modifiers that are used to control the way in which variables may be
accessed or modified.
1. const variables declared under this modifier cannot be changed during program
execution. However, you may give an initial value before the start of the
program.
Syntax:
const datatype variable = value;
Example:
const float
version = 3.20;
Interpretation:
This creates a float variable called version that may not be modified by your
program. A constant variable will receive its value either from an explicit
initialization or by some means dependent on the hardware.
2. using # define
C Language Programming
Page
Syntax:
# define variable
value
Example:
# define amount 56.89
Type Modifiers
A modifier is used to alter the meaning of the base type to more precisely fit the needs
of various situation. With the exception of type void, the basic data type may have
various modifiers preceding them.
Example:
signed
long
unsigned
short
Bit Width
8
8
8
Range
to
to
to
-128
0
-128
127
255
127
int
unsigned int
signed int
short int
unsigned short int
signed short int
long int
signed long int
16
16
16
16
16
16
32
32
-32768
0
-32768
-32768
0
-32768
-2147483648
-2147483648
to
to
to
to
to
to
to
to
32767
65535
32767
32767
65535
32767
2147483649
2147483649
float
double
long double
64
64
80
3.4E 38
1.7E 308
3.4E-4932
to
to
to
3.4E+38
1.7E+308
1.1E+4932
Assignment Statement
Is the process of assigning a value to a variable. In C, we use the equal sign (=)
as the assignment operator.
A = C + r * (9 / p);
Expression
Assignment Operator
Variable
C Language Programming
Page
10
OPERATORS
OPERATORS
a.
Arithmetic Operators
Symbols
+
*
/
%
-++
Functions
subtraction
addition
multiplication
division
modulus
decrementing
incrementing
Important Notes:
1.
2.
3.
4.
The operators +, -, *, and / all work the same way in C as they do in most computer
languages.
When / is applied to an integer or character, any remainder will be truncated.
Example:
13/6 = 2
3/4 = 0
10/3 = 3
11/2 = 5
The modulus division operator, % yields the remainder of an integer division. % cannot be
float on type or double.
Example:
13 % 2 = 1
-25 % 2 = -1
5%3=2
6%2=0
When an increment or decrement operator precedes its operand, C performs the increment
or decrement operation prior to using the operands value. If the operator follows its
operand, C uses the operands value before incrementing or decrementing it.
Example:
X = 12;
Y = ++X;
X is 13; Y is 13
X = 12;
Y = X++
X is 13; Y is 12
C Language Programming
Page
11
decrement operator
Example:
1. X = X + 1 or X+=1 is the same with X++
2. X = 5, Y = 12
W = Y + X++
W = Y + X;
17
X = X + 1;
6
W = Y + ++ X
X =X + 1;
6
W= Y+ X;
18
W = Y + X--
W = Y + X;
X = X - 1;
17
4
W = Y + -- X
X =X - 1;
W= Y+ X;
4
16
Symbols
>
>=
<
<=
==
!=
c.
Functions
greater than
greater than or equal to
less than
less than or equal to
equal
not equal
Examples
x>y
num >= 100
x<y
num <= 100
x == y
x != 10
Logical Operators refers to the ways the relationships can be connected together using the
rules of formal logic.
Symbols
&&
||
!
Functions
and
or
not
d.
e.
Combined Operators
+=
*=
-=
ex. a+=b
ex. a*=b
ex. a-=b
a=a+b
a=a*b
a=a-b
C Language Programming
/=
%=
f.
ex.
ex.
Page
a/=b
a%=b
12
a=a/b
a=a%b
Other Operators
1.
?: Ternary Operator (Question mark colon) because it requires three operands and takes
the general form
Syntax:
Example:
x = 10;
y = x>9 ? 100: 200;
x=10
x>9 ? printf(Yes): printf(No);
max = (a>b) ? a : b;
Interpretation:
x = 10;
if (x>9)
Y = 100;
else
Y = 200;
Exp1, epx2 and exp3 are expressions; exp1 is evaluated, if true then
exp2 is evaluated and its value becomes the value of the expression.
The value of a ? expression is determined this way: Exp1 is evaluated.
If it is true, then Exp2 is evaluated and becomes the value of the
entire ? expression. If Exp1 is false, then Exp3 is evaluated and its
value becomes the value of the expression.
Example:
Finally
x = (y=3, y+1);
The value of x is 4
y = 20;
x = (y=y-5, 30/y);The value of x is 2
C Language Programming
HIERARCHY
OF
Page
13
C OPERATORS
()
! ++ - - (type)
* / %
+ < <= > >=
== !=
&&
||
?
= *= /= %= +=
,
highest
lowest
EXPRESSION
Operators, constant and variables are the constituents of expressions
Expression Evaluation:
1.
2.
3.
4.
v = (6 / 2 * 3) >= ((6/2 % 3) + 6 * 2)
v = (5 == (3 + 1)) || (( 6 % 3) >= (5 /2)) && (5 !=6)
A = 1; B=2; C=3;
X = !((A > C) && (B >=3)) || (C < 4) && ((6 <= 6) || (7 < B))
v = !((3 * 2) < (1 * 3)) || !(2== 2)
CASTS
It is possible to force an expression to be of a specific type by using a construct called a
cast.
Syntax:
(type) expression
where:
type is one of the standard C data types.
Sample Program No. 1
#include "stdio.h"
main()
{
int i;
clrscr();
for(i=1;i<=5;++i)
printf("%d / 2 is: %.2f\n", i, (float)i/2);
getche();
C Language Programming
Page
14
IN
Example:
printf
printf
printf
printf
(%c, a);
(%d, b);
(%f, c);
(%s, name);
When an argument is printed, the place where it is printed is called field and the number
of characters in its field is called its field width. The filed width can be specified in a
format as an integer occurring between the percent character (%) and the format specifier.
Example:
printf (%c%3c%5c\n, X,Y,Z);
C Language Programming
Page
15
will print:
X_ _ _ Y_ _ _ _ _Z
Examples:
#include "stdio.h"
main()
{
clrscr();
printf("programming is fun \n");
printf("programming in C is even more fun\n");
getche();
}
Output:
programming is fun
programming in C is even more fun
#include <stdio.h>
main()
{
clrscr();
printf("Testing...\n..1\n...2\n....3\n");
getche();
Output:
Testing...
..1
...2
....3
#include "stdio.h"
main()
{
int sum;
clrscr();
sum=50+25;
printf("The sum of 50 and 25 is %d\n", sum);
getche();
Output:
The sum of 50 and 25 is 75
#include <stdio.h>
C Language Programming
Page
16
main()
{
}
Output:
The sum of 50 and 25 is 75
2.
Example:
1.
2.
3.
4.
scanf(%d, &numero);
scanf(%c, &letra);
scanf(%s, ngalan);
scanf(%lf, doble);
Meaning
Newline
Backspace
Formfeed
Horizontal tab
Vertical tab
Insert Single quote
Backslash
Insert Double quote
Sound the bell
Insert char hh where is hexadecimal number
C Language Programming
Page
17
Example:
#include <stdio.h>
main()
{
char my_char;
clrscr();
printf("Please type a character : ");
scanf("%c", &my_char);
printf("Thank You. That character was %c\n", my_char);
getche();
4.
5.
6.
IN
getch( )
reads a character without echo. Does not wait for carriage return ENTER key.
getche() reads a character with echo. Does not wait for carriage return or ENTER key.
gets( )
this function takes the name of the string as an argument and reads characters from
the keyboard until ENTER key is pressed. ENTER key is not stored but is replaces be
the null terminator.
getchar() reads a single individual character from the keyboard and waits for the carriage
return or ENTER key.
puts( )
write a string to the screen, followed by a newline. It can only output a string of
characters. It cannot output numbers or do format conversion. It takes up less space
and run faster.
putchar( ) writes a string (character) to the screen.
C Language Programming
Page
18
CONTROL STRUCTURES
CONTROL STRUCTURES
3 KINDS
OF
CONTROL STRUCTURES
C Language Programming
Page
19
if (condition)
statementT;
Example:
if (grade >=75)
printf(Passed);
Interpretation:
Note:
IF ELSE STATEMENT
The general form of the if - else statement is
Syntax :
if (condition)
statementT;
else
statementT;
Example:
C Language Programming
Page
20
IF ELSE IF STATEMENTS
if (condition)
Statement1;
else if (condition)
statement2;
else if (condition)
statementn;
:
else statemente;
Example:
if (x > 0)
printf(x is positive);
else if (x < 0)
printf(x is negative);
else printf(x is zero);
Interpretation:
The conditions here are evaluated in sequence until a true condition is reached. If
a condition is true, the statement following it is executed, and the rest is skipped.
If a condition is false, the statement following it is skipped, and the next condition
is tested. If all conditions are false, then the statement e following the final else is
executed.
Note:
A common programming constructs is the nested if else statement. It look like this:
Syntax :
Example:
if (condition)
if (condition)
statement2;
else
statementn;
else
statemente;
if (x == 50)
if (y >= 120)
{ sum = x+y;
printf(the sum of x and y is %d, sum);
}
else
{ diff = x - y;
printf(the difference of x and y is %d, diff);
}
else
printf(x is zero);
printf(Next time);
C Language Programming
Page
21
int num;
clrscr();
printf("Enter an integer ");
scanf("%d",&num);
if (num > 0)
printf("%d is a positive integer",num);
else
printf("%d is a negative integer",num);
getch();
}
Sample Program No. 2
/* Program to determine if a number is odd or even*/
#include "stdio.h"
main()
{
int num,rem;
clrscr();
printf("Enter a number ");
scanf("%d",&num);
rem = num % 2;
if (rem == 0)
printf("%d is an even number",num);
else if (rem != 0)
printf("%d is an odd number",num);
getch();
}
Sample Program No. 3
/* Program Arithmetic Operations */
#include "stdio.h"
main()
{
int f,s, total=0;
char optr;
clrscr();
printf("Enter 1st number : "); scanf("%i", &f);
printf("Enter the operator : "); scanf("%s", &optr);
printf("Enter 1st number : "); scanf("%i", &s);
if (optr=='+')
total=f+s;
if (optr=='-')
total=f-s;
if (optr=='*')
total=f*s;
if (optr=='/')
total=f/s;
if (optr=='+' || optr=='-' || optr=='*' || optr=='/')
printf("%d %c %d = %d", f, optr, s, total);
else
printf("Operator not valid!!!");
}
getch();
SWITCH STATEMENT
C Language Programming
Page
22
Syntax:
switch(variable/ expression)
{
case constant1 : statement;
break;
case constant2 : statement;
break;
case constant3 : statement;
break;
:
default
: statement;
}
Example:
switch(QUIZ)
{
case 10 :
case 9 : printfA);
break;
case 8 : printfB);
break;
case 7 : printfC);
break;
case 6 : printfD);
break;
case 5 :
case 4 :
case 3 :
case 2 :
case 1 :
case 0 : printfF);
break;
default : printf(Input out of Range);
}
Interpretation:
The switch expression maybe any expression which evaluates to an int,
conditional, char.
The case list must consists of constants whose matches that of the switch
expression.
After the statements for a case, a keyword break maybe used.
The break keyword means that at that point, execution should jump to the
end of the switch statement.
The switch statement is terminated by curly bracket (}).
This switch constant can be used to specify an action to be taken if the
value of the switch expression does not match any of the listed values.
Note:
C Language Programming
Page
23
If no case label value matches the expression, the entire switch statement
body is skipped unless it contains a default label. If so, the statements
following the default label are executed.
C Language Programming
Page
24
FOR LOOP
The for loop will continue to execute as long as the condition is true. Once the condition
becomes false, program execution will resume at the statement following the for.
Syntax:
Example:
Interpretation:
First, the initialization expression is executed.
Then, the loop repetition condition is tested.
If it is true, the statement is executed, and the update expression is evaluated. The
loop repetition condition is re-tested.
If the loop repetition condition is found to be false, the for loop is exited.
Note / Programming style:
These three major sections must be separated by semicolons.
You may place all three expressions in the for heading in a single line, specially if all
three expressions are very short.]
The body of a for loop may be a compound statement.
C Language Programming
/* Program on Factorial */
#include <stdio.h>
main()
{
int f,x,ans;
clrscr();
printf("Enter a number : "); scanf("%d",&f);
ans=1;
for(x=f;x>=1;x--)
ans=x*ans;
printf("The factorial of %d is %d",f, ans);
getche();
}
Page
25
Enter a number : 5
The factorial of 5 is 120
Enter Base : 2
Enter Exponent: 3
The answer is 8.00
10
22
39
4 26
5 58
6 110 Institute of the Philippines
Technological
7 187
294 142 40
C Language Programming
Page
26
#define r 7
int k, k2, x, y, z;
main()
{
clrscr();
k=x=0; y=2; z=5; k=1;
for (;k<=r;k++)
{
k2=x;
x+=y;
y+=z;
z+=5;
printf("%d %d \n", k, k2);
}
printf("%d %d %d", x, y, z);
getch();
}
Sample Program No. 5
/*Program Simulation*/
#include "stdio.h"
int x, y;
main()
{
clrscr();
x=7; y=3;
x=x%y;
if(x==0)
printf("FINISH");
else
for(x=10;x>=2;x-=2)
for(y=x;y>=1;y-=2)
printf("%d ", y);
printf("\n");
getche();
}
Sample Program No. 6
/* Program Simulation */
#include "stdio.h"
#define p printf
#define c case
10 8 6 4 2 8 6 4 2 6 4 2 4 2 2
_JACK**_AND_JILL_
C Language Programming
Page
27
c 1 : p("J");break;
c 4 : p("C");
c 15: p("K");
c 16: p("**");
c 10: p("_AND_");
c 13: p("J");break;
default : p("I");p("L");p("L");p("_");
}
x++;
}
getch();
WHILE LOOP
continues to execute as long as the condition which can be any expressions remains true.
Syntax:
Example:
while (num != 0)
{ scanf(%d, &num);
sum += num;
}
printf(the sum of all number is %d, sum);
Interpretation:
First, the loop repetition condition is tested or evaluated.
If it is true, the statement is executed and the loop repetition condition is retested.
The loop body, namely statement is repeated as long as the loop repetition
condition is true.
Once it is found to be false, the while loop is exited and the next program
statement after the while statement is executed.
Note:
int count=1;
clrscr();
while (count<=5)
{
printf("%d\n", count);
++count;
}
getche();
1
2
3
4
5
C Language Programming
Page
28
Enter a number
12345
54321
DO WHILE LOOP
Syntax:
do
Example:
do {
statement;
while (loop repetition condition);
scanf(%d,&num);
sum += num;
} while (num > 100);
printf(the sum is %d, sum);
Interpretation:
If the result of the loop repetition condition is TRUE, then the loop continues and
program statements is once again executed.
C Language Programming
Page
29
terminated and next statement in the program will be executed in the normal sequential
manner.
Sample Program No. 1
/* Program to reverse the digits of a number */
#include<stdio.h>
main()
{ int num, rightdigit;
clrscr();
printf("Enter a number \n");
scanf("%d", &num);
do
{
rightdigit = num % 10;
printf("%d", rightdigit);
num = num / 10;
}
while (num != 0);
printf("\n");
getch();
}
Enter a number
12345
54321
0 1 1 2 3 5 8 13 21 34 55 89 144
{
char name[20], stno;
int ctr;
clrscr();
printf("Student Name : "); gets(name);
gotoxy(5,4);printf("Student No.:
Q");
ctr=1;
do
{
do
{
gotoxy(18+ctr,4);
C Language Programming
Page
30
stno=getch();
gotoxy(184+ctr,4); printf("%c",stno);
}
while(!((stno>='0') && (stno<='9')));
ctr=ctr+1;
}
while (ctr <=7);
getche();
}
BREAK
AND
CONTINUE STATEMENT
break Statement
This statement is encountered inside the loop, the loop is immediately terminated and
program control resumes at the next statement following the loop.
Example:
#include <stdio.h>
main()
{ int t;
clrscr();
for(t=0; t<100; t++)
{ printf("%d ",t);
if (t==10)
break;
}
getch();
}
0 1 2 3 4 5 6 7 8 9 10
continue Statement
C Language Programming
Page
31
Works in a somewhat similar way to the break statement, instead of forcing termination,
continue forces the next iteration of the loop to take place, skipping any code in between.
The continue statement causes the current iteration of the loop to stop and causes the next
iteration of the loop to begin immediately. The continue statement may only occur inside for,
while, and do loops.
Sample Declaration:
do {
scanf(%d, &num);
if (x < 0)
continue;
printf(%d, x);
} while (x != 100);
Example:
#include <stdio.h>
main()
{ int t;
clrscr();
for(t=0; t<10; t++)
{ if (t%2)
continue;
printf("%d ",t);
}
getch();
}
02468
goto Statement
Is included in the C language because sometimes it is the only way out of a certain condition.
Used to alter the normal sequence of a program execution statements by transferring control to
some other part of the program.
Syntax:
goto label;
label:
statement;
where:
label is an identifier
the target statement must be labeled (unique label)
C Language Programming
Page
32
Example:
void main( )
{
int counter = 0;
try_again:
if (counter < 100) goto stop;
printf(%d\n, counter);
++counter;
goto try_again;
stop:
FUNCTIONS
FUNCTIONS
is a subroutine that contains one or more statements and performs one or more tasks
is a section of a program which perform a specific task. The task assigned to a function is
performed whenever C encounters the function name.
Is actually a subprogram that is, a function perform a task within a program and is
written in a form similar to C main program.
Advantages of Using a Function:
1. fits naturally in top-down approach
2. can be divided for many programmers as subtasks
3. can easily be tested, each function can be tested individually.
C Language Programming
Page
33
Reuse of Code
Functions can be executed more than once
Easier to alter code
Procedural Abstraction
Procedures functions in C
A programming technique in which we use function subprograms to allow us to
remove from the main function, the code that provides detailed solution to a subproblem.
Protection of data
Centers around concept of local data data available only to the function wherein
it is declared and only when the function is executing. When the function is done,
the data are gone.
Syntax:
type_specifier function_name(parameter_list)
{
body of function
}
where:
type_specifier / return_type
( specifies the type of value that the function returns using the return statement.
0parameter_list / function_argument
( comma separated list of variables that receive the values of the arguments when the
function is called.
( a function maybe without parameters in which case the parameter list contains only
the keyword void.
Uses of return Statement:
1. it causes an immediate exit from the function it is in. That is, it causes program execution
to return to the calling code.
2.1 it can be used to return a value.
Sample Program No. 1
/* Program that uses a function without a parameter */
#include <stdio.h>
void star(void)
*****C*****
{
printf("*****");
}
main()
{
clrscr();
star();
printf("C");
star();
C Language Programming
Page
34
getch();
Enter a number : 3
The cube of 3 is 27
main()
{
int y;
clrscr();
printf("Enter a number : ");
scanf("%d",&y);
printf("The cube of %d is %d",y, cube(y));
getche();
}
C Language Programming
Page
35
getche();
Global variables
known throughout the entire program and may be used by any piece of code. It is declared
outside any function.
Local variables
variables that are declared inside a function. It can be referenced only by a statements that
are inside the block in which the variables are declared.
Formal variables
variables that accept the values of the arguments of a function.
PASSING DATA
IN
FUNCTIONS
Call by value
this method copies the value of an argument into the formal parameter of the subroutine.
changes made to the parameters of the subroutine have no effect on the variables used to
call it.
2. Call by reference
the address of an argument is copied into the parameter. Inside the subroutine, the address
is used to access the actual argument used in the call.
changes made to the parameter affect the variable used to call the routine.
10
12
14
12
12
12
12
12
14
10
12
14
16
14
14
10
16
10
14
16
10
16
16
12
16
10
10
16
C Language Programming
Page
36
clrscr();
trick(w,x,y,z);
trick(x,y,w,z);
trick(y,w,z,x);
trick(x,x,w,z);
trick(x,y,y,w);
trick(x,z,z,w);
trick(x,y,w,z);
getch();
5 8 13 18
7 7 16 17
8 13 7 17
15 6 20 7
17 7 15 7
19 16 10 14
7 7 14 19
main()
{
int w=5, x=8, y =13, z=18;
clrscr();
printf("%d %d %d %d\n",w,x,y,z);
print(&w,x,y,&z);
printf("%d %d %d %d\n",x,y,w,z);
print(&y,w,z,&x);
printf("%d %d %d %d\n",z,w,y,x);
print(&z,z,w,&y);
printf("%d %d %d %d\n",x,w,y,z);
getch();
}
10
13
15
12
13
13
13
12
14
10
12
15
13
16
14 16
10 15
14 13
11 14
15 11
13 10
9 149 13 17 13
main()
C Language Programming
Page
37
8 10 12 14
11 12 12 8
11 13 7 13
11 11 7 12
14 7 11 12
11 11 11 8
11 14 7 127 11 15 11
main()
{
int w=8, x=10, y=12, z=14;
clrscr();
trick(w, &x, y, &z);
trick(x, &y, y, &w);
trick(x, &y, w, &z);
trick(x, &x, w, &z);
trick(y, &w, z, &x);
trick(x, &z, z, &w);
trick(x, &y, w, &z);
printf("%d %d %d %d", w,x,y,z);
getch();
}
5 15
15 5
12 5
5 12
5 15
12
12
15
15
12
C Language Programming
Page
38
}
main()
{
int x=5, y=12, z=15;
clrscr();
swap(&z,&y); printf("%d %d %d\n", x,y,z);
swap(&y,&x); printf("%d %d %d\n", x,y,z);
swap(&z,&x); printf("%d %d %d\n", x,y,z);
swap(&x,&y); printf("%d %d %d\n", x,y,z);
swap(&y,&z); printf("%d %d %d\n", x,y,z);
getch();
}
Sample Program No. 11
/*Program Simulation */
#include <stdio.h>
swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y= temp;
}
6 10
10 6
10 4
10 6
6 10
4
4
6
4
4
main()
{
int x=4, y=10, z=6;
clrscr();
swap(&z,&x); printf("%d %d %d\n", x,y,z);
swap(&y,&x); printf("%d %d %d\n", x,y,z);
swap(&z,&y); printf("%d %d %d\n", x,y,z);
swap(&y,&z); printf("%d %d %d\n", x,y,z);
swap(&x,&y); printf("%d %d %d\n", x,y,z);
getch();
}
240
644
C Language Programming
Page
39
*a=d;
*c=b+d;
}
main()
{
int x, y, z;
clrscr();
x=y=z=0;
balik(&x,5,&y);
printf("%d %d %d\n",x,y,z);
balik(&z,y,&x);
printf("%d %d %d\n",x,y,z);
getch();
}
STRINGS
ARRAYS
OF CHAR AND
STRINGS
A character string is a sequence of characters which is to be considered as a single data item. The
characters of a string are displayed enclosed within double quotes. A string may include letters, digits,
symbols and control characters. Strings are used in application programs to store and process text data.
C Language Programming
Page
40
Examples:
Input Error
123456
$890.99
STRING FUNCTIONS
header files : string.h
Copy
1.
strcpy(str1,str2)
char str1[8], str2[8];
strcpy(str1,hello);
strcpy(str2,there);
strcpy(str1,str2);
strcpystr2,str1);
printf(%s, str2);
output:
there
strncpy() used to copy to count characters from the string source_str2 into the
string target_str1, target_srt1 and source_str2 overlap, the behavior of this is
undefined; if string pointed by source_str2 has fewer count characters, nulls are
appended.
2.2
syntax:
strncpy(target_str1,source_str2,count);
example:
strcpy(str1,Hello);
strncpy(str1,str1,4);
output:
Hell
3. strxfrm() used to copy to count characters from the string source_str2 into the
string target_str1. It returns the length of the string source_str2. This function is
the same with the strncpy.
syntax:
strncpy(target_str1,source_str2,count);
Concatenate
1.
strcat(str1,str2);
C Language Programming
example:
Page
41
output:
Folks! HellothereFolks
2. strncat() concatenates no more than count characters of str2 to str1 and assigns this
to str1; str2 is untouched by the operation
syntax:
strcat(str1,str2,count);
Compares
1. strcmp() compares the two strings until unequal characters are found or until the end
of a strings is reached. It returns an integer to indicate the results of the compare
based on the following:
Value
Meaning
< 0
>0
syntax: strcmp(str1,str2);
example:
char s[10];
printf(Enter password: );
gets(s);
if (((strcmp(s,pass)) ==0))
printf(Welcome);
else
printf(Intruder!!!);
2.
stricmp()/ strcmpi()
compares two strings while ignoring cases; strcmpi() is a
macro that translates to a strcimp() call
syntax:
Meaning
< 0
>0
3. strucmp() / strncmp() / strncmpi() compares no more than count characters for the
two strings; strncmpi() and strnicmp() ignore cases.
syntax:
Case
C Language Programming
Page
42
strlwr(str);
example:
char s[20];
strcpy(s,A TEST);
strlwr(s);
printf(%s,s);
2.
Set
1.
output:
2.
strset(str,chr);
strcpy(str,HELLO);
strset(str,E);
EEEEE
strnset() sets the first count character in the str to the value of chr.
syntax: strnset(str,chr,count)
example
output:
strupr(str);
Others
1.
strcpy(str1,HELLO);
strnset(str1,A,3);
AAALO
2.
strlen(str);
example:
char s[20];
int x;
gets(s);
x=strlen(s);
printf(The length is %d, x);
strrev() reverses all the characters in the string pointed to by str.
syntax:
strrev(str);
example:
C Language Programming
Page
43
char s[10];
gets(s);
strrev(s);
printf(%s, s);
CHARACTER FUNCTIONS
header files : ctype.h
1. isalnum() a function that returns non-zero if its argument is either a letter of the alphabet
or a digit.
syntax:
int isalnum(int char);
2. isalpha() a function that returns non-zero if char is a letter of the alphabet otherwise zero
is returned.
syntax:
int isalpha(int char);
3. isdigit() a function that return non-zero if char is a digit, that is 0-9; otherwise zero is
returned.
syntax:
int isdigit(int char);
4. islower() a function that returns non-zero if char is a lowercase letter (a-z); otherwise zero
is returned.
syntax:
int islower(int char);
5. ispunct() a function that returns non-zero if char is a punctuation character, excluding the
space; otherwise zero is returned.
syntax:
int ispunct(int char);
6. isspace() a function that returns non-zero if char is one of the following: a space, tab,
vertical tab, form feed, carriage return, newline; otherwise zero is returned.
syntax:
int isspace(int char);
7. tolower() returns the lowercase equivalent of the character pointed to by char, if char is in
lowercase it is unchanged.
syntax:
int tolower(int char);
example:
char ans;
scanf(%c, &ans);
if (tolower(ans)==y)
printf(bye);
else
printf(again?);
8. toupper() returns the uppercase equivalent of the character pointed to by char, if char is in
uppercase it is unchanged.
syntax: touppper(char);
C Language Programming
Page
44
MATHEMATICAL FUNCTIONS
header file : math.h
1. abs() a function that returns the absolute value of integer number.
syntax:
int abs(int num);
2. ceil() a function smallest integer represented as double not less than num.
syntax:
double ceil(double num);
3. fabs() a function that return the absolute value of num.
syntax: double fabs(double num);
4. floor() a function that returns the largest integer, represented as double not greater than
num.
syntax:
double floor(double num);
5. fmod() a function that returns the remainder of x / y.
syntax:
double fmod(double x, double y);
6. pow() a function that returns based to the exp power (base exp.)
syntax:
double pow(double base, double exp);
7. pow10() returns 10 raised to the power n. Overflow and undeflow are the only possible
errors.
syntax:
double pow10(int n);
8. sqrt() returns the square root of num. If called with a negative argument domain error will
occur.
syntax: double sqrt(double num);
CONVENTIONAL FUNCTIONS
header file : math.h
1. atof() a function that converts the string pointed to be str into a double value.
syntax:
double atof(const char *str);
2. atoi() a function that converts the string pointed to by str into an int value. The string must
contain valid into value, if not zero is returned.
syntax:
int atoi(const char *str);
3. atol() a function that that converts the string pointed to by str into a long int value. The
string must contain valid long int value.
syntax: int atol( const char *str);
C Language Programming
Page
45
a function that converts the integer number into string equivalent and places the
result in the string pointed to be str. The base of the output string is determined by radix
which can be in the range of 2-36. this function returns a pointed to str. There is no error
return value. Be sure to call itoa() with string of sufficient length to hold the converted
result. The maximum length needed is 17 bytes.
syntax:
char *itoa(int num, char *str, int radix);
4. itoa()
C Language Programming
Page
46
ARRAYS
ARRAY
collection of variables of the same type that are referenced by a common name. A
specific element in an array is accessed by an index. The lowest address corresponds to
the first element and the highest address corresponds to the last element. All arrays
have 0 as the index of their first element.
Is a fixed-size, sequenced collection of elements of the same data type.
Sample Representation:
Assuming we have a problem that requires 30 integers to be processed. We need to read,
processed and print them. We must also keep these 30 integers in memory for the duration of the
program. We can declare and define 30 variables, each with a different name, as shown in the
illustration below.
Num0
Num1
Num2
Num29
Explanation:
This will involved thirty variables but having 30 different names creates another
problem. How can we read 30 integers from the keyboard and store them? To read 30 integers
from the keyboard, we need thirty references, each to one variable. Another thing, once we
have them in memory, how can we print them? To print them, we need another thirty
references.
But in this situation, 30 integers may be acceptable but it definitely not acceptable
for 500 or 3,000 or 30,000 integers. To process such large amount of data, we need a powerful
data structure, such as array.
USING ARRAYS
IN
The advantages of the array would be limited if we didnt also have programming constructs that
would allow us to process the data more conveniently. Fortunately, there is a powerful set of
programming constructs using loops that makes array processing easy.
C Language Programming
Page
47
We will first show how to declare and define arrays. Afterwards, we will look at several typical
applications using arrays including reading values into arrays, accessing and exchanging elements in
arrays and printing arrays.
An array must be declared and defined first before it can be used. Through declaring and defining
arrays will tell the compiler the name of the array, the type of each element, and the size or number of
elements in the array. The size of the array is a constant and must have a value at compilation time.
Syntax:
element_type array_name[array_size];
where:
element_type type of each elements
array_name name of the array
array_size
number of elements the array will hold
Example Declaration:
int scores [9];
type of
each
element
[0] [1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
scores
[2]
name of
the array
[3]
[4]
[5]
[6]
[7]
[8]
[9]
name
number of
elements
[1]
[2]
. . .
[37] [38]
[39]
gwa
Sample Program:
#include <stdio.h>
#include <conio.h>
int score[30], x,sum=0;
array
void main
declaration
{
clrscr();
printf("Please enter 30 scores:\n ");
for (x=0;x<30;x++)
{
scanf("%d",&core[x];
C Language Programming
Page
48
Syntax:
array_name[index]
Example:
Given an array score[30], we could access the first element as score[0].
Storing Values in Arrays
Declaration and definition only reserve for the elements in the array. No values will be stored. If we
want to store in the array, we must either initialize the elements, read values from the keyboard, or
assign values to each individual element.
Initialization
Initialization of all elements in an array can be done at the time of declaration and
definition, just as with declaration of variables. For each element in the array, provide a value
and these should be enclosed in curly braces, { }. And if there are more than one, separated by
commas. It is a compile error to specify more values than there are elements in the array.
10
22
44
10
22
44
C Language Programming
Page
49
all filled
with 0s
Inputting Values
Another way to fill the array is to read the values from the keyboard or a file. This can be
done using a loop. When the array is going to be completely filled, the most appropriate
loop is the for loop because the number of elements are fixed and known.
Example:
int score[5];
.
.
for (x = 0; x < 5; x++)
scanf(%d, &score[x]);
Interpretation:
Several concepts need to be studied in this simple statement. First, we begin the index
, x at zero. Since there are five elements in the array, we must load the values from index
locations zero through 4. the limit test, therefore, is set at x < 5, which conveniently is the
number of elements in the array. Then, even though we are dealing with array elements,
the address operator (&) is still necessary in the scanf call.
Finally, when there is a possibility that all the elements are not going to filled, then
one of the event-controlled loops should be used. Which you use would depend on the
application.
Assigning Values
Individual elements can be assigned values using the assignment operator. Any value
that reduces to the proper type can be assigned to an individual array element.
Example:
double x[8];
array x
x[0]
x[1]
x[2]
x[3] x[4]
16.0
12.0
6.0
25.0
8.0
x[5]
x[6]
11.0
14.0
x[7]
24.0
Explanation
Displays the value of x[0], which is 16.0.
Stores the value 25.0 in x[3].
C Language Programming
Page
50
Enter a String:
Elsa
aslE
C Language Programming
Page
51
Enter 5 numbers :
14352
The numbers in ascending
order
12345
C Language Programming
Page
52
}
}
getch();
8910
8910
8910
12345
246810
3691215
48121620
510152025
C Language Programming
Page
53
for (ctr2=0;ctr2<=4;ctr2++)
printf("%d",num[ctr][ctr2]);
printf("\n");
}
getch();
}
clrscr();
printf("Enter Number in 3 x 3 matrix :");
cols=5; rows=2;
for (x=0;x<=2;x++)
{
for (y=0;y<=2;y++)
{
gotoxy(cols,rows);
scanf("%d",&num[x][y]);
cols+=3;
}
cols=5;rows++;
}
for (y=0;y<=2;y++)
for (x=0;x<=2;x++)
{
a_row[y]=a_row[y] + num[y][x];
a_col[x]=a_col[x] + num[y][x];
}
cols=5;
for(x=0;x<=2;x++)
{
gotoxy(cols,7); printf("%d",a_row[x]);
gotoxy(cols,8); printf("%d",a_col[x]);
cols+=3;
}
getch();
}
C Language Programming
Page
54
Types of Streams:
Text Stream is a sequence of characters that does not have a one-to-one relationship
between the characters that are written or read and those on the external device.
Binary Stream is a sequence of bytes that have a one-to-one correspondence to those found
on the external device. The number of bytes written or read will be the same as the number
found on the external device.
1.
2.
FILE
a collection of data stored in the memory.
Files reside in the secondary memory
Text file
Binary file
MS Word Documents
Excel Spreadsheets
Database files
C Language Programming
Page
55
Operations in a File
1.
2.
3.
4.
Open a file.
Close a file.
Read the contents of a file.
Write to a file.
Opening Files
fopen() function - opens a stream for use, links a file with that stream, and then returns a FILE pointer
to that stream. Most often, the file is a disk file.
Syntax:
InternalFileName = fopen (ExternalFileName, OpenMode);
where:
InternalFileName is a variable which represents the file in the program.
ExterbalFileName is the actual namr of the file that is being opened.
OpenMode is the mode pointing to a string containing the desired status.
C Language Programming
Page
56
Open
Mode
r
w
a
rb
wb
ab
r+
w+
a+
Meaning
Open
Mode
Meaning
r+b
w+b
a+b
rt
wt
at
r+t
w+t
a+t
If you wish to open a file for writing with the name TIPQC.TXT, write
fp = fopen (TIPQC.TXT,w);
Note:
TIPQC
Hello
C Language Programming
Page
57
fputc(l, fp);
fputc(l, fp);
fputc(o, fp);
fputs() writes a string to a stream.
Syntax:
fputs(StringExpression,InternalFileName);
Output:
Technological Institute of the Philippines
CS/IT/IM Department
Example:
fputs(Technological Institute of the Philippines\n,fp);
fputs(CS/IT/IM Department, fp);
Example:
Assume that we declare the variable outdata as
And open it in the output mode
FILE *outdada:
outdata = fopen (A:\OUT.TXT, w);
Statement
Output
10
1020
15.750000
xy
xy
C Language Programming
10 20 15.750000 x
C Language Programming
C Language Programming
Page
58
2. fscanf(fp,%s, &svar);
3. while (!feof(fp)) {
fscanf(fp, %c, &a);
printf(%c, a);
}
retrieves the contents of the file pointed by the file pointer one
at a time and displays them on the screen.
2. while (!feof(fp)) {
a = fgetc(fp);
printf(%c, a);
}
retrieves the contents of the file pointed by the file pointer one
at a time and displays them on the screen.
/* --------ADDING
TEXT
TO FILE------*/
/* --------READING TEXT FROM A FILE-----*/
fgets(p,3,
fp);
/*-------------ADDTXT.C---------------*/
/*-------------READTXT.C---------------*/
printf(%s, p);
displays TIP
to the screen.
#include <stdio.h>
main()
#include <stdio.h>
main()
{
FILE *fp;
char str[80];
FILE *fp;
char a;
clrscr();
printf(Enter String:);
gets(str);
clrscr();
if((fp=fopen)TIPQC.TXT,r))==NULL)
{
if((fp=fopen)TIPQC.TXT,w))==NULL)
{
puts(Cannot Write File!);
exit(0));
}
fprintf(fp, %s\n,str);
fclose(fp);
}
while (! Feof(fp))
{
a = fgetc(fp);
printf(%c, a);
}
fclose(fp);
getch();Technological Institute of the Philippines
}
C Language Programming
Page
59
In the example, the first program will ask the user to input a string. The string will then be saved in
the file TIPQC.TXT. the second program will retrieve the contents of the file and display them on the
screen. Note that the open mode used in the first program is w. This means that a new file will be
created every time the first program is executed. The previous contents of the file are replaced by the
new string entered.
You can use the open mode a to enable the file to append entries so that previous contents are not
lost and that new entries are added to the file.
feof() checks for end-of-file status during input.
Syntax:
feof(InternalFileName);
Example: