SlideShare a Scribd company logo
F1001 PROGRAMMING FUNDAMENTALS




    UNIT

      5

STRUCTURE OF C PROGRAM

   Basic Concepts of C Programming
   Important Elements In A C Program
 Data and Variables
 Input and Output




                                                 70
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


                                                                                        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
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
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
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
F1001 PROGRAMMING FUNDAMENTALS


  HEADER    LIBRARY                             USES
   FILES   FUNCTIONS
stdio.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 form

math.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 x

ctype.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 character

string.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 string

conio.h    clrscr()         Clears the output screen




                                                                               75
F1001 PROGRAMMING FUNDAMENTALS




Data and Variables

Data
      Data is an array of facts that can be modified by the computer into useful forms for human beings.




                                                                                                            76
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
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 = Expression
Variables

                                  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
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 variable


Local 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
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 variable's 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 array



Constant


                                                                                                                     80
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.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)




                  %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 (%)
F1001 PROGRAMMING FUNDAMENTALS




Input And Output

Input 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 and
Syntax :         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

More Related Content

What's hot

structure of a c program
structure of a c programstructure of a c program
structure of a c program
sruthi yandapalli
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
JAYA
 
Overview of c language
Overview of c languageOverview of c language
Overview of c languageshalini392
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
Sowri Rajan
 
iOS overview
iOS overviewiOS overview
iOS overview
gupta25
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of c
kinish kumar
 
C Program Structure
C Program StructureC Program Structure
C Program Structure
Mahfuzur Rahman
 
Subprogramms
SubprogrammsSubprogramms
Subprogramms
janapriyanaidu
 
Extension and Evolution
Extension and EvolutionExtension and Evolution
Extension and Evolution
Eelco Visser
 
Cp week _2.
Cp week _2.Cp week _2.
Cp week _2.
shahidullah57
 
C programming session 11
C programming session 11C programming session 11
C programming session 11AjayBahoriya
 
Functions
FunctionsFunctions
7 compiler lab
7 compiler lab 7 compiler lab
7 compiler lab
MashaelQ
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topics
veningstonk
 
C programming
C programming C programming
C programming
Rohan Gajre
 
Feature and platform testing with CMake
Feature and platform testing with CMakeFeature and platform testing with CMake
Feature and platform testing with CMake
Richard Thomson
 
C++ basics
C++ basicsC++ basics
C++ basics
AllsoftSolutions
 
Deep C
Deep CDeep C
Deep C
Olve Maudal
 

What's hot (20)

structure of a c program
structure of a c programstructure of a c program
structure of a c program
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
Overview of c language
Overview of c languageOverview of c language
Overview of c language
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
iOS overview
iOS overviewiOS overview
iOS overview
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of c
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
C Program Structure
C Program StructureC Program Structure
C Program Structure
 
Subprogramms
SubprogrammsSubprogramms
Subprogramms
 
Extension and Evolution
Extension and EvolutionExtension and Evolution
Extension and Evolution
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Cp week _2.
Cp week _2.Cp week _2.
Cp week _2.
 
C programming session 11
C programming session 11C programming session 11
C programming session 11
 
Functions
FunctionsFunctions
Functions
 
7 compiler lab
7 compiler lab 7 compiler lab
7 compiler lab
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topics
 
C programming
C programming C programming
C programming
 
Feature and platform testing with CMake
Feature and platform testing with CMakeFeature and platform testing with CMake
Feature and platform testing with CMake
 
C++ basics
C++ basicsC++ basics
C++ basics
 
Deep C
Deep CDeep C
Deep C
 

Similar to Unit 5

Sachin kumar ppt on programming in c
Sachin kumar ppt on programming in cSachin kumar ppt on programming in c
Sachin kumar ppt on programming in c
Sachin Kumar
 
Unit-1 (introduction to c language).pptx
Unit-1 (introduction to c language).pptxUnit-1 (introduction to c language).pptx
Unit-1 (introduction to c language).pptx
saivasu4
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5
REHAN IJAZ
 
Basics of c Nisarg Patel
Basics of c Nisarg PatelBasics of c Nisarg Patel
Basics of c Nisarg Patel
TechNGyan
 
5. Functions in C.pdf
5. Functions in C.pdf5. Functions in C.pdf
5. Functions in C.pdf
santosh147365
 
5.Hello World program Explanation. ||C Programming tutorial.
5.Hello World program Explanation. ||C Programming tutorial.5.Hello World program Explanation. ||C Programming tutorial.
5.Hello World program Explanation. ||C Programming tutorial.
Fiaz Hussain
 
C structure
C structureC structure
C structure
ankush9927
 
C Programming UNIT 1.pptx
C Programming  UNIT 1.pptxC Programming  UNIT 1.pptx
C Programming UNIT 1.pptx
Mugilvannan11
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
ManiMala75
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
ManiMala75
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
TejaswiB4
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
TejaswiB4
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
valerie5142000
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
imtiazalijoono
 
C++ AND CATEGORIES OF SOFTWARE
C++ AND CATEGORIES OF SOFTWAREC++ AND CATEGORIES OF SOFTWARE
C++ AND CATEGORIES OF SOFTWARE
UNIVERSITY OF ENGINEERING AND TECHNOLOGY TAXILA
 
C - ISRO
C - ISROC - ISRO
C - ISRO
splix757
 
Lecture 3 getting_started_with__c_
Lecture 3 getting_started_with__c_Lecture 3 getting_started_with__c_
Lecture 3 getting_started_with__c_
eShikshak
 

Similar to Unit 5 (20)

