SlideShare una empresa de Scribd logo
1 de 27
Basic Programs in C
Structure Of C Program
• C programs consist of one or more functions. Each function
   performs a specific task. A function is a group or sequence of
   C statements that are executed together.
• The following is a simple C program that prints a message on
   the screen.
/* A simple program for printing a message */
# include <stdio.h>
# include <conio.h>
void main( )
{
   clrscr( );
   printf(“Welcome to C”);
   getch( );
}
Description
• The first line
/* A simple program for printing a message */
   is a comment line. Comments in the c program are optional
   and may appear anywhere in a C program. Comments are
   enclosed between /* and */.
• The second line
# include <stdio.h>
    tells the compiler to read the file stdio.h and include its
   contents in this file. stdio.h, one of header files, contain the
   information about input and output functions. stdio.h means
   Standard Input Output Header file. This file contains the
   information about printf() function.
Description (contd..)
The third line
# include <conio.h>
• tells the compiler to read the file conio.h and include its contents in this
    file. conio.h means Consoled Input Output Header file. This file contains
    the information about clrscr() and getch() functions.
The fourth line
void main( )
• is the stat of the main program. The word main is followed by a pair of
    ordinary parenthesis ( ), which indicates that main is also a function.
The fifth line
    {
• the left brace represents the beginning of the program.
The sixth line
    clrscr( );
• tells the compiler to clear the screen and kept the cursor at left side
    corner.
Description (contd..)
The seventh line
   printf( “Welcome to C”);
this function causes its arguments to be printed on the
   screen on the computer.
The eight line
   getch( );
is reads the single character directly from the keyboard
   without printing on the screen.
The ninth line
  }
the right brace represents the ending of the program.
Writing a C program
 1. All C statements must end with semicolon.
 2. C is case-sensitive. That is, upper case and lower case
    characters are different. Generally the statements are typed
    in lower case.
 3. A C statement can be written in one line or it can split into
    multiple lines.
 4. Braces must always match upon pairs, i.e., every opening
    brace { must have a matching closing brace }.
 5. Every C program starts with void main( ) function.
 6. Comments cannot be nested. For example,
/* Welcome to ‘C’ ,/* programming*/ */
 – A comment can be split into more than one line.
Execution of C Program
Steps to be followed in writing and running a C program.
• Creation of Source Program
Create a C program file in various C compilers are available
   under MS-DOS, Turbo C Editor etc.
• Compilation of the Program
Turbo C compiler is user friendly and provides integrated
   program development environment. Thus, selecting key
   combination can do compilation. That means press Alt +
   F9 for compilation.
• Program Execution
In Turbo C environment, the RUN option will do the
   compilation and execution of a program. Press Ctrl + F9
   for execution the program.
Execution
Printf() Function
• The printf( ) function is used to write information to standard
  output (normally monitor screen). The structure of this function is
• printf(format string, list of arguments); e.g. printf(“%d”,a)
The format string contains the following:
• Characters that are simply printed on the screen.
• Specifications that begin with a % sign and define the output
  format for display of each item.
•   Escape sequence characters that begin with a  sign such as n, t
  etc Character    Argument              Resulting Output


            c     Character   A single character

           d      Integer     Signed decimal integer

            s     String      Prints character strings

            f     Floating    Single floating point number
                  point
Scanf(),Getting input from user
• The real power of a technical C program is its ability to
  interact with the program user. This means that the
  program gets input values for variables from users.
• The scanf( ) function is a built-in C function that
  allows a program to get user input from the keyboard.
  The structure of this function is
• scanf(format string &list of arguments);
Examples
•     scanf(“%d”, &a );
•     scanf(“%d %c %f ”,&a, &b, &c );
Control Structures
• The control flow statements of a language determine
  the order in which the statements are executed.
• We also need to be able to specify that a statement, or a
  group of statements, is to be carried out conditionally,
  only if some condition is true.
• Also we need to be able to carry out a statement or a
  group of statements repeatedly based on certain
  conditions.
