Sie sind auf Seite 1von 42

EKT120 Introduction to

Computer Programming
Lecture 2 – Introduction to C
Languge

20 Feb 2016 EKT120: Computer Programming 1


The C Language
C is a general
purpose language
Developed in 1972 by
Dennis M Ritchie at
the Bell Telephone
laboratories to
developed the UNIX
operating system.
First implementation
on DEC PDP-11
computer
20 Feb 2016 EKT120: Computer Programming 2
The C language
The most widely used programming language
together with JAVA programming language
Easy to learn
Structured language
It produces efficient programs.
It can handle low-level activities.
It can be compiled on a variety of computer
platforms

20 Feb 2016 EKT120: Computer Programming 3


Why use C
C was used for system development work - the
operating system.
Because it produces code that runs nearly as
fast as code written in assembly language.
Some examples of the use of C might be:
● Operating Systems ● Network Drivers
● Language Compilers ● Modern Programs
● Assemblers ● Databases
● Text Editors ● Language Interpreters
● Print Spoolers
20 Feb 2016
● Utilities
EKT120: Computer Programming 4
Sample C Program
Comment
/*Program name : program1.c
Programmer : Salina
This program calculates the area of triangle*/ Preprocessor declaration
#include <stdio.h> Void – means no input to
run the program
int main(void)
{ Begin / start
double dBase, dHeight, dArea;
Variable declaration
printf(“Enter base length : “);
scanf(“%f”, &dBase);
Program body – all the
printf(“Enter height length : “); program structures that
scanf(“%f”, &dHeight); needed for the program
(processes, input,
dArea=0.5 * dBase * dHeight; decision, loop, display
printf(“\nArea of the triangle is : %5.2f\n”, dArea);
Return a value to OS
return 0;
}
End program
20 Feb 2016 EKT120: Computer Programming 5
Program Comments
There are two kinds of comment
Block comment
Line by line comment
Block comment starts with /* and terminates
with */
Line by line comment use character // at the
beginning of comment line

20 Feb 2016 EKT120: Computer Programming 6


Preprocessor Directives
An instruction to include any pre-processor in the C
language
It is include standard library headers for example
<stdio.h>, <math.h>, <string.h>, <stdlib.h>
The command is #include <stdio.h>
The hashtag symbol is used to include the preprocessor
directive in the program
The standard library of stdio.h is a library for input output
commands that can be used to display and get input

e.g scanf – to get input and printf – to display output on
the computer monitor
math.h – library for complex mathematical function

e.g power function etc.
20 Feb 2016 EKT120: Computer Programming 7 7
Variables
Variables or Identifiers are:
labels for program elements
In C program they are “case sensitive”
Variable name can consist of capital letters[A..Z],
small letters[a..z], digit[0..9], and underscore
character _
The first character MUST be a letter or an
underscore
Blank is prohibited

e.g my book – should be mybook or my_book
Variable cannot same with Reserved Words

20 Feb 2016 EKT120: Computer Programming 8


Reserved Words
Are words already use by the C Compiler,and
have their own meaning in the program
(refer to program example)
● e.g.: main, void, double, printf, scanf, return, include,

void

20 Feb 2016 EKT120: Computer Programming 9


Variables
An identifier for the data in the program
Hold the data in your program
Is a location (or set of locations) in
memory where a value can be stored
A parameter that can change during
program execution

20 Feb 2016
UniMAP Sem I-13/14 EKT120: Computer Programming 10
Constants Variable
There are two kinds of variable
Variable that can change during the running
program
Variable that cannot change during the running
program
Constant is variable which can not change
during the program execution.
Example:
const double dPi=3.141592;

20 Feb 2016 EKT120: Computer Programming 11


Data Types
Every variable must belong to a data type. Example data
type:
Integer, floating point, character, string etc
Each data types has their own physical characteristic:
Number of bytes it occupies in memory
Range of data
Operations that can be performed on the data
There are modifiers which alter the meaning of the base
data type to more precisely fit a specific need C language
supports example modifiers type:
short, long, signed, unsigned
It is usually use as – short integer, long integer etc

20 Feb 2016 EKT120: Computer Programming 12


Data Types & Memory Allocation
Type Bits Bytes Range
Char or Signed Char 8 1 -128 to +127
Unsigned Char 8 1 0 to +255
Int or Signed int 32 4 -2,147,483,648 to
+2,147,483,647
Unsigned int 32 4 0 to +4,294,967,295
Short int or Signed 16 2 -32,768 to + +32,767
short int
Unsigned short int 16 2 0 to +65,535
Long int or signed long 32 4 -2,147,483,648 to
int +2,147,483,647
Unsigned long int 32 4 0 to +4,294,967,295
Float 32 4 .4 e-38 to 3.4 e+38
Double 64 8 1.7e-308 to 1.7e+308
20Long Double
Feb 2016 64 Computer Programming
EKT120: 8 1.7e-308 to 1.7e+308 13
Variables Naming Conventions
Variable names should use Hungarian notation
Start with an appropriate prefix that indicates the
data type
After the prefix, the name of variable should have
ore or more words
The first letter of each word should be in upper
case
The rest of the letter should be in lower case
The name of variable should clearly convey the
purpose of the variable
20 Feb 2016 EKT120: Computer Programming 14
Naming Variables According to
Standards
Prefix Data Type Example
i int and unsigned int iTotalScore
f float fAverageScore
d double dHeight
l long and unsigned long lFactorial
c signed char and unsigned char cProductCode

ai Array of integer aiStudentId


af Array of float afWeight
ad Array of double adAmount
al Array of long integer alSample
ac Array of characters acMaterial

20 Feb 2016 EKT120: Computer Programming 15


Variable Declaration
Before variable can be use in a program it
must be declared first.
Example of command to use are:
float fIncome;
float fNet_income;
double dBase, dHeight, dArea;
Declare and
int iIndex =0, iCount =0; initialize

char cCh=‘a’, cCh2; Named constant


const float fEpf = 0.1, fTax = 0.05; declared and
initialized

20 Feb 2016 EKT120: Computer Programming 16


Variable declaration
To declare variable with integer data type
int counter
To declare floating point number
float CGPA;
To declare character
char abjad;

20 Feb 2016 EKT120: Computer Programming 17


Types of Operators
Operators in C language include:
Arithmetic operators (+ , - , * , / , %)
Relational operators (> , < , == , >= , <=, !=)
Logical operators (&& , ||)
Compound assignment operators (+=, -=, *=, /=, %=)
Binary operators are operator need two
operands e.g no1 + no2 (no1 and no2 are
operands
Unary operators are operators need single
operand e.g counter++
Bitwise operators use to executes on bit level
20 Feb 2016 EKT120: Computer Programming 18
Arithmetic Operators
Used to execute mathematical equations
The result is usually assigned to a data
storage (instance/variable) using assignment
operator ( = )
E.g.
sum = marks1 + marks2;

20 Feb 2016 EKT120: Computer Programming 19


Arithmetic Operators

C Operation Arithmetic Algebraic C Expression


Operator Expression
Addition + f+7 f+7
Subtraction - p–c p-c
Multipication * bm b*m
Division / x/y x/y
Remainder % r mod s r%s
(Modulus)

20 Feb 2016 EKT120: Computer Programming 20


Operator Precedence
Operators Precedence
! + - (unary operators) first
* / % second
+ - (binary operators) third
< <= >= > fourth
== != fifth
&& sixth
|| seventh
= last

20 Feb 2016 EKT120: Computer Programming 21


Exercise
Write a program to display hello world
Write a program to ask user to input his/her
name, then display it on the screen.
Write a c program that will ask user to
input an integer number then your
program will calculate and display the
square of the input number
Write a program to input two integer
number, add the two integer and display
the result on screen
20 Feb 2016 EKT120: Computer Programming 22
Answer
1. #include <stdio.h>
int main (){
printf(“Hello World”);
}

2. #include <stdio.h>
int main(){
char name[20];
scanf(“%s”,name);
printf(“Your name is %s”,name);
}
20 Feb 2016 EKT120: Computer Programming 23
Relational and Logical Operators
Previously, relational operator:
>, < >=, <=, == , !=
Previously, logical operator:
&&, ||
Used to control the flow of a program
Usually used as conditions in loops and
branches

20 Feb 2016 EKT120: Computer Programming 24


More on relational operators
Relational operators use mathematical
comparison (operation) on two data, but give
logical output
e.g.1 let say b = 8, if (b > 10)
e.g.2 while (b != 10)
e.g.3 if (mark == 60) print (“Pass”);
Reminder:
DO NOT confuse == (relational operator)
with = (assignment operator)

20 Feb 2016 EKT120: Computer Programming 25


More on logical operators
Logical operators are manipulation of logic.
For example:
b=8, c=10,
if ((b > 10) && (c<10))
while ((b==8) || (c > 10))
if ((kod == 1) && (salary > 2213))

20 Feb 2016 EKT120: Computer Programming 26


Truth Table for && (logical AND)
Operator
exp1 exp2 exp1 && exp2

false false false

false true false

true false false

true true true

20 Feb 2016 EKT120: Computer Programming 27


Truth Table for || (logical OR)
Operator
exp1 exp2 exp1 || exp2

false false false

false true true

true false true

true true true

20 Feb 2016 EKT120: Computer Programming 28


Compound Assignment Operators
To calculate value from expression and store it in
variable, we use assignment operator (=)
Compound assignment operator combines binary
operator with assignment operator
E.g. val +=one; is equivalent to val = val +
one;
E.g. count = count -1; is equivalent to

count -=1;

count--;

--count;
20 Feb 2016 EKT120: Computer Programming 29
Unary Operators
Obviously operating on ONE operand
Commonly used unary operators
Increment/decrement { ++ , -- }
Arithmetic Negation { - }
Logical Negation { ! }
Usually using prefix notation
Increment/decrement can be both a prefix and
postfix

20 Feb 2016 EKT120: Computer Programming 30


Comparison of Prefix and Postfix Increments

20 Feb 2016 EKT120: Computer Programming 31


Unary Operators (Example)
Increment/decrement { ++ , -- }
prefix:value incr/decr before used in expression
postfix:value incr/decr after used in expression

val=5; Output: val=5; Output:


printf (“%d”, ++val); 6 printf (“%d”, --val); 4

val=5; Output: val=5; Output:


printf (“%d”, val++); 5 printf (“%d”, val--); 5

20 Feb 2016 EKT120: Computer Programming 3232


Output Formated

20 Feb 2016 EKT120: Computer Programming 33


Formatted Output with “printf”
#include <stdio.h>
Declaring variable (fMonth) to be integer
void main (void)
{ Declaring variables (fExpense and fIncome) to
be real
int iMonth;
float fExpense, fIncome; Assignment statements store numerical values
in the memory cells for the declared variables
iMonth = 12;
‘,’ separates string literal from
fExpense = 111.1;
variable names
fIncome = 1000.0;
printf (“Month=%2d, Expense=$%9.2f\n”,iMonth,fExpense);
} Correspondence between variable names
and %...in string literal

20 Feb 2016 EKT120: Computer Programming 34


Formatted Output with printf-cont
printf (“Month= %2d, Expense=$ %9.2f \n” ,iMonth,
fExpense);
%2d refer to variable iMonth value.
%9.2f refer to variable fExpense value.
The output of printf function will be displayed as

20 Feb 2016 EKT120: Computer Programming 35


Formatted input with scanf

20 Feb 2016 EKT120: Computer Programming 36


Formatted input with scanf-cont

20 Feb 2016 EKT120: Computer Programming 37


Program Debugging
Syntax error
Mistakes caused by violating “grammar” of C
C compiler can easily diagnose during compilation
Run-time error
Called semantic error or smart error
Violation of rules during program execution
C compiler cannot recognize during compilation
Logic error
Most difficult error to recognize and correct
Program compiled and executed successfully but answer
wrong

20 Feb 2016 EKT120: Computer Programming 38


Program debugging-syntax error
snapshot

20 Feb 2016
UniMAP Sem I-13/14 EKT120: Computer
EKT120: Programming
Computer Programming 39
Program debugging-run time error
snapshot

20 Feb 2016 EKT120: Computer Programming 40


Program debugging-logic error
snapshot

20 Feb 2016
UniMAP Sem I-13/14 EKT120: Computer
EKT120: Programming
Computer Programming 41
Q&A

20 Feb 2016 EKT120: Computer Programming 42

Das könnte Ihnen auch gefallen