0% found this document useful (0 votes)
22 views28 pages

Lec 04

Uploaded by

anjandas0003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views28 pages

Lec 04

Uploaded by

anjandas0003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Taking Inputs (scanf)

ESC101: Fundamentals of Computing


Nisheeth
1
Announcements
 Graded labs starting today

 Prutor accounts: Hopefully everyone now has a working


Prutor account (accessible via your CC email id and CC
password)
 If not, please arrive at the lab early (by 1:45pm) and we
will create your account on the spot

2
Recap
Every C program’s entry point
(program’s execution starts Tells C compiler to include the standard
here) is the main function input/output library stdio.h (collection of
with return type integer functions such as printf, scanf, etc)

#include<stdio.h> main function


must open with
int main(){ left curly brace {
printf function prints a user
specified output
printf(“Welcome to ESC101”);
return 0;
main function
must close with } The main function must return
Every statement in a C program
must end with semi-colon ;
right curly brace } an integer (return 0 means successful
execution of program)

printf(“Welcome to ESC101”) and return 0 are ‘statements’ in the abo


code. Each C statement must end with a semi-colon ; 3
Recap
1 2
# include <stdio.h> a b
int main () { Each variable’s declaration creates a “box” big
enough to store it at a location in computer’s 3
int a = 1; main memory (RAM)
int b = 2;
c
Assigning a value to the variable
int c; writes that value in the box
= and + are “operators”
c = a + b;
printf(“Result is %d”, c); = is assignment operator

return 0; + is addition operator


} a+b is an “expression”

The program prints the message “Result is 4


What’s Wrong Here?

# include <stdio.h>
int main () {
int a = 1; Can’t assign a value to c
since it has not been
int b = 2; declared yet
c = a + b;
printf(“Result is %d”, c);
return 0;
} Will NOT Compile

5
What’s Wrong Here?
# include <stdio.h>
int main () {
int a; Can’t use variables a and b in this
int b; assignment operation since a and
b have not been assigned a value
int c; (initialized) in this program
c = a + b;
printf(“Result is %d”, c);
return 0;
} Will Compile but
will print garbage
6
What’s Wrong Here?

# include <stdio.h> Will print some garbage value


since c has not been assigned
int main () { a value (initialized) yet
int a = 1;
int b = 2;
int c;
printf(“Result is %d”, c);
return 0;
}
Will Compile but
will print garbage
7
What About This?
# include <stdio.h>
int main () { Can’t use variables a and b in this
int a; assignment operation since a and
b have not been assigned a value
int b; (initialized) in this program yet.
int c; Assigning a and b values later does
c = a + b; NOT solve this problem
a = 2;
b = 1;
printf(“Result is %d”, c); Will Compile but
return 0; will print garbage
} 8
Lesson Learned

Declare and initialize (or assign


values to) your variables
properly before their use

9
Recap: Alphabet and Keywords of C
 C programs can be written using the following
alphabet
A B .... Z Keywords in C
a b .... z
0 1 .... 9
Space . , : ; ‘ $ “
# % & ! _ { } [ ] ( ) |
+ - * / =

10
Naming Convention for Variables and
Functions
 We have seen variables and their usage in programs
 We have seen the main and printf function (and will see
various other standard functions and user-defined function
later)
 Need to follow some rules for naming of variables and
functions
 Names can only contain A-Z, a-z, 0-9, and underscore _
 Can’t begin a variable’s or function’s name with a number
 A_3, abcDS2, this_variable are some valid names
 321, 5_r, dfd@dhr, this variable, no-entry are some not
Contains special Contains hyphen
valid names symbol @
Start with number Contains space
character (“dash”) character -
11
Variables and Function Names: Some
Suggestions
 Should prefer short, meaningful names. Don’t use C
keywords.
 Multi-word name allows, e.g., firstNumber,
first_number
• Advice: Use capital letters for constants Yes,(e.g.,
but not advisable.
NUMBER_DAYS_JAN)
#include <stdio.h> May make mistakes,
confuse others
• intAdvice:
main(){ Use small letters for variables (e.g., radius,
So this program is fine?
intvolume)
temp, TEMP, Temp, TeMp;
For me, the names temp,
return 0;
Temp, TEMP, TeMp are all
} different variable names
12
Recap: printf and its use Note: In some cases,
there will be no such list.
Example: printf(“Hello”);

