SlideShare a Scribd company logo
6.087 Lecture 4 – January 14, 2010
Review
Control flow
I/O
Standard I/O
String I/O
File I/O
1
Blocks
• Blocks combine multiple statements into a single unit.
• Can be used when a single statement is expected.
• Creates a local scope (variables declared inside are local
to the block).
• Blocks can be nested.
{
in t x =0;
{
int y=0; / ∗ both x and y v i s i b l e ∗ /
}
/ ∗ only x v i s i b l e ∗ /
}
1
Conditional blocks
if ... else..else if is used for conditional branching of execution
i f ( cond )
{
/ ∗ code executed i f cond i s tru e ∗ /
}
else
{
/ ∗ code executed i f cond i s fa l s e ∗ /
}
2
Conditional blocks
switch..case is used to test multiple conditions (more efficient
than if else ladders).
switch ( opt )
{
case ’A’ :
/ ∗ execute i f opt == ’A ’ ∗ /
break ;
case ’B’ :
case ’C’ :
/ ∗ execute i f opt == ’B ’ | | opt == ’C ’ ∗ /
default :
}
3
Iterative blocks
• while loop tests condition before execution of the block.
• do..while loop tests condition after execution of the block.
• for loop provides initialization, testing and iteration together.
4
6.087 Lecture 4 – January 14, 2010
Review
Control flow
I/O
Standard I/O
String I/O
File I/O
5
goto
• goto allows you to jump unconditionally to arbitrary part of
your code (within the same function).
• the location is identified using a label.
• a label is a named location in the code. It has the same
form as a variable followed by a ’:’
s t a r t :
{
i f ( cond )
goto outside ;
/ ∗ some code ∗ /
goto s t a r t ;
}
outside :
/ ∗ outside block ∗ /
5
Spaghetti code
Dijkstra. Go To Statement Considered Harmful.
Communications of the ACM 11(3),1968
• Excess use of goto creates sphagetti code.
• Using goto makes code harder to read and debug.
• Any code that uses goto can be written without using one.
6
error handling
Language like C++ and Java provide exception mechanism to
recover from errors. In C, goto provides a convenient way to exit
from nested blocks.
cont _flag =1;
for ( . . )
for ( . . ) {
{ for ( i n i t ; c o n t _ f l a g ; i t e r )
for ( . . ) {
{ i f ( error_cond )
i f ( error_cond ) {
goto e r r o r ; c o n t _ f l a g =0;
/ ∗ skips 2 blocks ∗ / break ;
} }
} / ∗ i n n er loop ∗ /
e r r o r : }
i f ( ! c o n t _ f l a g ) break ;
/ ∗ outer loop ∗ /
}
7
6.087 Lecture 4 – January 14, 2010
Review
Control flow
I/O
Standard I/O
String I/O
File I/O
8
Preliminaries
• Input and output facilities are provided by the standard
library <stdio.h> and not by the language itself.
• A text stream consists of a series of lines ending with ’n’.
The standard library takes care of conversion from
’rn’−’n’
• A binary stream consists of a series of raw bytes.
• The streams provided by standard library are buffered.
8
Standard input and output
int putchar(int)
• putchar(c) puts the character c on the standard output.
• it returns the character printed or EOF on error.
int getchar()
• returns the next character from standard input.
• it returns EOF on error.
9
Standard input and output
What does the following code do?
int main ( )
{
char c ;
while ( ( c=getchar ( ) ) ! = EOF)
{
i f ( c>=’A’ && c<=’Z’ )
c=c−’A’+’a’ ;
putchar ( c ) ;
}
return 0;
}
To use a file instead of standard input, use ’<’ operator (*nix).
• Normal invocation: ./a.out
• Input redirection: a.out < file.txt. Treats file.txt as source of
standard input.This is an OS feature, not a language
feature.
10
Standard output:formatted
int printf (char format[],arg1,arg2 ,...)
• printf() can be used for formatted output.
• It takes in a variable number of arguments.
• It returns the number of characters printed.
• The format can contain literal strings as well as format
specifiers (starts with %).
Examples:
p r i n t f ( "hello worldn" ) ;
p r i n t f ( "%dn" ,10); / ∗ format : %d ( intege r ) , argument :10 ∗ /
p r i n t f ( "Prices:%d and %dn" ,10 ,20);
11
printf format specification
The format specification has the following components
%[flags][width ][. precision ][ length]<type>
type:
type meaning example
d,i integer printf ("%d",10); /∗prints 10∗/
x,X integer (hex) printf ("%x",10); /∗print 0xa∗/
u unsigned integer printf ("%u",10); /∗prints 10∗/
c character printf ("%c",’A’); /∗prints A∗/
s string printf ("%s","hello"); /∗prints hello∗/
f float printf ("%f",2.3); /∗ prints 2.3∗/
d double printf ("%d",2.3); /∗ prints 2.3∗/
e,E float(exp) 1e3,1.2E3,1E−3
% literal % printf ("%d %%",10); /∗prints 10%∗/
12
printf format specification (cont.)
%[flags][width ][. precision ][ modifier]<type>
width:
format output
printf ("%d",10) "10"
printf ("%4d",10) bb10 (b:space)
printf ("%s","hello") hello
printf ("%7s","hello") bbhello
13
printf format specification (cont.)
%[flags][width ][. precision ][ modifier]<type>
flag:
format output
printf ("%d,%+d,%+d",10,−10) 10,+10,-10
printf ("%04d",10) 0010
printf ("%7s","hello") bbhello
printf ("%-7s","hello") hellobb
14
printf format specification (cont.)
%[flags][width ][. precision ][ modifier]<type>
precision:
format output
printf ("%.2f,%.0f,1.141,1.141) 1.14,1
printf ("%.2e,%.0e,1.141,100.00) 1.14e+00,1e+02
printf ("%.4s","hello") hell
printf ("%.1s","hello") h
15
printf format specification (cont.)
%[flags][width ][. precision ][ modifier]<type>
modifier:
modifier meaning
h interpreted as short. Use with i,d,o,u,x
l interpreted as long. Use with i,d,o,u,x
L interpreted as double. Use with e,f,g
16
Digression: character arrays
Since we will be reading and writing strings, here is a brief
digression
• strings are represented as an array of characters
• C does not restrict the length of the string. The end of the
string is specified using 0.
For instance, "hello" is represented using the array
{’h’,’e’,’l’,’l’,’0’}.
Declaration examples:
• char str []="hello"; /∗compiler takes care of size∗/
• char str[10]="hello"; /∗make sure the array is large enough∗/
• char str []={ ’h’,’e’,’l’,’l’,0};
Note: use " if you want the string to contain ".
17
Digression: character arrays
Comparing strings: the header file <string.h> provides the
function int strcmp(char s[],char t []) that compares two strings in
dictionary order (lower case letters come after capital case).
• the function returns a value <0 if s comes before t
• the function return a value 0 if s is the same as t
• the function return a value >0 if s comes after t
• strcmp is case sensitive
Examples
• strcmp("A","a") /∗<0∗/
• strcmp("IRONMAN","BATMAN") /∗>0∗/
• strcmp("aA","aA") /∗==0∗/
• strcmp("aA","a") /∗>0∗/
18
Formatted input
int scanf(char∗ format ,...) is the input analog of printf.
• scanf reads characters from standard input, interpreting
them according to format specification
• Similar to printf , scanf also takes variable number of
arguments.
• The format specification is the same as that for printf
• When multiple items are to be read, each item is assumed
to be separated by white space.
• It returns the number of items read or EOF.
• Important: scanf ignores white spaces.
• Important: Arguments have to be address of variables
(pointers).
19
Formatted input
int scanf(char∗ format ,...) is the input analog of printf.
Examples:
printf ("%d",x) scanf("%d",&x)
printf ("%10d",x) scanf("%d",&x)
printf ("%f",f) scanf("%f",&f)
printf ("%s",str) scanf("%s",str) /∗note no & required∗/
printf ("%s",str) scanf("%20s",str) /∗note no & required∗/
printf ("%s %s",fname,lname) scanf("%20s %20s",fname,lname)
20
String input/output
Instead of writing to the standard output, the formatted data can
be written to or read from character arrays.
int sprintf (char string [], char format[],arg1,arg2)
• The format specification is the same as printf.
• The output is written to string (does not check size).
• Returns the number of character written or negative value
on error.
int sscanf(char str [], char format[],arg1,arg2)
• The format specification is the same as scanf;
• The input is read from str variable.
• Returns the number of items read or negative value on
error.
21
File I/O
So far, we have read from the standard input and written to the
standard output. C allows us to read data from text/binary files
using fopen().
FILE∗ fopen(char name[],char mode[])
• mode can be "r" (read only),"w" (write only),"a" (append)
among other options. "b" can be appended for binary files.
• fopen returns a pointer to the file stream if it exists or
NULL otherwise.
• We don’t need to know the details of the FILE data type.
• Important: The standard input and output are also FILE*
datatypes (stdin,stdout).
• Important: stderr corresponds to standard error
output(different from stdout).
22
File I/O(cont.)
int fclose(FILE∗ fp)
• closes the stream (releases OS resources).
• fclose() is automatically called on all open files when
program terminates.
23
File input
int getc(FILE∗ fp)
• reads a single character from the stream.
• returns the character read or EOF on error/end of file.
Note: getchar simply uses the standard input to read a
character. We can implement it as follows:
#define getchar() getc(stdin)
char[] fgets(char line [], int maxlen,FILE∗ fp)
• reads a single line (upto maxlen characters) from the input
stream (including linebreak).
• returns a pointer to the character array that stores the line
(read-only)
• return NULL if end of stream.
24
File output
int putc(int c,FILE∗ fp)
• writes a single character c to the output stream.
• returns the character written or EOF on error.
Note: putchar simply uses the standard output to write a
character. We can implement it as follows:
#define putchar(c) putc(c,stdout)
int fputs(char line [], FILE∗ fp)
• writes a single line to the output stream.
• returns zero on success, EOF otherwise.
int fscanf(FILE∗ fp,char format[],arg1,arg2)
• similar to scanf,sscanf
• reads items from input stream fp.
25
Command line input
• In addition to taking input from standard input and files, you
can also pass input while invoking the program.
• Command line parameters are very common in *nix
environment.
• So far, we have used int main() as to invoke the main
function. However, main function can take arguments that
are populated when the program is invoked.
26
Command line input (cont.)
int main(int argc,char∗ argv[])
• argc: count of arguments.
• argv[]: an array of pointers to each of the arguments
• note: the arguments include the name of the program as
well.
Examples:
• ./cat a.txt b.txt (argc=3,argv[0]="cat" argv[1]="a.txt"
argv[2]="b.txt"
• ./cat (argc=1,argv[0]="cat")
27
MIT OpenCourseWare
http://ocw.mit.edu
6.087 Practical Programming in C
January (IAP) 2010
For information about citing these materials or our Terms of Use,visit: http://ocw.mit.edu/terms.
Ad

More Related Content

Similar to Lecture 04 Programming C for Beginners 001 (20)

C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptx
vijayapraba1
 
CInputOutput.ppt
CInputOutput.pptCInputOutput.ppt
CInputOutput.ppt
mohammadsajidansari4
 
Cbasic
CbasicCbasic
Cbasic
Sapkal Knowledge Hub Late G. N.Sapkal College of Engg.
 
Cbasic
CbasicCbasic
Cbasic
Sapkal Knowledge Hub Late G. N.Sapkal College of Engg.
 
C tutorial
C tutorialC tutorial
C tutorial
Anuja Lad
 
C tutorial
C tutorialC tutorial
C tutorial
Khan Rahimeen
 
C tutorial
C tutorialC tutorial
C tutorial
tuncay123
 
basic C PROGRAMMING for first years .pptx
basic C  PROGRAMMING for first years  .pptxbasic C  PROGRAMMING for first years  .pptx
basic C PROGRAMMING for first years .pptx
divyasindhu040
 
C_Progragramming_language_Tutorial_ppt_f.pptx
C_Progragramming_language_Tutorial_ppt_f.pptxC_Progragramming_language_Tutorial_ppt_f.pptx
C_Progragramming_language_Tutorial_ppt_f.pptx
maaithilisaravanan
 
Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0x
ppd1961
 
2 data and c
2 data and c2 data and c
2 data and c
MomenMostafa
 
Introduction to Input/Output Functions in C
Introduction to Input/Output Functions in CIntroduction to Input/Output Functions in C
Introduction to Input/Output Functions in C
Thesis Scientist Private Limited
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
Ishin Vin
 
Error correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-cError correction-and-type-of-error-in-c
Error correction-and-type-of-error-in-c
Md Nazmul Hossain Mir
 
2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt
swateerawat06
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
Wei-Ning Huang
 
slides3_077.ppt
slides3_077.pptslides3_077.ppt
slides3_077.ppt
DEEPAK948083
 
Theory1&amp;2
Theory1&amp;2Theory1&amp;2
Theory1&amp;2
Dr.M.Karthika parthasarathy
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
Kamil Toman
 

More from MahmoudElsamanty (7)

Lecture 03 Programming C for Beginners 001
Lecture 03 Programming C for Beginners 001Lecture 03 Programming C for Beginners 001
Lecture 03 Programming C for Beginners 001
MahmoudElsamanty
 
Lecture 02 Programming C for Beginners 001
Lecture 02 Programming C for Beginners 001Lecture 02 Programming C for Beginners 001
Lecture 02 Programming C for Beginners 001
MahmoudElsamanty
 
Lecture 01 Programming C for Beginners 001
Lecture 01 Programming C for Beginners 001Lecture 01 Programming C for Beginners 001
Lecture 01 Programming C for Beginners 001
MahmoudElsamanty
 
lecture03_EmbeddedSoftware for Beginners
lecture03_EmbeddedSoftware for Beginnerslecture03_EmbeddedSoftware for Beginners
lecture03_EmbeddedSoftware for Beginners
MahmoudElsamanty
 
ECE-3567-Lecture-2-Spring-2025 for beginners
ECE-3567-Lecture-2-Spring-2025 for beginnersECE-3567-Lecture-2-Spring-2025 for beginners
ECE-3567-Lecture-2-Spring-2025 for beginners
MahmoudElsamanty
 
ECE-3567-Lecture-1-Spring-2025 for beginner
ECE-3567-Lecture-1-Spring-2025 for beginnerECE-3567-Lecture-1-Spring-2025 for beginner
ECE-3567-Lecture-1-Spring-2025 for beginner
MahmoudElsamanty
 
C Programming course for beginners and intermideate
C Programming course for beginners and intermideateC Programming course for beginners and intermideate
C Programming course for beginners and intermideate
MahmoudElsamanty
 
Lecture 03 Programming C for Beginners 001
Lecture 03 Programming C for Beginners 001Lecture 03 Programming C for Beginners 001
Lecture 03 Programming C for Beginners 001
MahmoudElsamanty
 
Lecture 02 Programming C for Beginners 001
Lecture 02 Programming C for Beginners 001Lecture 02 Programming C for Beginners 001
Lecture 02 Programming C for Beginners 001
MahmoudElsamanty
 
Lecture 01 Programming C for Beginners 001
Lecture 01 Programming C for Beginners 001Lecture 01 Programming C for Beginners 001
Lecture 01 Programming C for Beginners 001
MahmoudElsamanty
 
lecture03_EmbeddedSoftware for Beginners
lecture03_EmbeddedSoftware for Beginnerslecture03_EmbeddedSoftware for Beginners
lecture03_EmbeddedSoftware for Beginners
MahmoudElsamanty
 
ECE-3567-Lecture-2-Spring-2025 for beginners
ECE-3567-Lecture-2-Spring-2025 for beginnersECE-3567-Lecture-2-Spring-2025 for beginners
ECE-3567-Lecture-2-Spring-2025 for beginners
MahmoudElsamanty
 
ECE-3567-Lecture-1-Spring-2025 for beginner
ECE-3567-Lecture-1-Spring-2025 for beginnerECE-3567-Lecture-1-Spring-2025 for beginner
ECE-3567-Lecture-1-Spring-2025 for beginner
MahmoudElsamanty
 
C Programming course for beginners and intermideate
C Programming course for beginners and intermideateC Programming course for beginners and intermideate
C Programming course for beginners and intermideate
MahmoudElsamanty
 
Ad

Recently uploaded (20)

"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
How to use nRF24L01 module with Arduino
How to use nRF24L01 module with ArduinoHow to use nRF24L01 module with Arduino
How to use nRF24L01 module with Arduino
CircuitDigest
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
How to use nRF24L01 module with Arduino
How to use nRF24L01 module with ArduinoHow to use nRF24L01 module with Arduino
How to use nRF24L01 module with Arduino
CircuitDigest
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Ad

Lecture 04 Programming C for Beginners 001

  • 1. 6.087 Lecture 4 – January 14, 2010 Review Control flow I/O Standard I/O String I/O File I/O 1
  • 2. Blocks • Blocks combine multiple statements into a single unit. • Can be used when a single statement is expected. • Creates a local scope (variables declared inside are local to the block). • Blocks can be nested. { in t x =0; { int y=0; / ∗ both x and y v i s i b l e ∗ / } / ∗ only x v i s i b l e ∗ / } 1
  • 3. Conditional blocks if ... else..else if is used for conditional branching of execution i f ( cond ) { / ∗ code executed i f cond i s tru e ∗ / } else { / ∗ code executed i f cond i s fa l s e ∗ / } 2
  • 4. Conditional blocks switch..case is used to test multiple conditions (more efficient than if else ladders). switch ( opt ) { case ’A’ : / ∗ execute i f opt == ’A ’ ∗ / break ; case ’B’ : case ’C’ : / ∗ execute i f opt == ’B ’ | | opt == ’C ’ ∗ / default : } 3
  • 5. Iterative blocks • while loop tests condition before execution of the block. • do..while loop tests condition after execution of the block. • for loop provides initialization, testing and iteration together. 4
  • 6. 6.087 Lecture 4 – January 14, 2010 Review Control flow I/O Standard I/O String I/O File I/O 5
  • 7. goto • goto allows you to jump unconditionally to arbitrary part of your code (within the same function). • the location is identified using a label. • a label is a named location in the code. It has the same form as a variable followed by a ’:’ s t a r t : { i f ( cond ) goto outside ; / ∗ some code ∗ / goto s t a r t ; } outside : / ∗ outside block ∗ / 5
  • 8. Spaghetti code Dijkstra. Go To Statement Considered Harmful. Communications of the ACM 11(3),1968 • Excess use of goto creates sphagetti code. • Using goto makes code harder to read and debug. • Any code that uses goto can be written without using one. 6
  • 9. error handling Language like C++ and Java provide exception mechanism to recover from errors. In C, goto provides a convenient way to exit from nested blocks. cont _flag =1; for ( . . ) for ( . . ) { { for ( i n i t ; c o n t _ f l a g ; i t e r ) for ( . . ) { { i f ( error_cond ) i f ( error_cond ) { goto e r r o r ; c o n t _ f l a g =0; / ∗ skips 2 blocks ∗ / break ; } } } / ∗ i n n er loop ∗ / e r r o r : } i f ( ! c o n t _ f l a g ) break ; / ∗ outer loop ∗ / } 7
  • 10. 6.087 Lecture 4 – January 14, 2010 Review Control flow I/O Standard I/O String I/O File I/O 8
  • 11. Preliminaries • Input and output facilities are provided by the standard library <stdio.h> and not by the language itself. • A text stream consists of a series of lines ending with ’n’. The standard library takes care of conversion from ’rn’−’n’ • A binary stream consists of a series of raw bytes. • The streams provided by standard library are buffered. 8
  • 12. Standard input and output int putchar(int) • putchar(c) puts the character c on the standard output. • it returns the character printed or EOF on error. int getchar() • returns the next character from standard input. • it returns EOF on error. 9
  • 13. Standard input and output What does the following code do? int main ( ) { char c ; while ( ( c=getchar ( ) ) ! = EOF) { i f ( c>=’A’ && c<=’Z’ ) c=c−’A’+’a’ ; putchar ( c ) ; } return 0; } To use a file instead of standard input, use ’<’ operator (*nix). • Normal invocation: ./a.out • Input redirection: a.out < file.txt. Treats file.txt as source of standard input.This is an OS feature, not a language feature. 10
  • 14. Standard output:formatted int printf (char format[],arg1,arg2 ,...) • printf() can be used for formatted output. • It takes in a variable number of arguments. • It returns the number of characters printed. • The format can contain literal strings as well as format specifiers (starts with %). Examples: p r i n t f ( "hello worldn" ) ; p r i n t f ( "%dn" ,10); / ∗ format : %d ( intege r ) , argument :10 ∗ / p r i n t f ( "Prices:%d and %dn" ,10 ,20); 11
  • 15. printf format specification The format specification has the following components %[flags][width ][. precision ][ length]<type> type: type meaning example d,i integer printf ("%d",10); /∗prints 10∗/ x,X integer (hex) printf ("%x",10); /∗print 0xa∗/ u unsigned integer printf ("%u",10); /∗prints 10∗/ c character printf ("%c",’A’); /∗prints A∗/ s string printf ("%s","hello"); /∗prints hello∗/ f float printf ("%f",2.3); /∗ prints 2.3∗/ d double printf ("%d",2.3); /∗ prints 2.3∗/ e,E float(exp) 1e3,1.2E3,1E−3 % literal % printf ("%d %%",10); /∗prints 10%∗/ 12
  • 16. printf format specification (cont.) %[flags][width ][. precision ][ modifier]<type> width: format output printf ("%d",10) "10" printf ("%4d",10) bb10 (b:space) printf ("%s","hello") hello printf ("%7s","hello") bbhello 13
  • 17. printf format specification (cont.) %[flags][width ][. precision ][ modifier]<type> flag: format output printf ("%d,%+d,%+d",10,−10) 10,+10,-10 printf ("%04d",10) 0010 printf ("%7s","hello") bbhello printf ("%-7s","hello") hellobb 14
  • 18. printf format specification (cont.) %[flags][width ][. precision ][ modifier]<type> precision: format output printf ("%.2f,%.0f,1.141,1.141) 1.14,1 printf ("%.2e,%.0e,1.141,100.00) 1.14e+00,1e+02 printf ("%.4s","hello") hell printf ("%.1s","hello") h 15
  • 19. printf format specification (cont.) %[flags][width ][. precision ][ modifier]<type> modifier: modifier meaning h interpreted as short. Use with i,d,o,u,x l interpreted as long. Use with i,d,o,u,x L interpreted as double. Use with e,f,g 16
  • 20. Digression: character arrays Since we will be reading and writing strings, here is a brief digression • strings are represented as an array of characters • C does not restrict the length of the string. The end of the string is specified using 0. For instance, "hello" is represented using the array {’h’,’e’,’l’,’l’,’0’}. Declaration examples: • char str []="hello"; /∗compiler takes care of size∗/ • char str[10]="hello"; /∗make sure the array is large enough∗/ • char str []={ ’h’,’e’,’l’,’l’,0}; Note: use " if you want the string to contain ". 17
  • 21. Digression: character arrays Comparing strings: the header file <string.h> provides the function int strcmp(char s[],char t []) that compares two strings in dictionary order (lower case letters come after capital case). • the function returns a value <0 if s comes before t • the function return a value 0 if s is the same as t • the function return a value >0 if s comes after t • strcmp is case sensitive Examples • strcmp("A","a") /∗<0∗/ • strcmp("IRONMAN","BATMAN") /∗>0∗/ • strcmp("aA","aA") /∗==0∗/ • strcmp("aA","a") /∗>0∗/ 18
  • 22. Formatted input int scanf(char∗ format ,...) is the input analog of printf. • scanf reads characters from standard input, interpreting them according to format specification • Similar to printf , scanf also takes variable number of arguments. • The format specification is the same as that for printf • When multiple items are to be read, each item is assumed to be separated by white space. • It returns the number of items read or EOF. • Important: scanf ignores white spaces. • Important: Arguments have to be address of variables (pointers). 19
  • 23. Formatted input int scanf(char∗ format ,...) is the input analog of printf. Examples: printf ("%d",x) scanf("%d",&x) printf ("%10d",x) scanf("%d",&x) printf ("%f",f) scanf("%f",&f) printf ("%s",str) scanf("%s",str) /∗note no & required∗/ printf ("%s",str) scanf("%20s",str) /∗note no & required∗/ printf ("%s %s",fname,lname) scanf("%20s %20s",fname,lname) 20
  • 24. String input/output Instead of writing to the standard output, the formatted data can be written to or read from character arrays. int sprintf (char string [], char format[],arg1,arg2) • The format specification is the same as printf. • The output is written to string (does not check size). • Returns the number of character written or negative value on error. int sscanf(char str [], char format[],arg1,arg2) • The format specification is the same as scanf; • The input is read from str variable. • Returns the number of items read or negative value on error. 21
  • 25. File I/O So far, we have read from the standard input and written to the standard output. C allows us to read data from text/binary files using fopen(). FILE∗ fopen(char name[],char mode[]) • mode can be "r" (read only),"w" (write only),"a" (append) among other options. "b" can be appended for binary files. • fopen returns a pointer to the file stream if it exists or NULL otherwise. • We don’t need to know the details of the FILE data type. • Important: The standard input and output are also FILE* datatypes (stdin,stdout). • Important: stderr corresponds to standard error output(different from stdout). 22
  • 26. File I/O(cont.) int fclose(FILE∗ fp) • closes the stream (releases OS resources). • fclose() is automatically called on all open files when program terminates. 23
  • 27. File input int getc(FILE∗ fp) • reads a single character from the stream. • returns the character read or EOF on error/end of file. Note: getchar simply uses the standard input to read a character. We can implement it as follows: #define getchar() getc(stdin) char[] fgets(char line [], int maxlen,FILE∗ fp) • reads a single line (upto maxlen characters) from the input stream (including linebreak). • returns a pointer to the character array that stores the line (read-only) • return NULL if end of stream. 24
  • 28. File output int putc(int c,FILE∗ fp) • writes a single character c to the output stream. • returns the character written or EOF on error. Note: putchar simply uses the standard output to write a character. We can implement it as follows: #define putchar(c) putc(c,stdout) int fputs(char line [], FILE∗ fp) • writes a single line to the output stream. • returns zero on success, EOF otherwise. int fscanf(FILE∗ fp,char format[],arg1,arg2) • similar to scanf,sscanf • reads items from input stream fp. 25
  • 29. Command line input • In addition to taking input from standard input and files, you can also pass input while invoking the program. • Command line parameters are very common in *nix environment. • So far, we have used int main() as to invoke the main function. However, main function can take arguments that are populated when the program is invoked. 26
  • 30. Command line input (cont.) int main(int argc,char∗ argv[]) • argc: count of arguments. • argv[]: an array of pointers to each of the arguments • note: the arguments include the name of the program as well. Examples: • ./cat a.txt b.txt (argc=3,argv[0]="cat" argv[1]="a.txt" argv[2]="b.txt" • ./cat (argc=1,argv[0]="cat") 27
  • 31. MIT OpenCourseWare http://ocw.mit.edu 6.087 Practical Programming in C January (IAP) 2010 For information about citing these materials or our Terms of Use,visit: http://ocw.mit.edu/terms.