SlideShare une entreprise Scribd logo
1  sur  50
Programming in C
Objectives


                In this session, you will learn to:
                   Work with operators
                   Use loops
                   Use formatted input-output functions




     Ver. 1.0                                             Slide 1 of 50
Programming in C
Working with Operators


                An operator:
                   Is a symbol used to command the computer to do
                   mathematical or logical manipulations.
                   Operates on data and variables.
                C has a rich set of operators, which can be classified into
                following various categories:
                   Relational operators
                   Logical operators
                   Unary operators
                   Binary operators
                   Ternary operator
                   Compound assignment operators
                   Increment/Decrement operators



     Ver. 1.0                                                         Slide 2 of 50
Programming in C
Logical Operators


                Notations for logical operators in C are:
                   Operator                    Notation
                     OR                          ||
                     AND                         &&
                     NOT                          !
                Operator precedence:
                NOT (!) is evaluated before AND (&&), which is evaluated
                before OR (||). Brackets () are used to change this order.




     Ver. 1.0                                                        Slide 3 of 50
Programming in C
Practice: 2.1


                • Write a function that accepts either y or n only as input. For
                  any other character input, an appropriate error message
                  should be displayed and the input is accepted again.




     Ver. 1.0                                                            Slide 4 of 50
Programming in C
Practice: 2.1 (Contd.)


                Solution:
                   #include<stdio.h>
                    main()
                    { char yn;
                      do {
                      puts(“Enter y/n (Yes/No)”);
                      yn=getchar ();
                      fflush (stdin);
                      if(yn!=’y’ && yn!=’n’)
                           puts(“Invalid input”);
                      }
                      while(yn!=’y’ && yn!=’n’);
                    }


     Ver. 1.0                                       Slide 5 of 50
Programming in C
Unary Operators


                Unary Operators:
                   Operates on a single operand.
                   Prefixed to an integer constant.
                   Tells the compiler to reverse the sign by subtracting the value
                   (or variable) from zero.
                   Has the same effect as the – sign, which is used to indicate a
                   number less than zero, for example -12.




     Ver. 1.0                                                              Slide 6 of 50
Programming in C
Practice: 2.2


                Which of the following are valid?
                1. valuea=-12;         /* valuea is int* /
                2. valuea = - valueb – 12 /* valuea and valueb
                   both are int */




     Ver. 1.0                                             Slide 7 of 50
Programming in C
Practice: 2.2 (Contd.)


                Solution:
                1. Valid
                2. Valid




     Ver. 1.0               Slide 8 of 50
Programming in C
Binary Operators


                Binary Operators:
                   Operate on two operands.
                   Are as follows:
                      + (add)
                      - (subtract)
                      * (multiply)
                      / (divide)
                      % (modulo)




     Ver. 1.0                                 Slide 9 of 50
Programming in C
Practice: 2.3


                In the following set of statements:
                char ch;
                ch=’S’;
                ch=ch+’a’-‘A’;        /*statement A*/
                ch=ch+’A’-‘a’;        /*statement B*/
                What will be the value of ch after:
                1. Statement A is executed?
                2. Statement B is executed?




     Ver. 1.0                                           Slide 10 of 50
Programming in C
Practice: 2.3 (Contd.)


                Solution:
                1. ch is equal to s. Note that ‘a’-‘A’ gives 32 after statement 1 is
                   executed.
                2. ch is back to S after statement 2 is executed.




     Ver. 1.0                                                               Slide 11 of 50
Programming in C
Binary Operators (Contd.)


                There are some set or rules, if followed, would prevent
                unexpected results, at the time of execution of programs:
                 – Any operand of type char is converted to int.
                 – All floats are converted to doubles.
                 – If either operand is double, the other is converted to a
                   double, giving a double result.




     Ver. 1.0                                                             Slide 12 of 50
Programming in C
Practice: 2.4


                •   In which of the following assignments is there no loss of
                    data? (i is an int, f a float, and d a double)
                     i=d;
                     d=f;
                     f=d;
                     i=f+d;
                     d=i+f;
                2. Is type casting necessary in the following example?
                     int i,j;
                     float f;
                     double d;
                     d=f+(float) i + j;




     Ver. 1.0                                                            Slide 13 of 50
Programming in C
Practice: 2.4 (Contd.)


                Solution:
                 – a. Loss of data. int set equal to a double.
                    b. No loss of data. double set equal to a float.
                    c. Loss of data. float set equal to a double.
                    d. Loss of data. Right-hand result is a double while left-hand
                       side is just an int.
                    e. No loss of data. Right-hand result is a double and
                       left-hand side is also a double.
                 2. Not necessary. The ints will automatically be converted to
                    doubles (following the conversion of the float to a double).




     Ver. 1.0                                                             Slide 14 of 50
Programming in C
Ternary Operator


                Ternary Operator:
                – Is a shorthand method for writing if.else conditional
                  construct.
                – Helps in reducing lines of code.
                – Has the following form for the expression using the ternary
                  operator:
                    (test-expression) ? T-expression : F-expression;




     Ver. 1.0                                                            Slide 15 of 50
Programming in C
Ternary Operator (Contd.)


                Consider the following example:
                 if(condition)
                 { Statements if condition is true }
                 else
                 { Statements if condition is false }
                Can be rewritten using the shorthand operator as follows:
                 larger_of_the_two = ( x > y ) ? x : y;




     Ver. 1.0                                                         Slide 16 of 50
Programming in C
Practice: 2.5


                1. State whether True or False:
                    In the general form of an expression that uses a ternary operator,
                    the test expression will be checked. If it is true, the T-expression
                    will be evaluated, otherwise the F-expression will be evaluated.
                2. What will the following statement do?
                    quotient = (b==0) ? 0 : (a/b); /*a, b, and
                    quotient are ints*/
                3. Can the preceding statement be written as follows?
                    quotient = (b) ? (a/b) : 0;
                4. What will the following statement do?
                    always_negative = (j>0) ? j : (-j);




     Ver. 1.0                                                                   Slide 17 of 50
Programming in C
Practice: 2.5 (Contd.)


                Solution:
                 – True.
                 – If b is non-zero, it will determine the quotient of a and b. If b
                   equals zero, quotient is set to 0.
                 – Yes. Note that if b is non-zero, the test expression (b)
                   evaluates to true and hence quotient is set to (a/b).
                 – The variable always_negative will always take on a non-
                   negative value, i.e. it will be assigned the absolute value of j.
                   The name of the variable always_negative is just a red
                   herring. Remember that self-documenting variable names will
                   help in writing programs that are readable. Note the unary
                   operator (-j).




     Ver. 1.0                                                               Slide 18 of 50
Programming in C
Compound Assignment Operators


               Compound Assignment Operators:
                  Are useful especially when long variable names are used.
                  Has the following general form:
                   left-value op= right-expression;
                  Here op can be either + (add), - (subtract, * (multiply), /
                  (divide), and % (modulo).
                  Consider the following example:
                   a_very_long_identifier=a_very_long_identifier + 2;
                  It can be written as:
                   a_very_long_identifier += 2;




    Ver. 1.0                                                              Slide 19 of 50
Programming in C
Increment / Decrement Operators


                Increment / Decrement Operators:
                   Are used to increase or decrease the value of a variable by 1.
                   Has the following two forms:
                      The ++ (two plus symbols without a space), called the increment
                      operator while that in ++ before the variable is called the pre
                      increment operator and after the variable is called the post
                      increment operator.
                      The -- (two minus symbols without a space), called the decrement
                      operator while that in ++ before the variable is called the pre
                      decrement operator and after the variable is called the post
                      increment operator.




     Ver. 1.0                                                                Slide 20 of 50
Programming in C
Increment / Decrement Operators (Contd.)


                Consider the following code snippet:
                   total = sum++;                  /* statement A */
                   total = ++sum;                  /* statement B */
                 The first statement is equivalent to:
                   total = sum; sum = sum + 1;
                  While the second is the same as:
                   sum = sum + 1; total = sum;




     Ver. 1.0                                                          Slide 21 of 50
Programming in C
Practice: 2.6


                1. Consider the following code snippet:
                    int sum   = 3, total = 5;
                    total =   sum++;
                    total =   ++sum;   /*statement A */
                    total =   sum—
                    total =   --sum;   /*statement B */
                   What will be the values of total and sum after:
                    a. statement A is executed?
                    b. statement B is executed?




     Ver. 1.0                                                        Slide 22 of 50
Programming in C
Practice: 2.6 (Contd.)


                1. State whether True or False:
                      The following statement:
                       for(i = 0; i< 100); i = i + 1)
                       {
                          Some statements
                       }
                          can be written as:

                       for (i = 0; i < 100; i++)
                       {
                          Some statements
                       }




     Ver. 1.0                                           Slide 23 of 50
Programming in C
Practice: 2.6 (Contd.)


                1. State whether True or False:
                       The for statement in #2 can also be written as:
                        fori = 0; i < 100; ++i)/*Note: ++i and not i++*/
                        {
                           Some statements
                        }
                4. Write a program, which reads in a year and reports on
                   whether it is a leap year or not (centuries should also be
                   considered).




     Ver. 1.0                                                            Slide 24 of 50
Programming in C
Practice: 2.6 (Contd.)


                Solution:
                 1. total=5, sum=5
                    total=3, sum=3
                    quite a complicated way of reducing total by 2.
                 2. True. i+1 is equivalent to i++.
                 5. True. i+1 is equivalent to 1+i.
                 4.

                                      Microsoft Word
                                         Document




     Ver. 1.0                                                         Slide 25 of 50
Programming in C
Using Loops


                • The while and do…while looping constructs are generally
                  used in situations where the number of execution of the
                  loop is not known.
                • The for loop construct is used when the number of
                  execution of the loop is known.




     Ver. 1.0                                                     Slide 26 of 50
Programming in C
The for Loop Construct


                The for loop construct:
                   Has three components in the loop control:
                     • Initialization
                     • Condition
                     • Re-initialization (increment/decrement)
                   Has the following sequence of execution:
                       Initialization
                       Evaluation of loop condition
                       Body of loop
                       Re-initialization




     Ver. 1.0                                                    Slide 27 of 50
