Sie sind auf Seite 1von 25

C Programming

by Zulkhairi Mohd Yusof Rev 1.0

The following concept will be introduced, examples will be shown and exercises will be given DIGS (basic), CDR (advanced) and FPASS (professional). DIGS Declare, Initialize, Get from user and Show CDR Compute, Decide and Repeat FPASS Function, Pointers, Array, String and Structure 1st concept. Computer as storage area (memory). There are three types of storage bin (data types).

Int

float

char

There are three types of data (constants).

3.14
(decimal point) Float / real

255
(x decimal point) integer

A
character on keyboard char

Each type of data can only be stored in its appropriate storage bin.

Program Edit, Save, Compile, Execute using IDE 1st program (skeleton) void main(void) { }

Knowing the type of data, and give a name to the storage bin is called declaration. Data constants : 67, 45, 92, 55, 34 etc (these are exams score) Give it a name (variable name): ExamScore or Score or Math_Score etc. Data type : integer (because no decimal point!) We reserve in memory, a place to store exam score of type integer Score void main(void) { int Score; } Names other than keywords must be declared ex 1.1
A cashier has currency notes of denominations 10, 50 and 100. If the amount to be withdrawn is input through the keyboard in hundreds, find the total number of currency notes of each denomination the cashier will have to give to the withdrawer.

variable amount total10 total50 total100

data eg. 200 3 0 2

type integer integer integer integer