• These kinds of situations are described in C using
  Conditional Control and Loop Control structures.
Conditional & Loop Structure
A conditional structure can be implemented in C
  using
• The if statement
• The if-else statement
• The nested if-else statement
• The switch statement.
Whereas loop control structures can be implemented
  in C using
• while loop
• do-while loop
• for statement
The ‘If’ Statement
• The if statement is used to control the flow of execution of
  statements. The general form of if statement is
•      if (condition)
•      statement;
Suppose if it is required to include more than one statement, then
  a compound statement is used, in place of single statement.
  The form of compound statement is
• if (condition)
• {statement1;
  statement2;
  }
• If the condition is true, then the statements will be executed.
  If the condition is false, then the statement/statements will not
  be executed.
If –else statement
The general form of if-else statement is…
• if (condition)
          statement1;
else
          statement2;
• If the condition is true, then statement1 is executed. Otherwise if the
    condition is false, then the statement2 is executed. Here statements
    statement1 and statement2 are either simple statements or compound
    statements.
•         if (condtion)
          {        statements                  /* if block */
          }
          else
          {        statements                  /* else */
          }
Example of ‘If-else’
/* Inputting year is Leap or not */
#include<conio.h>
#include<stdio.h>
   int main(){
                                                Sample output:
                                                Enter any year: 2010
   int year;                                    2010 is not a leap year
   printf("Enter any year: ");
   scanf("%d",&year);                            Enter any year: 2100
   if((year%4)==0)                               2100 is not a leap
                                                 year
       printf("%d is a leap year",year);
   else                                         Enter any year: 2000
       printf("%d is not a leap year", year);   2000 is a leap year
   return 0;
}
Example
• // Single digit or not
#include<stdio.h>
#include<conio.h>                  Output 1
void main()                        Enter a number:5
{ int n;                           Single digit
   clrscr();                       Output 2
                                   Enter a number:12
   printf(“Enter a number:”);
                                   Not single digit
   scanf(“%d”,&n);
   if(n<=9)
   printf(“Single digit”);
   else
   printf(“Not single digit”);
   getch(); }
Nested If-else
                             /* A quick demo of nested if-else */
• We can also write an       main( )
  entire if-else             {
  construct within           int i ;
                             printf ( "Enter either 1 or 2 " ) ;
  either the body of the     scanf ( "%d", &i ) ;
  if statement or the        if ( i == 1 )
  body of an else            printf ( "You have entered 1" ) ;
  statement.                 else
                             {
• This is called ‘nesting’   if ( i == 2 )
  of ifs. This is shown      printf ( " You have entered 2" );
  in the program.            else
                             printf ( “You have entered wrong entry”) ;
                             }
                             }
Decision Using Switch
• The control statement that allows us to make a decision from
   the number of choices is called a switch, or more correctly a
   switch case-default, since these three keywords go together
   to make up the control statement. They most often appear as
   follows:
switch ( integer expression )
{ case constant 1 :
do this ;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;}
Without Break keyword
• The integer expression following   main( )
  the keyword switch is any C        {
                                     int i = 2 ;
  expression that will yield an
                                     switch ( i )
  integer value.                     {
• It could be an integer constant    case 1 :
  like 1,2 or an expression that     printf ( "I am in case 1 n" ) ;
  evaluates to an integer.           case 2 :
• The keyword case is followed by    printf ( "I am in case 2 n" ) ;
                                     case 3 :
  an integer or a character
                                     printf ( "I am in case 3 n" ) ;
  constant. Each constant in each    default :
  case must be different from all    printf ( "I am in default n" );
  the others.                        }
                                     }