Programming in C
The for Loop Construct (Contd.)


                The sequence of execution of a complete for loop construct
                is shown in the following figure.

                                      INITIALIZATION




                                                          FALSE
                                       EVALUATE
                                       CONDITION


                                                   TRUE

                                    BODY OF LOOP




                                     REINITIALIZATION




     Ver. 1.0                                                      Slide 28 of 50
Programming in C
The for Loop Construct (Contd.)


                In a for loop construct:
                   Multiple initializations and/or multiple re- initializations, are
                   separated by commas.
                   Multiple conditions are specified using logical operators.




     Ver. 1.0                                                                   Slide 29 of 50
Programming in C
Practice: 2.7


                1. Write a function to accept twenty characters from the
                   character set, and to display whether the number of lower-
                   case characters is greater than, less than, or equal to
                   number of upper-case characters. Display an error
                   message if the input is not an alphabet.
                2. Modify the function to accept characters endlessly until the
                   character ! is input from keyboard.




     Ver. 1.0                                                           Slide 30 of 50
Programming in C
Practice: 2.7 (Contd.)


                Solution:
                1.

                                 Microsoft Office
                             Word 97 - 2003 Document




                2.

                                Microsoft Office
                            Word 97 - 2003 Document




     Ver. 1.0                                          Slide 31 of 50
Programming in C
Controlling the Loop Execution


                • At times there is a need to exit from a loop before the loop
                  condition is re-evaluated after iteration.
                • To exit from loop control, break and continue statements
                  are used.




     Ver. 1.0                                                          Slide 32 of 50
Programming in C
Practice: 2.8


                Write a function, which accepts numbers until 0 is entered
                or 10 numbers have been accepted. The function prints the
                total number of entries, the number of positive entries, and
                the sum of all the positive numbers.




     Ver. 1.0                                                        Slide 33 of 50
Programming in C
Practice: 2.8 (Contd.)


                Solution:




                               Microsoft Office
                            Word 97 - 2003 Document




     Ver. 1.0                                         Slide 34 of 50
Programming in C
Using Formatted Input-Output Functions


                C provides the following functions for formatted input-output:
                   printf()
                   scanf()




     Ver. 1.0                                                         Slide 35 of 50
Programming in C
Formatted Output


               • Syntax of the formatted output function printf() is:
                   printf (format, data1, data 2, ….);
                 Consider the following example:
                   printf(“%c”, inp);
                 The character specified after % is called a conversion
                 character.
                 The conversion character allows one data type to be
                 converted to another type and printed.




    Ver. 1.0                                                          Slide 36 of 50
Programming in C
Formatted Output (Contd.)


                The conversion characters and their meanings are shown in
                the following table.

                       Character                     Meaning

                          d         the data is converted to decimal (integer)


                           c        the data is taken as a character

                           s        the data is a string and characters from
                                    the string are printed until a NULL
                                    character is reached
                           f        the data is output as a double or float with
                                    a default precision to 6




     Ver. 1.0                                                                      Slide 37 of 50
Programming in C
Practice: 2.9


                What is the output of the statement:
                 printf(“Integer is: %d; Alphabet is: %cn”,
                 inum, inp);
                where inum contains 15 and inp contains Z.




     Ver. 1.0                                                Slide 38 of 50
Programming in C
Practice: 2.9 (Contd.)


                Solution:
                 Integer is: 15; Alphabet is Z.




     Ver. 1.0                                     Slide 39 of 50
Programming in C
Formatted Input


                • The scanf() function is used for formatted input.
                • The syntax for the scanf() functions is as follows:
                   scanf (format, data1, data2……);
                   Here
                   format       - The format-specification string
                   data1, data2 - Data names where the input data
                                  is to be stored as per the
                                  format-specification string




     Ver. 1.0                                                           Slide 40 of 50
Programming in C
Formatted Input (Contd.)


                • The format-specification string in scanf() consists of:
                      Blanks, tabs, (also called white space characters).
                      New line which are ignored.
                      Conversion consisting of %, an optional number specification
                      specifying the width and a conversion character.
                • While accepting strings using scanf(), a space is
                  considered as a string terminator.




     Ver. 1.0                                                               Slide 41 of 50
Programming in C
Practice: 2.10


                Write a function to accept and display the element number
                and the weight of a Proton. The element number is an
                integer and weight is fractional.




     Ver. 1.0                                                      Slide 42 of 50
Programming in C
Practice: 2.10 (Contd.)


                Solution:
                 #include<stdio.h>
                 main()
                 {
                   int e_num;
                   float e_wt;
                   printf(“Enter the Element No. and Weight of a
                   Protonn”);
                   scanf(“%d %f”, &e_num, &e_wt);
                   fflush(stdin);
                   printf(“The Element No. is: “, e_num);
                   printf(“The weight of a Proton is: %fn“,
                   e_wt);
                 }

     Ver. 1.0                                              Slide 43 of 50
Programming in C
Practice: 2.11


                Write a function to input a string of continuous characters
                with no white space as part of the input. The function should
                assign the input to variables of the types specified in the
                following table.
                  Position of character from   Number of    Type of argument to
                        start of string        characters         assign
                              1                    2                 int
                              3                    4                float
                              7                    2            char (string)
                              9                    3                 int




                The function should also print out each of the assigned data
                items in separate lines.



     Ver. 1.0                                                                     Slide 44 of 50