void main(void) { //declare variables int amount; int total10, total50, total100; }

Give an initial value to a variable. 35 Score void main(void) { int Score = 35; } ex 2.1
A cashier always has RM250 reserve in the cash register every morning. Find the balance in the cash register at the end of the day.

We reserve in memory, a place named Score of type integer, and store an initial value 35.

void main(void) { //declare variables float reserve = 250.0; float balance; }

Sometimes we do not know the value. We get the value from user. We use a library function called scanf. scanf is not a keyword, therefore it must be declared somewhere. Therefore, either you declare the function (chap 3-1) or use a function already declared by somebody else (in the library). To use a library function, we type, #include <stdio.h> where stdio.h is the library (h is header files) This statement is placed on top of the program (before any function). eg. to get a data from user into a variable called year, we type: scanf("%d", &year); %d is a control character. Control characters (preceded by a %) depend on the data type: control character data type %d integer %f float/real %c char Notice, &year is used instead of year. This is a pointer (chap 3-2). For now, just remember the syntax; scanf("%d", &year); ex 3.1
Get a radius of a circle from user and compute the area of the circle.

#include <stdio.h> void main(void) { //declare variables float radius; float area; scanf("%f", &radius); }

Show the content of the variables to user. We use a library function called printf. printf is not a keyword, therefore it must be declared. To use this library function, we type, #include <stdio.h> eg. to show the content of variable year, we type: printf("%d", year);

-> 2009

The syntax is almost similar to scanf, except for the &. To show any text on the screen, just type: printf("hello world");

-> hello world

To print combination of text and variable content on the screen, type: printf("radius = %f", radius); -> radius = 3.146656 ex 4.1
Get a radius of a circle from user. Print and radius on the screen.

#include <stdio.h> void main(void) { //declare variables float radius; float pi = 3.142857; printf("Enter radius : "); scanf("%f", &radius); printf("pi = %f\n", pi); printf("radius = %f", radius); } Now, there is a \n in the syntax. \n is an escape sequence. It can be said as representing a special key on your keyboard. escape sequence key \n new line \t horizontal tab \\ backslash 6

\b \" \'

backspace quotation mark apostrophe

Common programming mistake: 1. mis-spelled keyword: eg. mian instead of main 2. forgot semicolon at the end of statement 3. extra semicolon when not needed: eg. void main(void); eg..#include<stdio.h>; 4. forgot &: eg. scanf("%d", year); 5. missing double quote: eg. printf(hello world); 6. misplaced the double quote: eg. printf(radius = %d, radius);

Quiz 1 Get from user his or her initial. Then print a welcome screen. Heres what the output screen looks like:

Please enter your initial : Z Assalamualaikum Z! Welcome to C programming.

(C) Compute

An important reason for using a computer very fast calculation. arithmetic instruction format: var = <var/const> <arithmetic operator> <var/const> Among the arithmetic operators are: +, -, *, /(division), %(mod) Any formula can be translated into the arithmetic instruction format. eg. area = r2, translated into: area = pi * radius * radius result 0 0.4 0.4 2

Also important is the type conversion. Basically, operation example int <arithmetic operation> int 2/5 int <arithmetic operation> float 2/5.0 float <arithmetic operation> float 2.0/5.0 int <arithmetic operation> int 2%5 ex 5.1

Get a radius of a circle from user. Calculate the area of the circle and print the result.

#include <stdio.h> void main(void) { //declare variables float radius; float pi = 3.142857; float area; printf(Enter radius : ); scanf(%f, &radius); //calculate area area = pi * radius * radius; printf("Area = %f\n", area); }

Computer can also make decision. We use keywords if, if-else, if-elseif, switch conditional statement format: <var/const> <conditional operator> <var/const> where the conditional operators are: >, <, >=, <=, == (equal), != (not equal) and the result of the conditional operation is either 0 (false) or 1 (true). In fact, other than 0 is equal to true. Eg. conditional operation result 2<5 true 2>5 false using if statement:

eg. if (area>3.5) printf(The area is ok.); using switch statement: No semicolon eg. switch (ans) { case Y: printf(Yes); break; case N: printf(No); break; default: printf(Others); } without break, then if ans==Yes, the computer will print both Yes, No and Others

10

equivalent using if-else if (ans==Y) printf(Yes); else { if (ans==N) printf(No); else printf(Others); } equivalent using if-elseif if (ans==Y) printf(Yes); elseif (ans==N) printf(No); else printf(Others); eg. 6.1 Decide the fate of Malaysian soccer team based on the number of goals scored against the team. #include <stdio.h> void main(void) { int goals ; printf ("Enter the number of goals scored against Malaysia : " ); scanf ("%d", &goals ); if ( goals <= 5 ) printf ("To err is human."); else { printf ( "About time soccer players learn C\n" ) ; printf ( "and said goodbye! adieu to soccer" ) ; } }

11

Computer can continue repeating tasks until instructed to stop. We use keywords for, while and do-while Basically, need to specify the initial value (init), when to stop (condition) and the step (increment or decrement). using for statement: indent No semicolon If using only one statement, use semicolon. If more than one statements, use block. Then, no need semicolon.

for (initial value; stop condition; step)

eg. for (i=0, i<3; i++) printf(i =.&d , i); using while statement: initial value; while (stop condition) { .. step; } eg. equivalent to the above for statements i=0; while (i<3) { printf(i = &d , i); i++; }

->

i=0 i=1 i=2

12

eg. 7.1
Two numbers are entered through the keyboard. Write a program to find the value of one number raised to the power of another.

#include <stdio.h> void main(void) { int a, b, result, i ; printf ("Enter a number : " ); scanf ("%d", &a ); printf ("Enter a number (raised to the power of) : " ); scanf ("%d", &b ); result = 1; for (i=0; i<b; i++) result = result * a; printf ("Result = %d\n", result) ; }

13

Quiz 2
Write a program to enter five numbers. At the end it should display the count of positive, negative and zeros entered.

Heres what the output screen looks like:

Please enter five numbers: -12 5 0 3 -1 You have 2 positive numbers You have 2 negative numbers You have 1 zeros

14

Writing functions avoids rewriting the same code over and over. Using functions it becomes easier to write programs and keep track of what they are doing. If the operation of a program can be divided into separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. Separating the code into modular functions also makes the program easier to design and understand. Any C program contains at least one function. If a program contains only one function, it must be main( ). Program execution always begins with main( ). There is no limit on the number of functions that might be present in a C program. Each function in a program is called in the sequence specified by the function calls in main( ). Function calling - followed by a semicolon argentina( ) ; Function definition - followed by a pair of braces void argentina(void ) { statement ; .. statement ; } A function can call itself. Such a process is called recursion. A function can be called from other function, but a function cannot be defined in another function. There are basically two types of functions: Library functions Ex. printf( ), scanf( ) etc. [compiler comes with a library of standard functions; eg stdio.h, math.h] User-defined functions Ex. argentina( ), brazil( ) etc.

General function calling and function definition

15

Type 1: accept nothing, return nothing

Type 2: accept something, return nothing

Type 1: accept nothing, return something

Type 1: accept something, return something

16

function need to be declared before use (if typed after main): void display ( int i ) ; void main( void ) { int i = 20 ; display ( i ) ; } void display ( int i ) { int k = 35 ; printf ( "%d\n", i ) ; printf ( "%d\n", k ) ; } scope of variable is within function: void goUK ( int Cathy ) { int k = 35 ; printf ( "%d\n", Cathy ) ; printf ( "%d\n", k ) ; } void main( void ) { int Khatijah = 20 ; goUK (Khatijah ) ; } example of call by values : void display ( int i ) ; void main( void ) { int i = 20 ; display ( i ) ; printf ( In main i = %d\n", i ) ; } void display ( int i ) { i=i+1; printf ( In display i = %d\n", i ) ; }

17

- because function can only return one data

declaring pointer - pointer variables: int *alpha ; // integer pointer char *ch ; // char pointer float *s ; // float pointer example of call by reference: void main ( void ) { int a = 10, b = 20 ; swap ( &a, &b ) ; printf ( "a = %d, b = %d\n", a, b ) ; } void swap ( int *x, int *y ) { int t ; t = *x ; *x = *y ; *y = t ; }

a = 20 b = 10

exercise : get radius, calculate area and perimeter using one function only.

18

- when we have the same data type, and we want to combine them

example on array: //This program demonstrate the usual //DIS - Declare, Initialize and Show #include <stdio.h> void main (void) { //declare variables int num1, num2, num3 float Avg; //initialize num1 = 1; num2 = 2; num3 = 4; Avg = (num1 + num2 + num3) / 3.0; printf ("The numbers are :\n"); printf ("%d\n", num1); printf ("%d\n", num2); printf ("%d\n", num3); printf ("Average = %.2f\n", Avg); } } //This program demonstrate the use of array //DIS - Declare, Initialize and Show #include <stdio.h> void main (void) { //declare array int num[3]; //num[0], num[1], and num[2] float Avg; //initialize array num[0] = 1; num[1] = 2; num[2] = 4; Avg = (num[0] + num[1] + num[2]) / 3.0; printf ("The numbers are :\n"); printf ("%d\n", num[0]); printf ("%d\n", num[1]); printf ("%d\n", num[2]); printf ("Average = %.2f\n", Avg);

19

//This program demonstrate the use of array //DGS - Declare, Get (from user) and Show #include <stdio.h> void main (void) { int num[3]; float Avg; printf ("Enter 3 numbers : "); scanf ("%d", &num[0]); scanf ("%d", &num[1]); scanf ("%d", &num[2]); Avg = (num[0] + num[1] + num[2]) / 3.0; printf ("The numbers are :\n"); printf ("%d\n", num[0]); printf ("%d\n", num[1]); printf ("%d\n", num[2]); printf ("Average = %.2f\n", Avg); }

//This program demonstrate the use of array //Use 'for' loop and 'define' #include <stdio.h> #define no 3 void main (void) { int num[no]; int i, Sum; float Avg; //get input from user printf ("Enter %d numbers : ", no); for (i=0; i<no; i++) scanf ("%d", &num[i]); for (Sum=0, i=0; i<no; i++) { Sum = Sum + num[i]; printf ("i = %d, num[%d] = %d, Sum = %d\n", i, i, num[i], Sum); } Avg = 1.0 * Sum / no; printf ("The numbers are :\n"); for (i=0; i<no; i++) printf ("%d\n", num[i]);

//This program demonstrate the use of array //Use function and pointers #include <stdio.h> #define no 4 void getAvg(int *num, float *Avg); void main (void) { int num[no], i; float Avg; //get input from user printf ("Enter %d numbers : ", no); for (i=0; i<no; i++) scanf ("%d", &num[i]); getAvg(num, &Avg); printf ("The numbers are :\n"); for (i=0; i<no; i++) printf ("The numbers are :\n");

printf ("Average = %.2f\n", Avg); }

for (i=0; i<no; i++) printf ("%d\n", num[i]); printf ("Average = %.2f\n", Avg); } void getAvg(int *num, float *Avg) { int i, Sum; for (Sum=0, i=0; i<no; i++) { Sum = Sum + *num; printf ("i = %d, num[%d] = %d, Sum = %d\n", i, i, *num, Sum); num++; } *Avg = 1.0 * Sum / no; } 20

