F1001 PROGRAMMING FUNDAMENTALS    UNIT      5STRUCTURE OF C PROGRAM   Basic Concepts of C Programming   Important Elemen...
F1001 PROGRAMMING FUNDAMENTALSINTRODUCTIONIn this unit students are introduced to a simple C program. The unit describes t...
F1001 PROGRAMMING FUNDAMENTALS    Comments•   A line starting with /* and ending with */ is a comment.•   The purpose of a...
F1001 PROGRAMMING FUNDAMENTALS•   #include <stdio.h>         #               •       Lines starting with the ‘#’ symbol is...
F1001 PROGRAMMING FUNDAMENTALS•   #define AGE 22        #               •       Lines starting with the ‘#’ symbol is proc...
F1001 PROGRAMMING FUNDAMENTALS  HEADER    LIBRARY                             USES   FILES   FUNCTIONSstdio.h    scanf()  ...
F1001 PROGRAMMING FUNDAMENTALSData and VariablesData      Data is an array of facts that can be modified by the computer ...
F1001 PROGRAMMING FUNDAMENTALS               NUMERIC                         INTEGER                                      ...
F1001 PROGRAMMING FUNDAMENTALS    1.   Name    2.   Type    3.   Holds a value that you assign to them                    ...
F1001 PROGRAMMING FUNDAMENTALS                                    numbers.                                          int Co...
F1001 PROGRAMMING FUNDAMENTALS         You can access (and change) local variables                    Global variables c...
F1001 PROGRAMMING FUNDAMENTALS•   The value of constant remains unchanged for the whole duration of the program execution....
F1001 PROGRAMMING FUNDAMENTALSInput And OutputInput Function                                              Output Function ...
Upcoming SlideShare
Loading in …5
×

Unit 5