Use of Break
• If you want that only case     main( )
  2 should get executed, it      {
  is up to you to get out of     int i = 2 ;
  the switch then and there      switch ( i )
                                 {
  by using a break
                                 case 1 :
  statement.
                                 printf ( "I am in case 1 n" ) ;
 Note :-there is no need for a   break ;
  break statement after the      case 2 :
  default, since the control     printf ( "I am in case 2 n" ) ;
  comes out of the switch        break ;
  anyway.                        case 3 :
                                 printf ( "I am in case 3 n" ) ;
                                 break ;
                                 default :
                                 printf ( "I am in default n" ) ;
                                 }
Flowchart
Examples
main( )
{
int i = 22 ;
switch ( i )
{
case 121 :
printf ( "I am in case 121 n" ) ;       • The output of
break ;                                     this program
case 7 :                                    would be:
printf ( "I am in case 7 n" ) ;
break ;                                  I am in case 22
case 22 :
printf ( "I am in case 22 n" ) ;
break ;
default :
printf ( "I am in default n" ) ;
}
}
Examples
main()
{                                     •The output of this
char c = 'x' ;
                                      program would be:
switch ( c )
{
                                      I am in case x
case 'v' :
                                      •In fact here when we
printf ( "I am in case v n" ) ;
break ;
                                      use ‘v’, ‘a’, ‘x’ they are
case 'a' :                            actually replaced by the
printf ( "I am in case a n" ) ;      ASCII values (118, 97,
break ;                               120) of these character
case 'x' :                            constants.
printf ( "I am in case x n" ) ;
break ;
default :
printf ( "I am in default n" ) ;}}
Some Points about Switch-Case
• A float expression cannot be tested using a switch
• Cases can never have variable expressions (for example it is
    wrong to say case a +3 : )
• Multiple cases cannot use same expressions. Thus the
    following switch is illegal
• switch ( a )
{
case 3 :
...
case 1 + 2 :
….
}
goto Keyword
• The use of goto should be avoided because after using it
  programs become unreliable, unreadable and hard to debug.
• In a difficult programming situation it seems so easy to use a
  goto to take the control where you want.
• The big problem with gotos is that when we do use them we
  can never be sure how we got to a certain point in our code.
• They obscure the flow of control. So as far as possible skip
  them.
Example
main()
{ int goals ;
printf ( "Enter the number of goals scored against England" ) ;
scanf ( "%d", &goals ) ;
if ( goals <= 5 )
goto sos ;
else
{
printf ( “soccer players n“ );
printf ( “Say goodbye to soccer" ) ;
exit( ) ; /* terminates program execution */
}
sos :
printf ( “Out of the execution!" ) ;}
• If the condition is satisfied the goto statement transfers
  control to the label ‘sos’, causing printf( ) following sos to
  be executed.
• The label can be on a separate line or on the same line as the
  statement following it, as in,
sos : printf ( "To err is human!" ) ;

Any number of gotos can take the control to the same label.
The exit( ) function is a standard library function which
   terminates the execution of the program. It is necessary to
   use this function since we don't want the statement
printf ( “Out of Execution”);
to get executed after execution of the else block.

Más contenido relacionado

La actualidad más candente

La actualidad más candente (19)

C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
C programming Workshop
C programming WorkshopC programming Workshop
C programming Workshop
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
C fundamentals
C fundamentalsC fundamentals
C fundamentals
 
C if else
C if elseC if else
C if else
 
C Prog. - Decision & Loop Controls
C Prog. - Decision & Loop ControlsC Prog. - Decision & Loop Controls
C Prog. - Decision & Loop Controls
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
 
Lecture 14 - Scope Rules
Lecture 14 - Scope RulesLecture 14 - Scope Rules
Lecture 14 - Scope Rules
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
Decision making statements in C
Decision making statements in CDecision making statements in C
Decision making statements in C
 
C operators
C operatorsC operators
C operators
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
Session 3
Session 3Session 3
Session 3
 
C program compiler presentation
C program compiler presentationC program compiler presentation
C program compiler presentation
 
Unit 5. Control Statement
Unit 5. Control StatementUnit 5. Control Statement
Unit 5. Control Statement
 
'C' language notes (a.p)
'C' language notes (a.p)'C' language notes (a.p)
'C' language notes (a.p)
 

Destacado

Simple C programs
Simple C programsSimple C programs
Simple C programsab11cs001
 
handling input output and control statements
 handling input output and control statements handling input output and control statements
handling input output and control statementsRai University
 
c-programming-using-pointers
c-programming-using-pointersc-programming-using-pointers
c-programming-using-pointersSushil Mishra
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_outputAnil Dutt
 
LAMP (Loop Mediated Isothermal Amplification)
LAMP (Loop Mediated Isothermal Amplification)LAMP (Loop Mediated Isothermal Amplification)
LAMP (Loop Mediated Isothermal Amplification)Varij Nayan
 

Destacado (7)

Simple C programs
Simple C programsSimple C programs
Simple C programs
 
handling input output and control statements
 handling input output and control statements handling input output and control statements
handling input output and control statements
 
c-programming-using-pointers
c-programming-using-pointersc-programming-using-pointers
c-programming-using-pointers
 
C Programming
C ProgrammingC Programming
C Programming
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_output
 
Structure of a C program
Structure of a C programStructure of a C program
Structure of a C program
 
LAMP (Loop Mediated Isothermal Amplification)
LAMP (Loop Mediated Isothermal Amplification)LAMP (Loop Mediated Isothermal Amplification)
LAMP (Loop Mediated Isothermal Amplification)
 

Similar a Lec 10

Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
1584503386 1st chap
1584503386 1st chap1584503386 1st chap
1584503386 1st chapthuhiendtk4
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.Haard Shah
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxAnkitaVerma776806
 
Fundamentals of programming)
Fundamentals of programming)Fundamentals of programming)
Fundamentals of programming)jakejakejake2
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in Csana shaikh
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptxeaglesniper008
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Functionimtiazalijoono
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programmingnmahi96
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
 
