Programming 1 Presentation
Programming 1 Presentation
Turbo C
Prepared by:
Roel Lauron
A programming language is an
artificial language that can be used
to control the behavior of a
machine, particularly a computer.
Programming Language Translation
1. Syntax Errors
- occurs when your code violates one or more
grammar rules of C and is detected by the
compiler as it attempts to translate your
program.
Note: If a statement has a syntax error, it cannot
be translated and your program will not be
executed.
Common Programming Errors
2. Run-time Errors
- are detected errors and displayed by the
compiler during the execution of the program.
- occurs when the program directs the
computer to perform illegal operation, such as
dividing a number by zero.
- an attempt to perform an invalid operation,
detected during program execution.
Note: When a run-time error occurs, the
computer will stop executing your program
and will display a diagnostic message that
indicates the line where the error was
detected.
Common Programming Errors
3. Logic Errors
- occur when a program follows a
faulty algorithm.
- do not cause a run-time error and
do not display error messages, so are
very difficult to detect.
C Language
one of the most popular languages
of modern times.
Programs written in C are portable
across different environments
Applications created using the C
language range from operating
systems to database systems.
FIGURE 2-1 Taxonomy of the C Language
C Programming Language
C is a programming language
designed by Dennis Ritchie in 1972
at AT&T Bell Laboratories.
C was designed as a language for
systems programming, as a way to
fully access the computer’s power
without becoming caught up in the
tedious writing of assembly
language.
General Description of C
C is a concise language
it has only about 32
keywords
it encourages concise code.
General Description of C
C is a modular language
The function is the primary
program structure, but
functions may not be nested.
The C programmer depends
on a library of function, many
of which becomes part of the
standard language definition.
General Description of C
C is weakly typed
allowing quite a bit of data
conversion and providing
minimal run time checking.
C Language Elements
Function Main
Every C program has a main function. This
is where program execution begins.
Body- the remaining line of the program in
the body.
Braces {} – enclose the body of the
function.
- indicates the beginning and end of the
function main.
C Language Elements
Two parts of the function body:
1. Declarations – the part of the program
that tells the compiler the names of
memory cells in a program needed in
the function, commonly data
requirements identified during problem
analysis.
2. Executable statements – derived
statements from the algorithm into
machine language and later executed.
FIGURE 2-2 Structure of a C Program
C Language Elements
Your First Program
#include <stdio.h>
#include <conio.h>
main()
{
printf("Hello World!\n");
getch();
}
C Language Elements
Reserved Words
In C, a reserved word is defined as
the word that has special meaning
in C and cannot be used for other
purposes.
double
int
FIGURE 2-6 Nested Block Comments Are Invalid
Variables, Data Types and Constants
Modifiers
The three data types above have the following
modifiers.
short
long
signed
unsigned
Examples:
1. Character constants – enclosed
between single quotes. Ex. ‘A’, ‘+’
2. Integer constants – specified as
numbers without fractional components.
Ex. 5 and -160
Variables, Data Types and Constants
Unary Operators
- changes the sign of a value or
variable.
- Unary minus (-) and unary plus
(+)
Examples:
2 +-3
((-x) + (+y))
Operators
Increment (++) and Decrement (--)
Operators
Prefix increment
is when the ++ is placed immediately
in front of its operand.
the value of the expression is the
variable’s value after incrementing.
Increment (++) and Decrement(--)
Operators
Postfix increment
is when the expression’s value is the
value of the variable before it is
incremented.
Increment (++) and Decrement(--)
Operators
Prefix Postfix
After… x y x y
5 6 5 5
Example
main(){
int a=3, b;
clrscr();
b=a++;
printf(“b is %d, and a is %d\n”, b, a);
b=++a;
printf(“Now b is %d, and a is %d\n”, b, a);
b=5%--a;
printf(“Now b is %d, and a is %d\n”, b, a);
printf(“Now b is %d, and a is %d\n”, ++b, a--);
printf(“Now b is %d, and a is %d\n”, b, a);
}
Output
b is 3, and a is 4
Now b is 5, and a is 5
Now b is 1, and a is 4
Now b is 2, and a is 4
Now b is 2, and a is 3
Operators
Prefix increment/decrement - when the
++ or -- is placed immediately in front of
its operand. Meaning the value of the
expression is the variables value after
incrementing or decrementing.
Example:
gets(name);
I/O Functions
Output Command
Example:
putchar(a);
Introduction to C Programming
CONTROL FLOW
Control Flow
Control Structures - specify the sequence of
execution of a group of statements.
3 Types:
1. Sequential
2. Conditional
3. Iterative
A flowchart is a diagrammatic
representation that illustrates the sequence
of operations to be performed to get the
solution of a problem. Flowcharts are
generally drawn in the early stages of
formulating computer solutions. Flowcharts
facilitate communication between
programmers and business people.
documentation of a complex program.
Guidelines in Flowcharting
1. In drawing a proper flowchart, all
necessary requirements should be
listed in logical order.
2. Flowchart should be clear, neat and
easy to follow.
3. The usual direction of the flow of a
procedure or system is from left to
right or top to bottom.
4. Only one flow line should come out
from a process symbol.
Guidelines in Flowcharting
5. Only one flow line should enter a decision
symbol, but 2 or more flow lines, one for
each possible answer, should leave the
decision symbol.
6. If flowchart becomes complex, it is better
to use connector symbols to reduce the
number of flow lines. Avoid the intersection
of flow lines.
7. Ensure that flowchart has a logical start
and end.
8. It is useful to test the validity of the
flowchart by passing through it with a
simple test data.
Advantages of Flowchart
1. Communication
flowcharts are better way of
communicating the logic of a system to
all concerned.
2. Effective analysis
with the help of flowchart, problem can
be analyzed in more effective way.
3. Proper documentation
flowcharts serve as a good program
documentation.
Advantages of Flowchart
4. Efficient coding
flowcharts act as a guide or blueprint
during the system analysis and program
development phase.
5. Proper Debugging
flowchart helps in debugging process
6. Efficient program maintenance
maintenance becomes easy with. It helps
the programmer to put efforts more
efficiently on that part.
Limitations of Flowcharts
1. Terminal Symbol
- used to designate the beginning and end
of a program.
2. Input Symbol or
- represents an instruction to an input
device
3. Processing Symbol
- used to represent a group of program
instructions that perform a processing
function or activity such as mathematical
operations or logical comparisons.
Algorithms and Flowcharting
Flowchart Symbols:
4. Output Symbol or
- represents an instruction to an
output device.
5. Decision Symbol
- denotes a point in the program
where more than one path can be
taken or used to designate a decision
making process.
Algorithms and Flowcharting
Flowchart Symbols:
9. Predetermined Symbol
- used as a subroutine symbol
- inner procedure needs to be repeated
several times.
Most Commonly Used Symbol
Sample Flowchart
Sample Flowchart
Sample Flowchart
Sample Flowchart
Sample Flowchart
System Flowcharts
High-Level Flowchart
A high-level (also called first-level or top-down) flowchart shows the major
steps in a process. It illustrates a "birds-eye view" of a process, such as
the example in the figure entitled High-Level Flowchart of Prenatal Care. It
can also include the intermediate outputs of each step (the product or
service produced), and the sub-steps involved. Such a flowchart offers a
basic picture of the process and identifies the changes taking place within
the process. It is significantly useful for identifying appropriate team
members (those who are involved in the process) and for developing
indicators for monitoring the process because of its focus on intermediate
outputs.
Most processes can be adequately portrayed in four or five boxes that
represent the major steps or activities of the process. In fact, it is a good
idea to use only a few boxes, because doing so forces one to consider the
most important steps. Other steps are usually sub-steps of the more
important ones.
Detailed Flowchart
Assignment
End
main()
{
int year;
printf("Enter a year(ex: 2005):");
scanf("%d", &year);
if(year%4==0)
{
if(year%100==0)
{
if(year%400==0)
printf("The year %d is a LEAP YEAR", year);
else
printf("The year %d is NOT A LEAP YEAR", year);
}
else
printf("The year %d is a LEAP YEAR", year);
}
else
printf("The year %d is NOT A LEAP YEAR", year);
getch();
Problem 14
128
Example
Loop types (reminder)
Indefinite Loop:
You do not know ahead of time how many
times your loop will execute.
For example, you do not know how many
books a person might order.
Definite Loop:
You know exactly how many times you want
the loop to execute.
not at compile time necessarily
130
Write a program that will allow the user to
input an integer value. If the value is
greater than or equal to zero, print the word
“POSITIVE”.
Control Flow
Control Structures - specify the sequence of
execution of a group of statements.
3 Types:
1. Sequential
2. Conditional
3. Iterative
if Selection Structure
- performs an indicated action only
when the condition is true, otherwise
the action is skipped.
Syntax: if (<expression>)
<statement>
T Statement
Condition
Example:
Write a program that will allow the user to input an
integer value. If the value is greater than or equal to
zero, print the word “POSITIVE”.
Begin
num
if “POSITIVE”
num>=0
End
Control Flow
Other Problems:
1. Write a program that will allow the user
to input a number. Print the word
NEGATIVE if the number is a negative
value.
2. Write a program to input two integers.
Thereafter, the program should determine
if these two numbers are equivalent. If
they are equivalent, print the word
EQUIVALENT.
3. Write a program that will input an integer
and determine if it is an even number.
Control Flow
else n
F
statement;
Statement
Control Flow
Example:
Nested-if Statement
Syntax:
if (condition)
{
if (condition)
statement;
else
statement;
}
Good Programming Practice
A nested if...else statement can
perform much faster than a series
of single-selection if statements
because of the possibility of early
exit after one of the conditions is
satisfied.
In a nested if...else statement, test the
conditions that are more likely to be
true at the beginning of the nested
if...else statement. This will enable the
nested if...else statement to run faster
and exit earlier than testing
infrequently occurring cases first.
Good Programming Practice
Example
Switch Statement
Is a selection statement
provided by C. It has a built in
multiple branch and work
similar to if else ladder
generally.
Control Flow
Switch Statement
- the controlling expression, an
expression with a value of type int
or type char, is evaluated and
compared to each of the case labels
in the case constant until a match is
found. A case constant is made of
one or more labels of the form case
followed by a constant value and a
colon.
Control Flow
It is defined by C that a
complier must support a
minimum of 257 case
statements in C89 and 1023
case statements in C99
though you may want to keep
this to minimum in
consideration of efficiency.
Control Flow
Switch Statement
Syntax:
switch (controlling expression)
{
case constant: statement;
break;
case constant: statement;
break;
. . .
default: statement;
}
Control Flow
Break
#include<stdio.h>
int main()
{
int i;
while (i < 10)
{
i++;
if (i == 5)
break;
}
return 0;
}
Control Flow
Example
main()
{
int num1, num2, sum, diff, prod, choice;
printf("Enter the first number:");
scanf("%d", &num1);
printf("Enter the second number:");
scanf("%d", &num2);
printf("Enter your choice (1-> ADD, 2-> SUBTRACT, 3->MULTIPLY:");
scanf("%d", &choice);
switch(choice) {
case 1: {
sum=num1+num2;
printf("The sum of 2 numbers is %d", sum);
break;
}
case 2: {
diff=num1-num2;
printf("The difference between 2 numbers is %d", diff);
break;
}
case 3: {
prod=num1*num2;
printf("The product of 2 numbers is %d", prod);
break;
}
default:
printf("Wrong Choice!!!"); }
getch();
Problem 14
Depending on situation,
sometimes it is better to use one
kind of loop than another, but
every loop can be transformed
into one another.
Loops
3 Types:
1. do-while statement
2. while statement
3. for statement
Control Flow
do-while statement
Example:
c=1;
do
{
printf(“Hello World\n”);
c++;
} while (c<=5);
Control Flow
while statement
Example:
c=1;
while (c<=5)
{
printf(“Hello World\n”);
c++;
}
Control Flow
for statement
- a kind of loop command wherein the
execution of the statement does not
depend on another instruction.
Syntax:
for (initialization expression; loop repetition
condition; update expression)
{
statement/s;
}
Control Flow
Example
Definite Loop:
You know exactly how many times you
want the loop to execute.
not at compile time necessarily
178
Infinite Loop
179
Types of Loop
1. Priming
Set counter=1
FALSE
182
For Loop Variations
while (*)
{
/* repeating block of code */
}
do {
/* repeating block of code */
} while (*);
Where:
data_type – valid data type
array_name – any user-defined
identifier
size – number of elements in the array
Example: int num[5];
ARRAY
a data structure which hold multiple variables of
the same data type.
IN SHORT, ARRAY IS
–Structures of related data items
–Static entity – same size throughout
program
c[ 0 ], c[ 1 ]...c[ n – 1 ]
Arrays
num[0] -45
num[1] 2
num[2] 4
num[3] 72
num[4] 1
Types of Array
1. Single Dimensional
1. Multidimensional
Initialization of Array
The values in the list care separated by commas, for example the
statement
Initialization of Array
int number[3]={0,0,0};
int counter[]={1,1,1,1};
int n [ 10 ] = { 0 } ;
Initialization of Array
Storing String in Character Arrays
data_type array_name[row_size][column_size];
int m[10][20]
Example:
int table[2][3]={0,0,0,1,1,1};
int table[2][3]={{0,0,0},{1,1,1}}
Array elements are like normal
variables
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );
c[ 5 - 2 ] == c[ 3 ] == c[ x ]
Declaring multiple arrays of same
type
Example:
int b[ 100 ], x[ 27 ];
Points to Ponder
int n[ 5 ] = { 1, 2, 3, 4, 5 };
int n[ ] = { 1, 2, 3, 4, 5 };
Make a C program to
create an array of 5
numbers. Output the
numbers.
Solution:
Solution
#include <stdio.h>
main()
{
int x, num[5];
#include <stdio.h>
#include <conio.h>
main()
{
char word[20];
word[0]='H';
word[1]='e';
word[2]='l';
word[3]='l';
word[4]='o';
word[5]=‘\0’; //slash zero
printf("The contents of word[] is --> %s\n", word);
getch();
}
Example
#include <stdio.h>
main()
{
int x, num[5];
num[0]=1;
num[1]=2;
num[2]=3;
num[3]=4;
num[4]=5;
num[5]=0;
for(x=0; x<=5; x++)
{
printf("The contents of num[%d] is --> %d\n",x,
num[x]);
}
getch();
}
Problem
Make a C program to
create an array of 5
names. Output the
names.
Solution:
Solution
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
int x;
char name[5][15];
fflush(stdin);
for(x=0; x<5; x++)
{
fflush(stdin);
printf("Enter name%d:", x);
gets(name[x]);
}
fflush(stdin);
for(x=0; x<5; x++)
{
fflush(stdin);
printf("Name is %s", name[x]);
printf("\n");
}
getch();
}
/* Histogram printing program */
#include <stdio.h>
#define SIZE 10
main()
{
int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; /* Initialize array*/
int i, j;
printf( "\n" );
} /* End of for loop i */
getch();
} /* END Main Program */
Program Output:
3. Create an array of N
scores. Determine the
average and output all the
scores that are greater
than or the average scores.
Arrays
Sorting Arrays
Sorting data – placing the data into a
particular order such as ascending
or descending.
Example:
Write a program that sorts the
values in the elements of the 10-
element array a into ascending
order.
MULTI DIMENSIONAL ARRAYS
0 1
1 2
2 3
2-dimensional array
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
You do get 3-dimensional arrays and more but they are
not used as often. Here is an example of how you declare
a 2-dimensional array and how to use it. This example
uses 2 loops because it has to go through both rows and
columns.
int a[3][3],i,j;
for (i = 0;i < 3;i++)
for (j = 0;j < 3;j++)
a[i][j] = 0;
What is a Magic Square?
Definition, Special Properties
Complete steps
Method for constructing a magic square of odd
order
Example:
int func(int one, int two)
{
int sum;
sum=one + two;
return sum;
}
Functions
Functions Returning Values
The return keyword has two important
uses:
1. It can be used to cause an immediate exit
from the function it is in. That is, the
return will cause program execution to
return to the calling function as soon as it
is encountered.
2. It can also be used to return a value.
Two types:
1. Pass by value - a copy of the data is
passed to the subroutine, so that no
matter what happens to the copy the
original is unaffected.
2. Pass by reference - the variable
argument is renamed, not copied. Only
the address of the argument is passed
to the function.
C Pointers
Pointers – enable programs to simulate
call by reference, and to create and
manipulate dynamic data structures, i.e..
Data structures that can grow and
shrink, such as linked lists, queues,
stacks and trees.
Pointer – a variable that contain memory
addresses as their values.
- It contains an address of a variable
that contains a specific value.
C Pointers
Indirection – means referencing a value
through a pointer.
Declaration:
data_type *variable_name;
Ex:
int *ptr; /*means ptr is a pointer to an
integer value*/
* - indicates that the variable being
declared is a pointer.
C Pointers
Directly and Indirectly referencing a
variable.
count
count directly references a
7 variable whose value is 7
ptr count
ptr indirectly references a
7 variable whose value is 7
C Pointers
Pointer Operators
Address operator (&) – a unary operator
that returns the address of its operand.
Example:
int y = 5;
int *yptr;
yptr = &y; /* assigns the address of the
variable y to pointer variable yptr */
C Pointers
Graphical representation of a pointer to an
integer variable in memory.
500000
yptr y 500002 5 y
500004
5
500006
500008
500010 500002
500012
C Pointers
Indirection operator (*) – also known as
dereferencing operator, returns the value
of the object to which its operand (i.e., a
pointer) points.
Example:
printf(“%d”, *yptr); /* prints the value
of variable y which is 5 */
C Pointers