354 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
354
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
13
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Unit 5

  1. 1. F1001 PROGRAMMING FUNDAMENTALS UNIT 5STRUCTURE OF C PROGRAM Basic Concepts of C Programming Important Elements In A C Program Data and Variables Input and Output 70
  2. 2. F1001 PROGRAMMING FUNDAMENTALSINTRODUCTIONIn this unit students are introduced to a simple C program. The unit describes the important elements of aC program and the types of data that can be processed by C. It also describes C statements for performingtasks such as getting data from the user and displaying the data on screen. Here students will be presentedwith 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 andconditions of C programming. By this time, they should know the ways to declare variables, use variablesand understand the naming conventions of variables and print outputs. Students should also have enoughknowledge to write clear, well documented and error free codes at the end of this chapter.Basic C program structure Comments /* Example of basic C program Structure */ #include <stdio.h> Header File Pre-processor commands #define MAX 20 void main() Main Function { Start of main function Constant const PI = 3.142; Data Type char letter; Variable int number; huruf = ‘A’; Output Function printf(“Enter one number : “); Input Function scanf(“%d”, &number); } End of main function NOTES The curly braces “{ }” symbol shows the body of the program body. Any code/statements must be written inside the body. 71
  3. 3. 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 Examples : /* this is a comment */ /* This is also a comment */ 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: main() (i) head { char b; b = ‘A’; (ii) body } HEAD BODY • Every function must have a header. • Every function must have a body which starts • Function header is the name of that function. with an open curly bracket ‘{’ and ends with • main() function has a fixed name. a close curly bracket ‘}’. • We cannot change the name of main() • Every body function contains a program function statement. • A program statement will perform certain tasks such as receiving value, display value, calculation and so on. Pre-processor Commands 72
  4. 4. F1001 PROGRAMMING FUNDAMENTALS• #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. #include <FileName> or <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) 73
  5. 5. F1001 PROGRAMMING FUNDAMENTALS• #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) #define <constant name> <constant value> AGE • Name of constant • Usually written in CAPITAL letters 22 • Value assigned to AGE Examples of Header Files in C programming 74
  6. 6. F1001 PROGRAMMING FUNDAMENTALS HEADER LIBRARY USES FILES FUNCTIONSstdio.h scanf()  Receives input from keyboard printf()  Displays output on screen gets()  Receives input in the form of string getchar()  Receives a character as input puts()  Displays output in string formmath.h pow(x,y)  Computes the value of x raised to the power of y sqrt(x)  Computes the square root of x exp(x)  Computes the exponent value of xctype.h isalnum(c)  To test whether c is alphabetic or digit isdigit(c)  To test whether c is a numeric ispunct(c)  To test whether c is a punctuation mark islower(c)  To test whether c is a lower case characterstring.h strlen(c)  To get the length of a string strncmp(c)  Compares the part of two strings strtok(c)  Splits string into words strncpy(c)  Copies one part of a chosen stringconio.h clrscr()  Clears the output screen 75
  7. 7. F1001 PROGRAMMING FUNDAMENTALSData and VariablesData Data is an array of facts that can be modified by the computer into useful forms for human beings. 76
  8. 8. F1001 PROGRAMMING FUNDAMENTALS NUMERIC INTEGER  All positive and negative numbers including zero and • Contains all types of no decimal place. numbers.  Example: 0, +1, -10. • Data which can be used  Integers are used to represent the counting of things. for calculation. Example: Numbers of month in a year (1,2,3…) • Example: sums of REAL NUMBER money, age, and  Contains all real numbers. distance (e.g: 34, 50,  The number will be stored in floating point. and 1.01).  Used for metric measurement, temperature and price. Example: 1.0, 234.55, 20.30, 36.7. CHARACTER  Consists of all letters, numbers and special symbols.  Characters are surrounded by single quotation mark (‘ ‘). DATA Example: ‘A’, ‘m’,’=’, ‘#’, ‘1’ or ‘ ‘. STRING  A combination of one or more characters. NON NUMERIC  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• 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: 77
  9. 9. F1001 PROGRAMMING FUNDAMENTALS 1. Name 2. Type 3. Holds a value that you assign to them • Must begin with a letter of the alphabet but, after the first letter,Naming Variables 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. • Examples: MY AGE, 4_stu, my age, printf, 81_sales,Invalid Variable Names Aug91+Sales, Age?Defining Variables Syntaks : DataType VariableName; Examples : int number; float money;Assigning Values To Syntaks : VariableName = ExpressionVariables Examples : number = 32; money = 30.50;Data Types• Data type is the type of data that will be stored in the memory location. DATA TYPE USES EXAMPLE CODE int int is used to define integer 78
  10. 10. F1001 PROGRAMMING FUNDAMENTALS 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 double Atoms; twice the storage for the number. Atoms= 2500000; char A char defines characters. char Letter; Letter = x;Variable Scope There are two main variable scopes: 1. Local variable 2. Global variableLocal Variable Global Variable #include <stdio.h> #include <stdio.h> FunctionName() char B; { int A; FunctionName() { /*Block of one or more */ / int A; *C statements*/ } /*Block of one or more */ /*C statements*/ } Local Variable Global Variable  It is a variable that has been defined  A global variable is a variable that has been immediately after the opening braces of a defined before a function (usually before the function. main() function).  Each functions can have their own variables  This means, all function in that program can declarations. use this variable. 79
  11. 11. F1001 PROGRAMMING FUNDAMENTALS  You can access (and change) local variables  Global variables can be used anywhere in only from the functions in which they are the program as soon as it has been defined. defined. Therefore that variables scope is protected.  All local variables lose their definition when their block ends.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. • A string is a collection of characters to represent a name How to define (mother, father, student, employee, car, building, shopping strings data type complex, software), address and extra. Syntaks: char variableName [STRING_LENGTH]; Example to declare char employeeName [30]; character array:  A string must be stored in character arrays, but not all character arrays contain a string. string Contoh : char name[9] = "Muhammad"; is not the same as char name[8] = {M, u, h, a, m, m, a, d}; Data String Variable Name Type length Character arrayConstant 80
  12. 12. F1001 PROGRAMMING FUNDAMENTALS• 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 : const data_type constant_name = constant_value; or #define constant_name constant_value Examples : const double PI = 3.1459; #define PI 3.1459Character 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) %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 81 %% percent sign (%)
  13. 13. F1001 PROGRAMMING FUNDAMENTALSInput And OutputInput Function Output Function • Use the scanf(), gets(), getc() and • Use the printf(), puts() and putchar() getchar() function from the stdio.h. function from stdio.h • One of way to get input is by asking the • This function sends all the output to the user to enter values into the variables using screen. the keyboard. Syntax : printf(“CS”,variablename) • It contains conversion characters. • The conversion character explains to C what data type to be inserted by user. CS: Control String – a combination of string andSyntax : scanf(“CC”, &variablename); conversion character CC – Conversion Character #include <stdio.h> #include <stdio.h> main () { main() int age; { /*Input*/ char name [35]; printf(“Your age ?”); scanf(“%d”, &age); /*Input*/ /*Output*/ printf(“Enter name :”); printf(“Your age : %d years”, age); scanf(“%s”, name); } } Control String 82

×