Decision statements in c laguage
Decision statements in c laguageDecision statements in c laguage
Decision statements in c laguageTanmay Modi
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notesSrikanth
 
C_Language_PS&PC_Notes.ppt
C_Language_PS&PC_Notes.pptC_Language_PS&PC_Notes.ppt
C_Language_PS&PC_Notes.pptganeshkarthy
 
Programming basics
Programming basicsProgramming basics
Programming basics246paa
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Shipra Swati
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02CIMAP
 

Similar a Lec 10 (20)

Control structure of c
Control structure of cControl structure of c
Control structure of c
 
1584503386 1st chap
1584503386 1st chap1584503386 1st chap
1584503386 1st chap
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
Programming in C
Programming in CProgramming in C
Programming in C
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
Fundamentals of programming)
Fundamentals of programming)Fundamentals of programming)
Fundamentals of programming)
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptx
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
Decision statements in c laguage
Decision statements in c laguageDecision statements in c laguage
Decision statements in c laguage
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
 
if,loop,switch
if,loop,switchif,loop,switch
if,loop,switch
 
C_Language_PS&PC_Notes.ppt
C_Language_PS&PC_Notes.pptC_Language_PS&PC_Notes.ppt
C_Language_PS&PC_Notes.ppt
 
Programming basics
Programming basicsProgramming basics
Programming basics
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
 
UNIT-II CP DOC.docx
UNIT-II CP DOC.docxUNIT-II CP DOC.docx
UNIT-II CP DOC.docx
 

Más de kapil078

12 lec 12 loop
12 lec 12 loop 12 lec 12 loop
12 lec 12 loop kapil078
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage classkapil078
 
Btech 1st yr midterm 1st
Btech 1st yr midterm 1stBtech 1st yr midterm 1st
Btech 1st yr midterm 1stkapil078
 
Cmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowchartsCmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowchartskapil078
 
Cmp104 lec 6 computer lang
Cmp104 lec 6 computer langCmp104 lec 6 computer lang
Cmp104 lec 6 computer langkapil078
 
