Unit 5
-
Upload
rohassanie -
Category
Technology
-
view
259 -
download
0
Transcript of Unit 5
![Page 1: Unit 5](https://reader036.fdocuments.net/reader036/viewer/2022082808/555e364cd8b42aad058b486b/html5/thumbnails/1.jpg)
F1001 PROGRAMMING FUNDAMENTALS
STRUCTURE OF C PROGRAM
Basic Concepts of C Programming
Important Elements In A C Program
Data and Variables
Input and Output
70
UNIT
5
![Page 2: Unit 5](https://reader036.fdocuments.net/reader036/viewer/2022082808/555e364cd8b42aad058b486b/html5/thumbnails/2.jpg)
F1001 PROGRAMMING FUNDAMENTALS
INTRODUCTION
In this unit students are introduced to a simple C program. The unit describes the important elements of a
C program and the types of data that can be processed by C. It also describes C statements for performing
tasks such as getting data from the user and displaying the data on screen. Here students will be presented
with examples that illustrate many important features of C programming.
At the end of this unit, students should be able to write simple C programs in accordance to the rules and
conditions of C programming. By this time, they should know the ways to declare variables, use variables
and understand the naming conventions of variables and print outputs. Students should also have enough
knowledge to write clear, well documented and error free codes at the end of this chapter.
Basic C program structure
71
NOTES
The curly braces “{ }” symbol shows the body of the program body. Any code/statements must
be written inside the body.
/* Example of basic C program Structure */
#include <stdio.h>
#define MAX 20
void main()
{
const PI = 3.142;
char letter;
int number;
huruf = ‘A’;
printf(“Enter one number : “);
scanf(“%d”, &number);
}
Comments
Header File
Main Function
Pre-processor commands
Data Type
Constant
Start of main function
Output Function
Input Function
Variable
End of main function
![Page 3: Unit 5](https://reader036.fdocuments.net/reader036/viewer/2022082808/555e364cd8b42aad058b486b/html5/thumbnails/3.jpg)
main() { char b;
b = ‘A’; }
(i) head
(ii) body
F1001 PROGRAMMING FUNDAMENTALS
Comments
A line starting with /* and ending with */ is a comment.
The purpose of a comment is to document and understand the program. It can be used to tell what is
the purpose of using variables or functions. It also enables your program to be easily understood by
others.
Comment will not be executed by the compiler.
A good programming practice is to have comments in the program
Main function and functions
Every C program contains a main function which is called main()
Program execution starts from this main function.
main() function has two parts:
HEAD
Every function must have a header.
Function header is the name of that function.
main() function has a fixed name.
We cannot change the name of main() function
BODY
Every function must have a body which starts
with an open curly bracket ‘{’ and ends with a
close curly bracket ‘}’.
Every body function contains a program
statement.
A program statement will perform certain
tasks such as receiving value, display value,
calculation and so on.
72
Examples :
/* this is a comment *//* This is also a comment */
![Page 4: Unit 5](https://reader036.fdocuments.net/reader036/viewer/2022082808/555e364cd8b42aad058b486b/html5/thumbnails/4.jpg)
F1001 PROGRAMMING FUNDAMENTALS
Pre-processor Commands
#include <stdio.h>
# Lines starting with the ‘#’ symbol is processed by the pre-
processor, before compiling the program.
#include Is known as pre-processor directive.
Each pre-processor directive has its own header file.
Pre-processor directive gives instruction so that manipulation
can be done on the programs. Example, by instructing the
processor to include other files that are needed by the program.
<stdio.h> Used for the process of displaying output on the screen or getting
input from the user via the keyboard ( example printf and scanf)
#define AGE 22
# Lines starting with the ‘#’ symbol is processed by the pre-
processor, before compiling the program.
#define It does a search-and-replace command on a word processor (editor)
AGE Name of constant
Usually written in CAPITAL letters
22 Value assigned to AGE
Examples of Header Files in C programming
73
#define <constant name> <constant value>
#include <FileName>
or
![Page 5: Unit 5](https://reader036.fdocuments.net/reader036/viewer/2022082808/555e364cd8b42aad058b486b/html5/thumbnails/5.jpg)
F1001 PROGRAMMING FUNDAMENTALS
Data and Variables
HEADER FILES
LIBRARY FUNCTIONS
USES
stdio.h scanf()
printf()
gets()
getchar()
puts()
Receives input from keyboard
Displays output on screen
Receives input in the form of string Receives a character as input Displays output in string form
math.h pow(x,y)
sqrt(x)
exp(x)
Computes the value of x raised to the power of y
Computes the square root of x
Computes the exponent value of x
ctype.h isalnum(c)
isdigit(c)
ispunct(c)
islower(c)
To test whether c is alphabetic or digit
To test whether c is a numeric
To test whether c is a punctuation mark
To test whether c is a lower case character
string.h strlen(c)
strncmp(c)
strtok(c)
strncpy(c)
To get the length of a string
Compares the part of two strings
Splits string into words
Copies one part of a chosen string
conio.h clrscr() Clears the output screen
74
![Page 6: Unit 5](https://reader036.fdocuments.net/reader036/viewer/2022082808/555e364cd8b42aad058b486b/html5/thumbnails/6.jpg)
F1001 PROGRAMMING FUNDAMENTALS
Data
Data is an array of facts that can be modified by the computer into useful forms for human beings.
DATA
NUMERIC
Contains all types of
numbers.
Data which can be used
for calculation.
Example: sums of
money, age, and distance
(e.g: 34, 50, and 1.01).
INTEGER
All positive and negative numbers including zero and
no decimal place.
Example: 0, +1, -10.
Integers are used to represent the counting of things.
Example: Numbers of month in a year (1,2,3…)
REAL NUMBER
Contains all real numbers.
The number will be stored in floating point.
Used for metric measurement, temperature and price.
Example: 1.0, 234.55, 20.30, 36.7.
NON NUMERIC
CHARACTER
Consists of all letters, numbers and special symbols.
Characters are surrounded by single quotation mark (‘
‘).
Example: ‘A’, ‘m’,’=’, ‘#’, ‘1’ or ‘ ‘.
STRING
A combination of one or more characters.
A string is surrounded by double quotation marks (“
“).
Example: (“WELCOME TO COSMOPOINT”) or
(“8758”).
LOGICAL VALUES
Used in making yes-or-no decisions (TRUE-or-
FALSE).
Example: To check 2 integers using If…Else control
structure.
Variables
75
![Page 7: Unit 5](https://reader036.fdocuments.net/reader036/viewer/2022082808/555e364cd8b42aad058b486b/html5/thumbnails/7.jpg)
F1001 PROGRAMMING FUNDAMENTALS
A variable is a place to store a piece of information. Just as you might store a friend’s phone
number in your own memory.
Each variable has:
1. Name
2. Type
3. Holds a value that you assign to them
Naming Variables Must begin with a letter of the alphabet but, after the first letter,
it can contain:
1. Letters: A……Z, a……..z
2. Number : 0……9
3. Underscore character: _
Variable names are case-sensitive (example: the variable
"mYNUMBER" is different from the variable "MYNUMBER").
Cannot be more than 31 characters.
Variable names cannot be the same as the C reserved words.
Variable names cannot have spaces.
Examples : my age count 1 student 10
Variable names cannot have special characters (typographic
symbols).
Examples : ? / ~ @ + $
Valid Variables Names Examples : MyAge123, myAGE, My_Age, my_age, NAME,
Name.
Invalid Variable Names
Examples: MY AGE, 4_stu, my age, printf, 81_sales,
Aug91+Sales, Age?
Defining Variables Syntaks :
Examples : int number; float money;
Assigning Values To Variables
Syntaks :
Examples : number = 32; money = 30.50;
Data Types
Data type is the type of data that will be stored in the memory location.
76
DataType VariableName;
VariableName = Expression
![Page 8: Unit 5](https://reader036.fdocuments.net/reader036/viewer/2022082808/555e364cd8b42aad058b486b/html5/thumbnails/8.jpg)
F1001 PROGRAMMING FUNDAMENTALS
DATA TYPE USES EXAMPLE CODE
int int is used to define integer
numbers.
int Count;
Count = 5;
float float is used to define floating point
numbers.
float Miles;
Miles = 5.6;
double A double is used to define BIG
floating point numbers. It reserves
twice the storage for the number.
double Atoms;
Atoms= 2500000;
char A char defines characters.
char Letter;
Letter = 'x';
Variable Scope
There are two main variable scopes:
1. Local variable
2. Global variable
Local Variable
It is a variable that has been defined
immediately after the opening braces of a
Global Variable
A global variable is a variable that has been
defined before a function (usually before the
77
#include <stdio.h>
FunctionName(){
int A;
/*Block of one or more */ /*C statements*/
}
Local Variable
#include <stdio.h>
char B;
FunctionName(){ int A;
/*Block of one or more */ /*C statements*/
}
Global Variable
![Page 9: Unit 5](https://reader036.fdocuments.net/reader036/viewer/2022082808/555e364cd8b42aad058b486b/html5/thumbnails/9.jpg)
F1001 PROGRAMMING FUNDAMENTALS
function.
Each functions can have their own variables
declarations.
You can access (and change) local variables
only from the functions in which they are
defined. Therefore that variable's scope is
protected.
All local variables lose their definition when
their block ends.
main() function).
This means, all function in that program can
use this variable.
Global variables can be used anywhere in
the program as soon as it has been defined.
Character And String Array
Array is a list of variables or constants, and most programming languages allow the use of such lists.
A character array is the place to hold strings of information.
How to define strings data type
A string is a collection of characters to represent a name
(mother, father, student, employee, car, building, shopping
complex, software), address and extra.
Syntaks:
Example to declare character array:
char employeeName [30];
A string must be stored in character arrays, but not all
character arrays contain a string.
Contoh :
is not the same as
78
char variableName [STRING_LENGTH];
string
char name[9] = "Muhammad";
char name[8] = {'M', 'u', 'h', 'a', 'm', 'm', 'a', 'd'};
Data Type
Variable Name String length Character array
![Page 10: Unit 5](https://reader036.fdocuments.net/reader036/viewer/2022082808/555e364cd8b42aad058b486b/html5/thumbnails/10.jpg)
F1001 PROGRAMMING FUNDAMENTALS
Constant
The value of constant remains unchanged for the whole duration of the program execution.
Every constant has :
1. Name
2. Type
3. Values that are set to them
Syntax :
Examples :const double PI = 3.1459;#define PI 3.1459
Character Conversion
This sign % is known as conversion character in C language.
Conversion character is used to tell the input function (scanf()) and the output function (printf())
about how the data is being accepted or viewed.
Examples of usage (input function):
int a; char b; char c[5]; float d;
scanf(“%d”, &a); scanf(“%c”, &b); scanf(“%s”, c); scanf(“%f”, &d);
Examples of usage (output function) :
printf(“Integer %d”, a); printf(“Aksara Tunggal %c”, b);
printf(“Rentetan %s”, c); printf(“Titik apung %f”, d)
79
%d decimal integer
%s string
%c character
%e exponential notation floating point number
%f float
%g use the short if %f or %e
%u unsigned integer
%o octal integer
%x hexadecimal integer
%% percent sign (%)
const data_type constant_name = constant_value;
or
#define constant_name constant_value
![Page 11: Unit 5](https://reader036.fdocuments.net/reader036/viewer/2022082808/555e364cd8b42aad058b486b/html5/thumbnails/11.jpg)
F1001 PROGRAMMING FUNDAMENTALS
Input And Output
Input Function
Use the scanf(), gets(), getc() and
getchar() function from the stdio.h.
One of way to get input is by asking the
user to enter values into the variables using
the keyboard.
It contains conversion characters.
The conversion character explains to C
what data type to be inserted by user.
Syntax :
CC – Conversion Character
Output Function
Use the printf(), puts() and putchar()
function from stdio.h
This function sends all the output to the
screen.
Syntax :
CS: Control String – a combination of string and
conversion character
80
scanf(“CC”, &variablename);
#include <stdio.h>
main(){
char name [35];
/*Input*/printf(“Enter name :”);scanf(“%s”, name);
}
printf(“CS”,variablename)printf(“CS”,variablename)
#include <stdio.h>
main (){ int age; /*Input*/ printf(“Your age ?”); scanf(“%d”, &age); /*Output*/ printf(“Your age : %d years”, age);}
Control String