Programming in C
Practice: 2.11


                Solution:
                 #include<stdio.h>
                 main()
                 {
                   int i,j;
                   char str[3];
                   float fnum;
                   printf(“Enter a string of 11 chrsn”);   /*why
                   11: because 11 is the total length of */
                   /*input.*/
                   scanf(“%2d %4f %2s %3d”,&i, &fnum, str, &j);
                   fflush(stdin);
                   printf(“%2dn %4fn %2sn %3dn”, i, fnum,
                   str, j);
                 }
     Ver. 1.0                                              Slide 45 of 50
Programming in C
Summary


               In this session, you learned that:
                  An operator is a symbol that is used to command the computer
                  to do mathematical or logical manipulations.
                  The operators in C language are classified into the following
                  categories:
                       Logical operators
                       Unary operators
                       Binary operators
                       Ternary operator
                       Compound assignment operators
                       Increment/Decrement operators




    Ver. 1.0                                                           Slide 46 of 50
Programming in C
Summary (Contd.)


               – The logical operators of C and their notations are as follows.

                                 Operator      Notation

                                   OR             ||

                                   AND           &&

                                   NOT            !



               – The unary operator prefixed to an integer constant or variable
                 tells the compiler to reverse the sign by subtracting the value
                 or variable from zero.
               – Binary operators in C language are + (add), - (subtract), *
                 (multiply), / (divide), and % (modulo).
               – Ternary operator offers a shorthand way of writing the
                 commonly used if…else construct.


    Ver. 1.0                                                             Slide 47 of 50
Programming in C
Summary (Contd.)


                 The syntax for using the ternary operator is:
                   (test-expression) ? T-expression : F-expression;
               – Compound assignment operators simplify the statements.
               – Increment / Decrement operators are used to
                 increment/decrement a variable by 1.
               – A for loop is used when the number of execution of the loop
                 is known.
               – The components of a for loop construct are:
                     initialization
                     loop condition
                     reinitialization (increment/decrement)




    Ver. 1.0                                                          Slide 48 of 50
Programming in C
Summary (Contd.)


                 The sequence of execution of a complete for loop is:
                   •   initialization
                   •   evaluation of the loop condition
                   •   the body of the loop
                   •   reinitialization
               – The break and continue statements are used to exit from
                 loop control.
               – The break statement is used to exit from all loop constructs
                 (while, do...while, and for) and switch...case
                 statements.
               – The continue statement is used to skip all subsequent
                 instructions and brings the control back to the loop.
               – The function printf() is used for formatted output to
                 standard output based on a format specification.



    Ver. 1.0                                                            Slide 49 of 50
Programming in C
Summary (Contd.)


               – The syntax of the function printf() is:
                   printf(format, datal, data 2,,..);
               – The function scanf() is used for formatted input from
                 standard input and provides many of the conversion facilities of
                 the function printf().
               – The syntax of the function scanf() is:
                   scanf (format, datal, data2, ...);




    Ver. 1.0                                                            Slide 50 of 50

Contenu connexe

Tendances

Aae oop xp_07
Aae oop xp_07Aae oop xp_07
Aae oop xp_07Niit Care
 
Programming C Language
Programming C LanguageProgramming C Language
Programming C Languagenatarafonseca
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C BasicsBharat Kalia
 
C Programming basics
C Programming basicsC Programming basics
C Programming basicsJitin Pillai
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xiiSyed Zaid Irshad
 
C programming Workshop
C programming WorkshopC programming Workshop
C programming Workshopneosphere
 
Lec 02. C Program Structure / C Memory Concept
Lec 02. C Program Structure / C Memory ConceptLec 02. C Program Structure / C Memory Concept
Lec 02. C Program Structure / C Memory ConceptRushdi Shams
 
2. data, operators, io
2. data, operators, io2. data, operators, io
2. data, operators, iohtaitk
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)sachindane
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language samt7
 

Tendances (19)

Aae oop xp_07
Aae oop xp_07Aae oop xp_07
Aae oop xp_07
 
Programming C Language
Programming C LanguageProgramming C Language
Programming C Language
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
C programming
C programmingC programming
C programming
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 
C Programming basics
C Programming basicsC Programming basics
C Programming basics
 
C language
C languageC language
C language
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
C programming Workshop
C programming WorkshopC programming Workshop
C programming Workshop
 
C Programming
C ProgrammingC Programming
C Programming
 
Lec 02. C Program Structure / C Memory Concept
Lec 02. C Program Structure / C Memory ConceptLec 02. C Program Structure / C Memory Concept
Lec 02. C Program Structure / C Memory Concept
 
2. data, operators, io
2. data, operators, io2. data, operators, io
2. data, operators, io
 
Verilog hdl
Verilog hdlVerilog hdl
Verilog hdl
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
Deep C
Deep CDeep C
Deep C
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language
 

En vedette

C programming session 11
C programming session 11C programming session 11
C programming session 11AjayBahoriya
 
Research and planning March
Research and planning  March Research and planning  March
Research and planning March hannahata2012
 
C programming session 10
C programming session 10C programming session 10
C programming session 10AjayBahoriya
 
C programming session 01
C programming session 01C programming session 01
C programming session 01AjayBahoriya
 