Cmp104 lec 2 number system
Cmp104 lec 2 number systemCmp104 lec 2 number system
Cmp104 lec 2 number systemkapil078
 
Cmp104 lec 6 computer lang
Cmp104 lec 6 computer langCmp104 lec 6 computer lang
Cmp104 lec 6 computer langkapil078
 
Cmp104 lec 4 types of computer
Cmp104 lec 4 types of computerCmp104 lec 4 types of computer
Cmp104 lec 4 types of computerkapil078
 
Cmp104 lec 3 component of computer
Cmp104 lec 3 component of computerCmp104 lec 3 component of computer
Cmp104 lec 3 component of computerkapil078
 
Cmp104 lec 1
Cmp104 lec 1Cmp104 lec 1
Cmp104 lec 1kapil078
 
cmp104 lec 8
cmp104 lec 8cmp104 lec 8
cmp104 lec 8kapil078
 

Más de kapil078 (13)

12 lec 12 loop
12 lec 12 loop 12 lec 12 loop
12 lec 12 loop
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
 
Btech 1st yr midterm 1st
Btech 1st yr midterm 1stBtech 1st yr midterm 1st
Btech 1st yr midterm 1st
 
Lec9
Lec9Lec9
Lec9
 
Cmp 104
Cmp 104Cmp 104
Cmp 104
 
Cmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowchartsCmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowcharts
 
Cmp104 lec 6 computer lang
Cmp104 lec 6 computer langCmp104 lec 6 computer lang
Cmp104 lec 6 computer lang
 
Cmp104 lec 2 number system
Cmp104 lec 2 number systemCmp104 lec 2 number system
Cmp104 lec 2 number system
 
Cmp104 lec 6 computer lang
Cmp104 lec 6 computer langCmp104 lec 6 computer lang
Cmp104 lec 6 computer lang
 
Cmp104 lec 4 types of computer
Cmp104 lec 4 types of computerCmp104 lec 4 types of computer
Cmp104 lec 4 types of computer
 
Cmp104 lec 3 component of computer
Cmp104 lec 3 component of computerCmp104 lec 3 component of computer
Cmp104 lec 3 component of computer
 
Cmp104 lec 1
Cmp104 lec 1Cmp104 lec 1
Cmp104 lec 1
 
cmp104 lec 8
cmp104 lec 8cmp104 lec 8
cmp104 lec 8
 

