You are on page 1of 11

' $

PDS Tutorial: IV (CS 11001): Section 9 Dept. of CS&Engg., IIT Kharagpur 1

Tutorial

 

Programming & Data Structure: CS 11001 
 

 
Section - 9/C
 
DO NOT POWER ON THE MACHINE 
Department of Computer Science and Engineering
I.I.T. Kharagpur
Autumn Semester: 2007 - 2008 (17.08.2007)

& %
' $
PDS Tutorial: IV (CS 11001): Section 9 Dept. of CS&Engg., IIT Kharagpur 2

Download

Download the file tut170807.ps from


Programming & Data Structures ... of

http://www.facweb.iitkgp.ernet.in/∼goutam

View the file using the command kghostview & or


ggv &

& %
' $
PDS Tutorial: IV (CS 11001): Section 9 Dept. of CS&Engg., IIT Kharagpur 3

Tutorial IV.I

Write a C program that reads n integers


(n ≥ 2) and prints the second largest among
them. The number of integers n is a data.

& %
' $
PDS Tutorial: IV (CS 11001): Section 9 Dept. of CS&Engg., IIT Kharagpur 4

Tutorial IV.II

Solve the previous problem when the number of


integers is is not a data. Use the return value of
scanf() or the eof() function. Take care of cases
when no input or only one input is provided
and the second largest is not defined.

& %
' $
PDS Tutorial: IV (CS 11001): Section 9 Dept. of CS&Engg., IIT Kharagpur 5

getchar() and putchar()

You may use getchar() to read a character from


the stdin (keyboard) and print the character
using putchar() in the stdout (VDU).

& %
' $
PDS Tutorial: IV (CS 11001): Section 9 Dept. of CS&Engg., IIT Kharagpur 6

#include <stdio.h>
int main(){ // tutIV.3.c
char c ;

c = getchar() ;
putchar(c) ;
putchar(’\n’) ;
return 0 ;
}

& %
' $
PDS Tutorial: IV (CS 11001): Section 9 Dept. of CS&Engg., IIT Kharagpur 7

Loop Termination

Character read can be used to control a loop.


As an example a loop can be terminated after
reading the end of the line ’\n’ (newline) or at
the end-of-file EOF (Ctrl-D).

& %
' $
PDS Tutorial: IV (CS 11001): Section 9 Dept. of CS&Engg., IIT Kharagpur 8

#include <stdio.h>
int main(){ // tutIV.4.c
char c ;

while((c = getchar()) != ’\n’)


putchar(c) ;
putchar(’\n’) ;
return 0 ;
}

& %
' $
PDS Tutorial: IV (CS 11001): Section 9 Dept. of CS&Engg., IIT Kharagpur 9

ASCII to Number

The face value of a digit d can be extracted by


subtracting the ASCII code of character ‘0’
from the ASCII code of d.

& %
' $
PDS Tutorial: IV (CS 11001): Section 9 Dept. of CS&Engg., IIT Kharagpur 10

#include <stdio.h>
int main(){ // tutIV.5.c
char c ;
c = getchar() ;
printf("val(%c) = %d\n", c, c - ’0’) ;
return 0 ;
}

& %
' $
PDS Tutorial: IV (CS 11001): Section 9 Dept. of CS&Engg., IIT Kharagpur 11

Tutorial IV.III

Write a C program that reads a sequence of


decimal digits as characters (not more than 9
digits) and converts it to its integral value and
prints it as hex numeral.
Input: 1234 - read as characters 1, 2, 3, 4
Output: 4D2

& %

You might also like