How does your media product represent particular social
How does your media product represent particular socialHow does your media product represent particular social
How does your media product represent particular socialhannahata2012
 
C programming session 16
C programming session 16C programming session 16
C programming session 16AjayBahoriya
 
C programming session 07
C programming session 07C programming session 07
C programming session 07AjayBahoriya
 

En vedette (7)

C programming session 11
C programming session 11C programming session 11
C programming session 11
 
Research and planning March
Research and planning  March Research and planning  March
Research and planning March
 
C programming session 10
C programming session 10C programming session 10
C programming session 10
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
 
How does your media product represent particular social
How does your media product represent particular socialHow does your media product represent particular social
How does your media product represent particular social
 
C programming session 16
C programming session 16C programming session 16
C programming session 16
 
C programming session 07
C programming session 07C programming session 07
C programming session 07
 

Similaire à C programming session 02

C programming session 02
C programming session 02C programming session 02
C programming session 02Dushmanta Nath
 
02 iec t1_s1_oo_ps_session_02
02 iec t1_s1_oo_ps_session_0202 iec t1_s1_oo_ps_session_02
02 iec t1_s1_oo_ps_session_02Pooja Gupta
 
Introduction to C Language - Version 1.0 by Mark John Lado
Introduction to C Language - Version 1.0 by Mark John LadoIntroduction to C Language - Version 1.0 by Mark John Lado
Introduction to C Language - Version 1.0 by Mark John LadoMark John Lado, MIT
 
C programming session 08
C programming session 08C programming session 08
C programming session 08Vivek Singh
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#Raghu nath
 
Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2Naveen Kumar
 
EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5PRADEEP
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxKrishanPalSingh39
 
02 intel v_tune_session_02
02 intel v_tune_session_0202 intel v_tune_session_02
02 intel v_tune_session_02Niit Care
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to cHattori Sidek
 

Similaire à C programming session 02 (20)

C programming session 02
C programming session 02C programming session 02
C programming session 02
 
C sharp chap3
C sharp chap3C sharp chap3
C sharp chap3
 
Java Quiz
Java QuizJava Quiz
Java Quiz
 
02 iec t1_s1_oo_ps_session_02
02 iec t1_s1_oo_ps_session_0202 iec t1_s1_oo_ps_session_02
02 iec t1_s1_oo_ps_session_02
 
Introduction to C Language - Version 1.0 by Mark John Lado
Introduction to C Language - Version 1.0 by Mark John LadoIntroduction to C Language - Version 1.0 by Mark John Lado
Introduction to C Language - Version 1.0 by Mark John Lado
 
C basics
C basicsC basics
C basics
 
C basics
C basicsC basics
C basics
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#
 
Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2
 
Verilogforlab
VerilogforlabVerilogforlab
Verilogforlab
 
C fundamental
C fundamentalC fundamental
C fundamental
 
Report on c
Report on cReport on c
Report on c
 
Aptitute question papers in c
Aptitute question papers in cAptitute question papers in c
Aptitute question papers in c
 
EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Chapter 07
Chapter 07 Chapter 07
Chapter 07
 
02 intel v_tune_session_02
02 intel v_tune_session_0202 intel v_tune_session_02
02 intel v_tune_session_02
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
 

Dernier

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Dernier (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 

C programming session 02

  • 1. Programming in C Objectives In this session, you will learn to: Work with operators Use loops Use formatted input-output functions Ver. 1.0 Slide 1 of 50
  • 2. Programming in C Working with Operators An operator: Is a symbol used to command the computer to do mathematical or logical manipulations. Operates on data and variables. C has a rich set of operators, which can be classified into following various categories: Relational operators Logical operators Unary operators Binary operators Ternary operator Compound assignment operators Increment/Decrement operators Ver. 1.0 Slide 2 of 50
  • 3. Programming in C Logical Operators Notations for logical operators in C are: Operator Notation OR || AND && NOT ! Operator precedence: NOT (!) is evaluated before AND (&&), which is evaluated before OR (||). Brackets () are used to change this order. Ver. 1.0 Slide 3 of 50
  • 4. Programming in C Practice: 2.1 • Write a function that accepts either y or n only as input. For any other character input, an appropriate error message should be displayed and the input is accepted again. Ver. 1.0 Slide 4 of 50
  • 5. Programming in C Practice: 2.1 (Contd.) Solution: #include<stdio.h> main() { char yn; do { puts(“Enter y/n (Yes/No)”); yn=getchar (); fflush (stdin); if(yn!=’y’ && yn!=’n’) puts(“Invalid input”); } while(yn!=’y’ && yn!=’n’); } Ver. 1.0 Slide 5 of 50
  • 6. Programming in C Unary Operators Unary Operators: Operates on a single operand. Prefixed to an integer constant. Tells the compiler to reverse the sign by subtracting the value (or variable) from zero. Has the same effect as the – sign, which is used to indicate a number less than zero, for example -12. Ver. 1.0 Slide 6 of 50
  • 7. Programming in C Practice: 2.2 Which of the following are valid? 1. valuea=-12; /* valuea is int* / 2. valuea = - valueb – 12 /* valuea and valueb both are int */ Ver. 1.0 Slide 7 of 50
  • 8. Programming in C Practice: 2.2 (Contd.) Solution: 1. Valid 2. Valid Ver. 1.0 Slide 8 of 50
  • 9. Programming in C Binary Operators Binary Operators: Operate on two operands. Are as follows: + (add) - (subtract) * (multiply) / (divide) % (modulo) Ver. 1.0 Slide 9 of 50
  • 10. Programming in C Practice: 2.3 In the following set of statements: char ch; ch=’S’; ch=ch+’a’-‘A’; /*statement A*/ ch=ch+’A’-‘a’; /*statement B*/ What will be the value of ch after: 1. Statement A is executed? 2. Statement B is executed? Ver. 1.0 Slide 10 of 50
  • 11. Programming in C Practice: 2.3 (Contd.) Solution: 1. ch is equal to s. Note that ‘a’-‘A’ gives 32 after statement 1 is executed. 2. ch is back to S after statement 2 is executed. Ver. 1.0 Slide 11 of 50
  • 12. Programming in C Binary Operators (Contd.) There are some set or rules, if followed, would prevent unexpected results, at the time of execution of programs: – Any operand of type char is converted to int. – All floats are converted to doubles. – If either operand is double, the other is converted to a double, giving a double result. Ver. 1.0 Slide 12 of 50
  • 13. Programming in C Practice: 2.4 • In which of the following assignments is there no loss of data? (i is an int, f a float, and d a double) i=d; d=f; f=d; i=f+d; d=i+f; 2. Is type casting necessary in the following example? int i,j; float f; double d; d=f+(float) i + j; Ver. 1.0 Slide 13 of 50
  • 14. Programming in C Practice: 2.4 (Contd.) Solution: – a. Loss of data. int set equal to a double. b. No loss of data. double set equal to a float. c. Loss of data. float set equal to a double. d. Loss of data. Right-hand result is a double while left-hand side is just an int. e. No loss of data. Right-hand result is a double and left-hand side is also a double. 2. Not necessary. The ints will automatically be converted to doubles (following the conversion of the float to a double). Ver. 1.0 Slide 14 of 50
  • 15. Programming in C Ternary Operator Ternary Operator: – Is a shorthand method for writing if.else conditional construct. – Helps in reducing lines of code. – Has the following form for the expression using the ternary operator: (test-expression) ? T-expression : F-expression; Ver. 1.0 Slide 15 of 50
  • 16. Programming in C Ternary Operator (Contd.) Consider the following example: if(condition) { Statements if condition is true } else { Statements if condition is false } Can be rewritten using the shorthand operator as follows: larger_of_the_two = ( x > y ) ? x : y; Ver. 1.0 Slide 16 of 50
  • 17. Programming in C Practice: 2.5 1. State whether True or False: In the general form of an expression that uses a ternary operator, the test expression will be checked. If it is true, the T-expression will be evaluated, otherwise the F-expression will be evaluated. 2. What will the following statement do? quotient = (b==0) ? 0 : (a/b); /*a, b, and quotient are ints*/ 3. Can the preceding statement be written as follows? quotient = (b) ? (a/b) : 0; 4. What will the following statement do? always_negative = (j>0) ? j : (-j); Ver. 1.0 Slide 17 of 50
  • 18. Programming in C Practice: 2.5 (Contd.) Solution: – True. – If b is non-zero, it will determine the quotient of a and b. If b equals zero, quotient is set to 0. – Yes. Note that if b is non-zero, the test expression (b) evaluates to true and hence quotient is set to (a/b). – The variable always_negative will always take on a non- negative value, i.e. it will be assigned the absolute value of j. The name of the variable always_negative is just a red herring. Remember that self-documenting variable names will help in writing programs that are readable. Note the unary operator (-j). Ver. 1.0 Slide 18 of 50
  • 19. Programming in C Compound Assignment Operators Compound Assignment Operators: Are useful especially when long variable names are used. Has the following general form: left-value op= right-expression; Here op can be either + (add), - (subtract, * (multiply), / (divide), and % (modulo). Consider the following example: a_very_long_identifier=a_very_long_identifier + 2; It can be written as: a_very_long_identifier += 2; Ver. 1.0 Slide 19 of 50
  • 20. Programming in C Increment / Decrement Operators Increment / Decrement Operators: Are used to increase or decrease the value of a variable by 1. Has the following two forms: The ++ (two plus symbols without a space), called the increment operator while that in ++ before the variable is called the pre increment operator and after the variable is called the post increment operator. The -- (two minus symbols without a space), called the decrement operator while that in ++ before the variable is called the pre decrement operator and after the variable is called the post increment operator. Ver. 1.0 Slide 20 of 50
  • 21. Programming in C Increment / Decrement Operators (Contd.) Consider the following code snippet: total = sum++; /* statement A */ total = ++sum; /* statement B */ The first statement is equivalent to: total = sum; sum = sum + 1; While the second is the same as: sum = sum + 1; total = sum; Ver. 1.0 Slide 21 of 50
  • 22. Programming in C Practice: 2.6 1. Consider the following code snippet: int sum = 3, total = 5; total = sum++; total = ++sum; /*statement A */ total = sum— total = --sum; /*statement B */ What will be the values of total and sum after: a. statement A is executed? b. statement B is executed? Ver. 1.0 Slide 22 of 50
  • 23. Programming in C Practice: 2.6 (Contd.) 1. State whether True or False: The following statement: for(i = 0; i< 100); i = i + 1) { Some statements } can be written as: for (i = 0; i < 100; i++) { Some statements } Ver. 1.0 Slide 23 of 50
  • 24. Programming in C Practice: 2.6 (Contd.) 1. State whether True or False: The for statement in #2 can also be written as: fori = 0; i < 100; ++i)/*Note: ++i and not i++*/ { Some statements } 4. Write a program, which reads in a year and reports on whether it is a leap year or not (centuries should also be considered). Ver. 1.0 Slide 24 of 50
  • 25. Programming in C Practice: 2.6 (Contd.) Solution: 1. total=5, sum=5 total=3, sum=3 quite a complicated way of reducing total by 2. 2. True. i+1 is equivalent to i++. 5. True. i+1 is equivalent to 1+i. 4. Microsoft Word Document Ver. 1.0 Slide 25 of 50
  • 26. Programming in C Using Loops • The while and do…while looping constructs are generally used in situations where the number of execution of the loop is not known. • The for loop construct is used when the number of execution of the loop is known. Ver. 1.0 Slide 26 of 50
  • 27. Programming in C The for Loop Construct The for loop construct: Has three components in the loop control: • Initialization • Condition • Re-initialization (increment/decrement) Has the following sequence of execution: Initialization Evaluation of loop condition Body of loop Re-initialization Ver. 1.0 Slide 27 of 50
  • 28. Programming in C The for Loop Construct (Contd.) The sequence of execution of a complete for loop construct is shown in the following figure. INITIALIZATION FALSE EVALUATE CONDITION TRUE BODY OF LOOP REINITIALIZATION Ver. 1.0 Slide 28 of 50
  • 29. Programming in C The for Loop Construct (Contd.) In a for loop construct: Multiple initializations and/or multiple re- initializations, are separated by commas. Multiple conditions are specified using logical operators. Ver. 1.0 Slide 29 of 50
  • 30. Programming in C Practice: 2.7 1. Write a function to accept twenty characters from the character set, and to display whether the number of lower- case characters is greater than, less than, or equal to number of upper-case characters. Display an error message if the input is not an alphabet. 2. Modify the function to accept characters endlessly until the character ! is input from keyboard. Ver. 1.0 Slide 30 of 50
  • 31. Programming in C Practice: 2.7 (Contd.) Solution: 1. Microsoft Office Word 97 - 2003 Document 2. Microsoft Office Word 97 - 2003 Document Ver. 1.0 Slide 31 of 50
  • 32. Programming in C Controlling the Loop Execution • At times there is a need to exit from a loop before the loop condition is re-evaluated after iteration. • To exit from loop control, break and continue statements are used. Ver. 1.0 Slide 32 of 50
  • 33. Programming in C Practice: 2.8 Write a function, which accepts numbers until 0 is entered or 10 numbers have been accepted. The function prints the total number of entries, the number of positive entries, and the sum of all the positive numbers. Ver. 1.0 Slide 33 of 50
  • 34. Programming in C Practice: 2.8 (Contd.) Solution: Microsoft Office Word 97 - 2003 Document Ver. 1.0 Slide 34 of 50
  • 35. Programming in C Using Formatted Input-Output Functions C provides the following functions for formatted input-output: printf() scanf() Ver. 1.0 Slide 35 of 50
  • 36. Programming in C Formatted Output • Syntax of the formatted output function printf() is: printf (format, data1, data 2, ….); Consider the following example: printf(“%c”, inp); The character specified after % is called a conversion character. The conversion character allows one data type to be converted to another type and printed. Ver. 1.0 Slide 36 of 50
  • 37. Programming in C Formatted Output (Contd.) The conversion characters and their meanings are shown in the following table. Character Meaning d the data is converted to decimal (integer) c the data is taken as a character s the data is a string and characters from the string are printed until a NULL character is reached f the data is output as a double or float with a default precision to 6 Ver. 1.0 Slide 37 of 50
  • 38. Programming in C Practice: 2.9 What is the output of the statement: printf(“Integer is: %d; Alphabet is: %cn”, inum, inp); where inum contains 15 and inp contains Z. Ver. 1.0 Slide 38 of 50
  • 39. Programming in C Practice: 2.9 (Contd.) Solution: Integer is: 15; Alphabet is Z. Ver. 1.0 Slide 39 of 50
  • 40. Programming in C Formatted Input • The scanf() function is used for formatted input. • The syntax for the scanf() functions is as follows: scanf (format, data1, data2……); Here format - The format-specification string data1, data2 - Data names where the input data is to be stored as per the format-specification string Ver. 1.0 Slide 40 of 50
  • 41. Programming in C Formatted Input (Contd.) • The format-specification string in scanf() consists of: Blanks, tabs, (also called white space characters). New line which are ignored. Conversion consisting of %, an optional number specification specifying the width and a conversion character. • While accepting strings using scanf(), a space is considered as a string terminator. Ver. 1.0 Slide 41 of 50
  • 42. Programming in C Practice: 2.10 Write a function to accept and display the element number and the weight of a Proton. The element number is an integer and weight is fractional. Ver. 1.0 Slide 42 of 50
  • 43. Programming in C Practice: 2.10 (Contd.) Solution: #include<stdio.h> main() { int e_num; float e_wt; printf(“Enter the Element No. and Weight of a Protonn”); scanf(“%d %f”, &e_num, &e_wt); fflush(stdin); printf(“The Element No. is: “, e_num); printf(“The weight of a Proton is: %fn“, e_wt); } Ver. 1.0 Slide 43 of 50
  • 44. Programming in C Practice: 2.11 Write a function to input a string of continuous characters with no white space as part of the input. The function should assign the input to variables of the types specified in the following table. Position of character from Number of Type of argument to start of string characters assign 1 2 int 3 4 float 7 2 char (string) 9 3 int The function should also print out each of the assigned data items in separate lines. Ver. 1.0 Slide 44 of 50
  • 45. Programming in C Practice: 2.11 Solution: #include<stdio.h> main() { int i,j; char str[3]; float fnum; printf(“Enter a string of 11 chrsn”); /*why 11: because 11 is the total length of */ /*input.*/ scanf(“%2d %4f %2s %3d”,&i, &fnum, str, &j); fflush(stdin); printf(“%2dn %4fn %2sn %3dn”, i, fnum, str, j); } Ver. 1.0 Slide 45 of 50
  • 46. Programming in C Summary In this session, you learned that: An operator is a symbol that is used to command the computer to do mathematical or logical manipulations. The operators in C language are classified into the following categories: Logical operators Unary operators Binary operators Ternary operator Compound assignment operators Increment/Decrement operators Ver. 1.0 Slide 46 of 50
  • 47. Programming in C Summary (Contd.) – The logical operators of C and their notations are as follows. Operator Notation OR || AND && NOT ! – The unary operator prefixed to an integer constant or variable tells the compiler to reverse the sign by subtracting the value or variable from zero. – Binary operators in C language are + (add), - (subtract), * (multiply), / (divide), and % (modulo). – Ternary operator offers a shorthand way of writing the commonly used if…else construct. Ver. 1.0 Slide 47 of 50
  • 48. Programming in C Summary (Contd.) The syntax for using the ternary operator is: (test-expression) ? T-expression : F-expression; – Compound assignment operators simplify the statements. – Increment / Decrement operators are used to increment/decrement a variable by 1. – A for loop is used when the number of execution of the loop is known. – The components of a for loop construct are: initialization loop condition reinitialization (increment/decrement) Ver. 1.0 Slide 48 of 50
  • 49. Programming in C Summary (Contd.) The sequence of execution of a complete for loop is: • initialization • evaluation of the loop condition • the body of the loop • reinitialization – The break and continue statements are used to exit from loop control. – The break statement is used to exit from all loop constructs (while, do...while, and for) and switch...case statements. – The continue statement is used to skip all subsequent instructions and brings the control back to the loop. – The function printf() is used for formatted output to standard output based on a format specification. Ver. 1.0 Slide 49 of 50
  • 50. Programming in C Summary (Contd.) – The syntax of the function printf() is: printf(format, datal, data 2,,..); – The function scanf() is used for formatted input from standard input and provides many of the conversion facilities of the function printf(). – The syntax of the function scanf() is: scanf (format, datal, data2, ...); Ver. 1.0 Slide 50 of 50

Notes de l'éditeur

  1. Begin the session by explaining the objectives of the session.
  2. Tell the students that they cannot create a useful programs without using the operators. A simple program such as adding two variables and showing the result needs the use of variables.
  3. Operator precedence is very important in a program. If the operator precedence is not considered then the program might produce an unexpected result. Give an example, which produces a result different from the expected result because of incorrect operator precedence.
  4. Use Slide 4 to test the student’s understanding on logical operators.
  5. Use Slide 7 to test the student’s understanding on unary operators.
  6. Use Slide 10 to test the student’s understanding on binary operators.
  7. Use this slide to test the student’s understanding on binary operators.
  8. Use this slide to test the student’s understanding on ternary operators.
  9. Use this slide to test the student’s understanding on increment/decrement operators.
  10. Explain definite and indefinite loops. Give some examples, which distinguish between definite and indefinite loops.
  11. The for loop consists of three parts : Initialization Condition Re-initialization (increment/decrement) In a for loop, after initialization, the condition is first checked. If the condition is valid, the body of the for loop is executed. For each iteration, re-initialization is done before the condition is checked again. Any or all of these parts may be left out of the construct. For example : for ( ; ; ) { } is an infinite loop (as there is no condition).
  12. Use this slide to test the student’s understanding on loops.
  13. Use this slide to test the student’s understanding on controlling the loop execution.
  14. When used with strings, the format string could be quite confusing. The statement: printf ( “%15.5s”, string) prints the first 5 characters of the string right-justified in 15 spaces. When used with floats, it represents the precision required.
  15. Use this slide to test the student’s understanding on formatted output.
  16. Use this slide to test the student’s understanding on formatted input.
  17. Use this slide to test the student’s understanding on formatted input-output.
  18. The output buffer is flushed only if it is full, or if the string to be printed contains a newline character at the end or if it is explicitly flushed using fflush () . The last option is used if the string does not contain a new line character. The string might not be displayed at the right place at the right time otherwise.
  19. Use this and the next 4 slides to summarize this session.