Lec 10

  • 2. Structure Of C Program • C programs consist of one or more functions. Each function performs a specific task. A function is a group or sequence of C statements that are executed together. • The following is a simple C program that prints a message on the screen. /* A simple program for printing a message */ # include <stdio.h> # include <conio.h> void main( ) { clrscr( ); printf(“Welcome to C”); getch( ); }
  • 3. Description • The first line /* A simple program for printing a message */ is a comment line. Comments in the c program are optional and may appear anywhere in a C program. Comments are enclosed between /* and */. • The second line # include <stdio.h> tells the compiler to read the file stdio.h and include its contents in this file. stdio.h, one of header files, contain the information about input and output functions. stdio.h means Standard Input Output Header file. This file contains the information about printf() function.
  • 4. Description (contd..) The third line # include <conio.h> • tells the compiler to read the file conio.h and include its contents in this file. conio.h means Consoled Input Output Header file. This file contains the information about clrscr() and getch() functions. The fourth line void main( ) • is the stat of the main program. The word main is followed by a pair of ordinary parenthesis ( ), which indicates that main is also a function. The fifth line { • the left brace represents the beginning of the program. The sixth line clrscr( ); • tells the compiler to clear the screen and kept the cursor at left side corner.
  • 5. Description (contd..) The seventh line printf( “Welcome to C”); this function causes its arguments to be printed on the screen on the computer. The eight line getch( ); is reads the single character directly from the keyboard without printing on the screen. The ninth line } the right brace represents the ending of the program.
  • 6. Writing a C program 1. All C statements must end with semicolon. 2. C is case-sensitive. That is, upper case and lower case characters are different. Generally the statements are typed in lower case. 3. A C statement can be written in one line or it can split into multiple lines. 4. Braces must always match upon pairs, i.e., every opening brace { must have a matching closing brace }. 5. Every C program starts with void main( ) function. 6. Comments cannot be nested. For example, /* Welcome to ‘C’ ,/* programming*/ */ – A comment can be split into more than one line.
  • 7. Execution of C Program Steps to be followed in writing and running a C program. • Creation of Source Program Create a C program file in various C compilers are available under MS-DOS, Turbo C Editor etc. • Compilation of the Program Turbo C compiler is user friendly and provides integrated program development environment. Thus, selecting key combination can do compilation. That means press Alt + F9 for compilation. • Program Execution In Turbo C environment, the RUN option will do the compilation and execution of a program. Press Ctrl + F9 for execution the program.
  • 9. Printf() Function • The printf( ) function is used to write information to standard output (normally monitor screen). The structure of this function is • printf(format string, list of arguments); e.g. printf(“%d”,a) The format string contains the following: • Characters that are simply printed on the screen. • Specifications that begin with a % sign and define the output format for display of each item. • Escape sequence characters that begin with a sign such as n, t etc Character Argument Resulting Output c Character A single character d Integer Signed decimal integer s String Prints character strings f Floating Single floating point number point
  • 10. Scanf(),Getting input from user • The real power of a technical C program is its ability to interact with the program user. This means that the program gets input values for variables from users. • The scanf( ) function is a built-in C function that allows a program to get user input from the keyboard. The structure of this function is • scanf(format string &list of arguments); Examples • scanf(“%d”, &a ); • scanf(“%d %c %f ”,&a, &b, &c );
  • 11. Control Structures • The control flow statements of a language determine the order in which the statements are executed. • We also need to be able to specify that a statement, or a group of statements, is to be carried out conditionally, only if some condition is true. • Also we need to be able to carry out a statement or a group of statements repeatedly based on certain conditions. • These kinds of situations are described in C using Conditional Control and Loop Control structures.
  • 12. Conditional & Loop Structure A conditional structure can be implemented in C using • The if statement • The if-else statement • The nested if-else statement • The switch statement. Whereas loop control structures can be implemented in C using • while loop • do-while loop • for statement
  • 13. The ‘If’ Statement • The if statement is used to control the flow of execution of statements. The general form of if statement is • if (condition) • statement; Suppose if it is required to include more than one statement, then a compound statement is used, in place of single statement. The form of compound statement is • if (condition) • {statement1; statement2; } • If the condition is true, then the statements will be executed. If the condition is false, then the statement/statements will not be executed.
  • 14. If –else statement The general form of if-else statement is… • if (condition) statement1; else statement2; • If the condition is true, then statement1 is executed. Otherwise if the condition is false, then the statement2 is executed. Here statements statement1 and statement2 are either simple statements or compound statements. • if (condtion) { statements /* if block */ } else { statements /* else */ }
  • 15. Example of ‘If-else’ /* Inputting year is Leap or not */ #include<conio.h> #include<stdio.h> int main(){ Sample output: Enter any year: 2010 int year; 2010 is not a leap year printf("Enter any year: "); scanf("%d",&year); Enter any year: 2100 if((year%4)==0) 2100 is not a leap year printf("%d is a leap year",year); else Enter any year: 2000 printf("%d is not a leap year", year); 2000 is a leap year return 0; }
  • 16. Example • // Single digit or not #include<stdio.h> #include<conio.h> Output 1 void main() Enter a number:5 { int n; Single digit clrscr(); Output 2 Enter a number:12 printf(“Enter a number:”); Not single digit scanf(“%d”,&n); if(n<=9) printf(“Single digit”); else printf(“Not single digit”); getch(); }
  • 17. Nested If-else /* A quick demo of nested if-else */ • We can also write an main( ) entire if-else { construct within int i ; printf ( "Enter either 1 or 2 " ) ; either the body of the scanf ( "%d", &i ) ; if statement or the if ( i == 1 ) body of an else printf ( "You have entered 1" ) ; statement. else { • This is called ‘nesting’ if ( i == 2 ) of ifs. This is shown printf ( " You have entered 2" ); in the program. else printf ( “You have entered wrong entry”) ; } }
  • 18. Decision Using Switch • The control statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switch case-default, since these three keywords go together to make up the control statement. They most often appear as follows: switch ( integer expression ) { case constant 1 : do this ; case constant 2 : do this ; case constant 3 : do this ; default : do this ;}
  • 19. Without Break keyword • The integer expression following main( ) the keyword switch is any C { int i = 2 ; expression that will yield an switch ( i ) integer value. { • It could be an integer constant case 1 : like 1,2 or an expression that printf ( "I am in case 1 n" ) ; evaluates to an integer. case 2 : • The keyword case is followed by printf ( "I am in case 2 n" ) ; case 3 : an integer or a character printf ( "I am in case 3 n" ) ; constant. Each constant in each default : case must be different from all printf ( "I am in default n" ); the others. } }
  • 20. Use of Break • If you want that only case main( ) 2 should get executed, it { is up to you to get out of int i = 2 ; the switch then and there switch ( i ) { by using a break case 1 : statement. printf ( "I am in case 1 n" ) ; Note :-there is no need for a break ; break statement after the case 2 : default, since the control printf ( "I am in case 2 n" ) ; comes out of the switch break ; anyway. case 3 : printf ( "I am in case 3 n" ) ; break ; default : printf ( "I am in default n" ) ; }
  • 22. Examples main( ) { int i = 22 ; switch ( i ) { case 121 : printf ( "I am in case 121 n" ) ; • The output of break ; this program case 7 : would be: printf ( "I am in case 7 n" ) ; break ; I am in case 22 case 22 : printf ( "I am in case 22 n" ) ; break ; default : printf ( "I am in default n" ) ; } }
  • 23. Examples main() { •The output of this char c = 'x' ; program would be: switch ( c ) { I am in case x case 'v' : •In fact here when we printf ( "I am in case v n" ) ; break ; use ‘v’, ‘a’, ‘x’ they are case 'a' : actually replaced by the printf ( "I am in case a n" ) ; ASCII values (118, 97, break ; 120) of these character case 'x' : constants. printf ( "I am in case x n" ) ; break ; default : printf ( "I am in default n" ) ;}}
  • 24. Some Points about Switch-Case • A float expression cannot be tested using a switch • Cases can never have variable expressions (for example it is wrong to say case a +3 : ) • Multiple cases cannot use same expressions. Thus the following switch is illegal • switch ( a ) { case 3 : ... case 1 + 2 : …. }
  • 25. goto Keyword • The use of goto should be avoided because after using it programs become unreliable, unreadable and hard to debug. • In a difficult programming situation it seems so easy to use a goto to take the control where you want. • The big problem with gotos is that when we do use them we can never be sure how we got to a certain point in our code. • They obscure the flow of control. So as far as possible skip them.
  • 26. Example main() { int goals ; printf ( "Enter the number of goals scored against England" ) ; scanf ( "%d", &goals ) ; if ( goals <= 5 ) goto sos ; else { printf ( “soccer players n“ ); printf ( “Say goodbye to soccer" ) ; exit( ) ; /* terminates program execution */ } sos : printf ( “Out of the execution!" ) ;}
  • 27. • If the condition is satisfied the goto statement transfers control to the label ‘sos’, causing printf( ) following sos to be executed. • The label can be on a separate line or on the same line as the statement following it, as in, sos : printf ( "To err is human!" ) ; Any number of gotos can take the control to the same label. The exit( ) function is a standard library function which terminates the execution of the program. It is necessary to use this function since we don't want the statement printf ( “Out of Execution”); to get executed after execution of the else block.