Sachin kumar ppt on programming in c
Sachin kumar ppt on programming in cSachin kumar ppt on programming in c
Sachin kumar ppt on programming in c
 
Unit-1 (introduction to c language).pptx
Unit-1 (introduction to c language).pptxUnit-1 (introduction to c language).pptx
Unit-1 (introduction to c language).pptx
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5
 
Basics of c Nisarg Patel
Basics of c Nisarg PatelBasics of c Nisarg Patel
Basics of c Nisarg Patel
 
5. Functions in C.pdf
5. Functions in C.pdf5. Functions in C.pdf
5. Functions in C.pdf
 
5.Hello World program Explanation. ||C Programming tutorial.
5.Hello World program Explanation. ||C Programming tutorial.5.Hello World program Explanation. ||C Programming tutorial.
5.Hello World program Explanation. ||C Programming tutorial.
 
C structure
C structureC structure
C structure
 
Structure
StructureStructure
Structure
 
C Programming UNIT 1.pptx
C Programming  UNIT 1.pptxC Programming  UNIT 1.pptx
C Programming UNIT 1.pptx
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
Structure of a C program
Structure of a C programStructure of a C program
Structure of a C program
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
C++ AND CATEGORIES OF SOFTWARE
C++ AND CATEGORIES OF SOFTWAREC++ AND CATEGORIES OF SOFTWARE
C++ AND CATEGORIES OF SOFTWARE
 
C - ISRO
C - ISROC - ISRO
C - ISRO
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 
Lecture 3 getting_started_with__c_
Lecture 3 getting_started_with__c_Lecture 3 getting_started_with__c_
Lecture 3 getting_started_with__c_
 

More from rohassanie

Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012rohassanie
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6rohassanie
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2rohassanie
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
FP 202 - Chapter 5
FP 202 - Chapter 5FP 202 - Chapter 5
FP 202 - Chapter 5rohassanie
 
Chapter 3 part 2
Chapter 3 part 2Chapter 3 part 2
Chapter 3 part 2rohassanie
 
Chapter 3 part 1
Chapter 3 part 1Chapter 3 part 1
Chapter 3 part 1rohassanie
 
FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3rohassanie
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3rohassanie
 
FP 201 Unit 2 - Part 2
FP 201 Unit 2 - Part 2FP 201 Unit 2 - Part 2
FP 201 Unit 2 - Part 2rohassanie
 
Chapter 2 (Part 2)
Chapter 2 (Part 2) Chapter 2 (Part 2)
Chapter 2 (Part 2) rohassanie
 
Labsheet 7 FP 201
Labsheet 7 FP 201Labsheet 7 FP 201
Labsheet 7 FP 201rohassanie
 
Labsheet 6 - FP 201
Labsheet 6 - FP 201Labsheet 6 - FP 201
Labsheet 6 - FP 201rohassanie
 
Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012rohassanie
 
Chapter 2 part 1
Chapter 2 part 1Chapter 2 part 1
Chapter 2 part 1rohassanie
 

More from rohassanie (20)

Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012Course outline FP202 - Dis 2012
Course outline FP202 - Dis 2012
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
FP 202 - Chapter 5
FP 202 - Chapter 5FP 202 - Chapter 5
FP 202 - Chapter 5
 
Chapter 3 part 2
Chapter 3 part 2Chapter 3 part 2
Chapter 3 part 2
 
Chapter 3 part 1
Chapter 3 part 1Chapter 3 part 1
Chapter 3 part 1
 
FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3FP 202 Chapter 2 - Part 3
FP 202 Chapter 2 - Part 3
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
FP 201 Unit 2 - Part 2
FP 201 Unit 2 - Part 2FP 201 Unit 2 - Part 2
FP 201 Unit 2 - Part 2
 
Lab ex 1
Lab ex 1Lab ex 1
Lab ex 1
 
Chapter 2 (Part 2)
Chapter 2 (Part 2) Chapter 2 (Part 2)
Chapter 2 (Part 2)
 
Labsheet 7 FP 201
Labsheet 7 FP 201Labsheet 7 FP 201
Labsheet 7 FP 201
 
Labsheet 6 - FP 201
Labsheet 6 - FP 201Labsheet 6 - FP 201
Labsheet 6 - FP 201
 
Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012Jadual Waktu Sesi JUN 2012
Jadual Waktu Sesi JUN 2012
 
Labsheet 5
Labsheet 5Labsheet 5
Labsheet 5
 
Labsheet 4
Labsheet 4Labsheet 4
Labsheet 4
 
Chapter 2 part 1
Chapter 2 part 1Chapter 2 part 1
Chapter 2 part 1
 

Recently uploaded

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 

Recently uploaded (20)

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 

Unit 5

  • 1. F1001 PROGRAMMING FUNDAMENTALS UNIT 5 STRUCTURE OF C PROGRAM  Basic Concepts of C Programming  Important Elements In A C Program  Data and Variables  Input and Output 70
  • 2. 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 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. 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. 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. 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. F1001 PROGRAMMING FUNDAMENTALS HEADER LIBRARY USES FILES FUNCTIONS stdio.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 form math.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 x ctype.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 character string.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 string conio.h clrscr()  Clears the output screen 75
  • 7. F1001 PROGRAMMING FUNDAMENTALS Data and Variables Data  Data is an array of facts that can be modified by the computer into useful forms for human beings. 76
  • 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. 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 = Expression Variables 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. 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 variable Local 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. 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 variable's 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 array Constant 80
  • 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.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) %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. F1001 PROGRAMMING FUNDAMENTALS Input And Output Input 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 and Syntax : 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