- when we have the same data type (char), and we want to combine them

example on string: #include <stdio.h> void main (void) { char name[5] = {'A','h','m','a','d'}; int i; for (i=0;i<5;i++) { printf("%c", name[i]); } } #include <stdio.h> void main (void) { char name[5]; int i; printf("Enter your name : "); for (i=0;i<5;i++) { scanf("%c", &name[i]); } for (i=0;i<5;i++) { printf("%c", name[i]); } printf("\n"); }

21

#include <stdio.h> void main (void) { char name[5]; int i, pos=0; printf("Enter your name : "); gets(name); printf("\nYour name is : "); puts(name); for (i=0;i<5;i++) { if (name[i]=='m') pos = i+1; } printf("char 'm' is in position %d\n", pos); }

#include <stdio.h> #include <string.h> void main (void) { char name[20]; int i, pos=0, length; printf("Enter your name : "); gets(name); printf("\nYour name is : "); puts(name); length = strlen(name); for (i=0;i<length;i++) { if (name[i]=='m') pos = i+1; } if (pos!=0) printf("char 'm' is in position %d\n", pos); else printf("Your name does not have char 'm'\n"); }

22

- when we have different data types, and we want to combine them

look at this function later! void getAvgMath (struct score *student, float *Avg) { int i, Sum; for (Sum=0, i=0; i<row; i++) Sum = Sum + student[i].Math; //printf("Sum = %d\n", Sum); *Avg = 1.0 * Sum / row; }

23

example of program using structure: #include <stdio.h> struct score { char name[10]; int Math; int Science; int English; }; void main (void) { int i; int Max, Min; float Avg; struct score student[4] = { "Amin", 55, 61, 86, "Aman", 48, 69, 76, "Azim", 88, 91, 77, "Azam", 78, 71, 56, }; /* //get input from user for (i=0; i<row; i++) { printf ("Enter row %d studentbers : ", i); for (j=0; j<col; j++) scanf ("%d", &student[i][j]); } */ //print array for (i=0; i<row; i++) { printf ("%s\t: %d %d %d", student[i].name, student[i].Math, student[i].Science, student[i].English); printf ("\n"); } getAvgMath (&student, &Avg); printf ("\nAverage = %.2f\n", Avg); }

24

Quiz 3 Create a structure to specify data of customers in a bank. The data should include; Account No, Name, Balance, Year Join Use the following information for your program: Account No Name Balance C011 Dahlia bt Atan 200 D012 Abu bin Bakar 20 B013 Ramli bin Amin 145 D014 Fatimah bt Haris 35 D017 Wong Hong Kau 45 Year Join 2004 2005 2003 2005 2005

Write a function to print the Account number and name of each customer with balance below RM 50 Example Output : ** Welcome to Bank of Wopuchitau ** ** This utility lets you to list all customers with balance below certain value. ** Please enter the cutoff value: RM 50 The customers with balance below RM 50: 1. D012 Abu bin Bakar 20 2. D014 Fatimah bt Haris 35 3. D017 Wong Hong Kau 45

25

Das könnte Ihnen auch gefallen