rintf(format string, list of things to print


printf(“Hello %d %d”,
a,b);
Printing some characters, such as “, new-line, %, \
equires special care (need to use escape sequences)

13
Reading Inputs: The scanf function
 Programs that don’t take inputs from user can be boring

 We saw programs to add two numbers but both had to be written into code

 Also called “hardcoding” the inputs

 A bit like a calculator which can only add 5 and 4

 To add 6 and 9, write a new calculator

 Can’t we ask Mr C to request us for the numbers when he is


executing our requests i.e. at runtime?

 YES, by taking input from the user using scanf function


Example: Adding Two User-provided Numbers

#include <stdio.h>
int main(){ 3 8
int a, b;
scanf(“%d”,
Thanks. Let me a
&a); b
get back to work
scanf(“%d”, &b);
11
printf(“%d”,
Please givea + b);
me input
return 0; 11
}
scanf: Some Words of Caution
In Prutor, input has to be specified before “Execute”
scanf: Some Words of Caution
In Prutor,
Yes, input
in printf they has tobutbe
are different Both work!
in specified before “Execute”
scanf, both look like whitespaces to me Experiment!
Please be very careful about this common mistake
Space, Tab, Newline are called whitespace
scanf(“%d”,a); scanf(“%d”,&a);
characters since they are invisible 

TAB SPAC NEWLI


Will explain what this & symbol means, in a few weeks
E NE

Why? Space is not


same as newline 

Huh! What is a
whitespace?
Taking Multiple Inputs using a Single scanf
#include <stdio.h>
int main(){ 3 8
int a, b; Help!!!
scanf(“%d%d”,
You
All entered
look the
a
&a, &b);
b
only
same oneto integer
me a + b);
printf(“%d”, 11
return 0;
11
}
Input please Thanks Okay okay
How does scanf work ?
HOW WE MUST SPEAK TO MR. HOW WE USUALLY SPEAK TO A
COMPILER HUMAN

scanf(“%d%d”, &a, &b); Please read one integer. Ignore all


whitespace
(spaces,tabs,newlines) after that
Format string tells till I write another integer. Read
Format string me how you will that second integer too.
write things, and Store value of the first integer in
then I am told a and value of second integer in
where to store b.
what I have read

Remember Mr. C likes to be told beforehand what all we


are going to ask him to do!
Scanf follows this exact same rule while telling Mr. C how to read
How does scanf work ?
Be a bit careful since Mr C is a bit careless in this
matter My advice to you is to
takeall
He treats input one at a time in characters the same when
whitespace Hmm … you are going
the beginning  Try out
integers acrobatics
are being input
in free time
to write the English
word Hello followed by
scanf will never
scanf(“Hello print anything
%d”,&a); space followed by an
integer. I will store the
value of that integer in a
Use printf to print and scanf to read
scanf(“%d
Try out what%d”,&a,&b);
happens withscanf(“%dHello%d”,&a,&b);
the following
scanf(“%d,%d”,&a,&b); scanf(“\“%d%d\“”,&a,&b);
scanf(“%d\n%d”,&a,&b); scanf(“%d\t%d”,&a,&b);
Commenting Your Code Okay. I will
add your two
Last week we learned about “indentation”
numbers
Let us learn about “comments” today
Absolutely essential in industry, even self projects
How we write commented What Mr C sees
code
int main(){ int main(){ Only humans int main(){

int a; int a; // My first int see comments int a;


int b; // The other int int b;
int b;
// Assign them values
a = 5, b = 4;
a = 5, b = 4; a = 5, b = 4;
int c = a + b; int c = a + b; int c = a + b;
printf(“c = %d”,c); printf(“c = %d”,c); printf(“c = %d”,c);
return 0; return 0; return 0;
21
} } }
Several Ways of Writing Comments
Since it is an art form, artists differ on what is more
pretty
int main(){ int main(){ int main(){
int a; // My first int int a; /* My first int */ int a; // My first int
int b; // The other int int b; /* The other int */ int b; // The other int
// Assign them values /* Assign them values */ /* Assign them values */
a = 5, b = 4; a = 5,Yes.
b = 4; In fact /* */ is used
a = 5, b = 4;
a + b; So I can mix a + b; to comment severala + b;
return 0; and match? returnlines 0; at once – shortcut! return 0;
} } }
Just be a bit careful.
Some compilers don’t
understand // comments 22
More on Comments
Use comments to describe why int main(){
you defined each variable and int a; // My first int
what each step of your code is
doing int b; // The other int
You will thank yourself for doing this when /* Assign them values
you are looking at your own code before the
endsem exams   so that I can add
Your team members in your them later on */
company/research group will also thank you
a = 5, b = 4;
Multiline comments very handy.
No need to write // on every line  a + b;
return 0;
}
23
A Useful Tip While Problem-Solving
Comments can be also used to identify where is error
Error! Okay! Okay!
Mr C will tell you (compile) where he thinks the error is
Commenting out lines can also help identify the error

int main(){ int main(){ int main(){


Aha! I forgot
int a, b; int a, b; int declare
to a, b, c; c
c = a + b; // c = a + b; c = a + b;
a = 5; a = 5; a = 5;
b = 4; b = 4; b = 4;
return 0; return 0; return 0;
} } } 24
Take Care with Formulae: Using Brackets Help
Bracket, Of, Division,
Operation C Code a b c Multiplication, Addition,
Addition c = a + b; 5 4 9 Subtraction
Subtraction c = a – b; 4 5 -1 Recall your BODMAS order
Multiplication c = a * b; -2 -4 8 rules from high school
Division c = a / b; 7 2 3 Mr. C follows similar rules –
Remainder c = a % b; 7 2 1 will see in detail soon
c = (a+b)/2; 5 1 3 Good practice to bracket
Bracketing your formulae
c = a + b/2; 5 1 5
Minimize confusion as well
as chances of error
Play with brackets in lab to
practice
25
A Useful Tip While Solving Problems
Print your solutions to
each one of these pieces
to see where going wrong

Try breaking up
I have no idea the problem into
what is going smaller pieces
wrong here!
26
A Useful Tip While Solving Problems

Equals 0
A Useful Tip While Solving Problems

Replace this part by


(2*x*x*x)/3

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy