100% found this document useful (1 vote)
33 views27 pages

E 102 F 23 Lecture 003 A

Uploaded by

ekim73
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
100% found this document useful (1 vote)
33 views27 pages

E 102 F 23 Lecture 003 A

Uploaded by

ekim73
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/ 27

ENGR 102 Introduction to

Electromechanical Systems
Engineering Programming in C
Lecture 03
Fall 2023

1
Basic I/O
There is no input or output defined in C itself
Character based (no format specifiers)
getchar() - input
putchar(c) - output
Formatted
scanf(stuff goes in here) - input *** white space is important!!!
printf(stuff goes in here) - output
Format Specifiers (% before specifier) – see next slide

#include <stdio.h> #include <stdio.h>


int main(void) { int main() { /* check1.c */
int i = 65; /* what if 258 instead of 65? */
int x;
char a;
printf("i=\n",i);
scanf(“%d\n”, &x);
printf("output with a putchar "); printf(“x=%d\n”, x); }
putchar(i); Q. Why are pointers given to scanf?
a = (char) i; A. Needs a pointer to the variable if
printf("a=\n",a); it is going to change the variable
getchar();
/* check.c */ itself i.e. assign a value to x.
return(0); }
C Language Conversion Characters
When programming in C, you use conversion characters — the percent sign and a
letter, for the most part — as placeholders for variables you want to display.
The following table shows the conversion characters and what they display:
Conversion Character Displays Argument (Variable’s Contents) As

%c Single character
%d Signed decimal integer (int)
%e Signed floating-point value in E notation
%f Signed floating-point value (float)
%g Signed value in %e or %f format, whichever is shorter
%i Signed decimal integer (int)
%o Unsigned octal (base8) integer (int)
%s String of text
%u Unsigned decimal integer (int)
%x Unsigned hexadecimal (base16) intege r(int)

%% (percentcharacter)
Inputs from the Keyboard
Inputs from the keyboard are read using the function scanf. The function
scanf requires a format string: that is, a format of the item (string) to be
read. A typical use of scanf for reading a string from a keyboard is:

scanf( “%d”, data);

where data is a variable.

The % sign is a format descriptor which determines the type of the next
input item and how to store that value.
Display to Monitor: printf

If we are to use a printf statement:

printf (“Time = %d hours\n”);

containing the special characters \ and %, the percent sign


denotes a format descriptor like in scanf and printf . Also
recall that \n denotes the start of a new line.
Answers: check.c and check1.c
#include <stdio.h> #include <stdio.h>
int main() { #define PI 3.14159265358979323846
int i = 65; int main() {
/* what if 258 instead of 65? */ int x;
char a; scanf("%d", &x); /* why need & ? */
printf("i=%d\n",i); printf("%d\n", x);
printf("output with a putchar ");
putchar(i); float var;
printf("\ni=%i",i); scanf("%f",&var);
a = (char) i; scanf("%d",&var);
printf("\na=%c\n",a); scanf("%lf", &var);
i=getchar(); int first, second;
printf("i=%c\n",i); scanf("enter value ", &var);
printf("i=0x%x\n",i); scanf("%d%d", &first, &second);
printf("i=%d\n",i); int i, j;
return (0); scanf(" %d %*d %*d%*d %d ", &i, &j)
} return 0; }
Printf formatted output conversions
Decimal & Floating point
Width of the whole number portion decimal
integer
%d Print as decimal integer
%6d Print as decimal integer, at least 6 characters wide
%f Print as floating point
%6f Print as floating point, at least 6 characters wide
%.2f Print as floating point,2 characters after decimal
point
%6.2f Print as floating point, at least 6 wide and 2 after
Decimal point
printfdemo.c
• It is possible to use more complicated conversion specifications to
fine-tune the appearance of the numbers displayed by printf.
There are a large number of options, but we will focus on
controlling the precision to which floating-point numbers are
displayed.
• You can ask for 3 digits of precision, for example, by using one of
%.3g, %.3f, or %.3e. Change each of the floating-point
conversion specifications in printfdemo.c so that it asks for 3
digits of precision, then compile and run the program.
• If you don't specify otherwise, the precision defaults to 6. When the
precision is p:
– the %g specification results in a p-digit mantissa
– the %f specification results in p digits after the decimal point
– the %e specification results in p digits after the decimal point.
printfdemo.c
• Try out the modified program with extremely
large (123456789e30), extremely small
(123456789e-30), and moderate
(123456.789).
• Try setting the precision to 30 and see what
happens. Even though doubles only have 15
digits of mantissa, C obligingly displays plenty
of garbage digits.
printfdemo.c
#include <stdio.h>

int main () {
/* We will use one floating-point and one integer variable. */
double x = .00000123456789;
int n = 12345;

/* Display plain text. */


printf("This is a test\n");
printf("This\tis\nanother\ttest\n\n");

/* Display an integer. */
printf("Here is n: %d\n\n", n);
/* Display a double three different ways. */
printf("Here is x: %g\n", x);
printf("Here is x: %f\n", x);
printf("Here is x: %e\n\n", x);

/* Display two numbers. */


printf("Here are n (%d) and x (%g)\n", n, x);
}
Scanf formatted input conversions
Consists of % at the beginning and a type indicator at the end
In between options:
* = used to suppress input
maximum field-width indicator
type indicator modifier
Scanf requires two inputs:
String argument
Set of additional arguments
Character InputData;Argumenttype
d Decimal integer
i integer; the integer may be in octal (leading 0) or hexadecimal (leading 0x or
0X).
o Octal integer (with or without leading zero)
u Unsigned decimal integer;
x Hexadecimal integer (with or without leading 0x or 0X)
e,f,g floating-point number; the input format for float’s is an optional sign, a string
of numbers possibly containing a decimal point, and an optional exponent
field containing an E or e followed by a possibly signed integer.
How scanf Consumes Input
• When scanf is called, it skips over all leading white space
(spaces, tabs, and newlines). Try recompiling and running
scanfdemo. Each time it prompts for a number, try entering
a bunch of newlines, spaces, and tabs before typing the
number. The extra white space will have no effect.
• After scanf has skipped over white space, it reads until it
finds something that doesn't belong in the type of number
than it is looking for and then quits. It leaves any remaining
input behind for the next call to scanf. Run scanfdemo,
and when it prompts for the first number enter
1.2 3.4
How scanf Consumes Input
• You will see than scanf reads the 1 as an integer, stopping when
it encounters the decimal point (which can't be part of an integer).
It later reads the .2 as a double, stopping when it encounters the
white space. Then it reads the 3 as an integer, and the .4 as a
double. Notice that if there is input left over from a previous call,
scanf will use it.
• Now run the program and enter
x
• None of the calls to scanf can get past the x, so the uninitialized
values of the variables are displayed
• Be careful when you supply input to your programs that you only
type in properly formatted numbers and white space. While it is
possible to write programs that are more robust in the face of bad
input, we will not be going into that topic
scanfdemo.c
• To read an int, supply scanf with a format string
containing the conversion specification %d, and include
an int variable preceded by an ampersand (&) as the
second parameter.
• To read a double, supply scanf with a format string
containing the conversion specification %lf (that's a
lower case L, not a one), and include a double variable
preceded by an ampersand as the second parameter.
• To read more than one number, include more than one
conversion specification and more than one extra
parameter.
Importance of Ampersand &
• It is important to put the ampersand in front of the variables
that appear as parameters to scanf, and it is easy to forget
to do this. Remove the ampersand and compile and run the
program. The program will crash before it runs to completion.
Put the ampersand back. If you see this behavior in the future,
check your scanf statements
• As with printf, it is important that the type of the variable
being read match up with the conversion specification. Try
changing the conversion specification in the first call to
scanf to %lf. After compiling and running the program,
change it back.
#include <stdio.h>
scanfdemo.c
int main () {
/* We will use a floating-point and an integer variable. */
double x;
int n;

/* Read in an integer. */
printf("Please enter an integer: ");
scanf("%d", &n);
printf("The integer was %d\n\n", n);

/* Read in a double. */
printf("Please enter a double: ");
scanf("%lf", &x);
printf("The double was %g\n\n", x);

/* Read in an integer and a double. */


printf("Please enter an integer and a floating-point number: ");
scanf("%d%lf", &n, &x);
printf("The numbers were %d %g\n", n, x);
}
getchar()
• Returns the next character from the standard input
(stdin)
• It is equivalent to calling getc with stdin as argument
• On success, the character read is returned (promoted
to an int value).
• The return type is int to accommodate for the special
value EOF, which indicates failure
getchar() Example
/* getchar example : typewriter */
#include <stdio.h>
int main ()
{ int c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do
{
c=getchar();
putchar(c);
} while (c != '.');
return 0;
}

A simple typewriter. Every sentence is echoed once ENTER has been


pressed until a dot (.) is included in the text.
See Also
getc Get character from stream (function )
putchar Write character to stdout (function )
scanf Read formatted data from stdin (function )
putchar()
• Writes a character to the standard output (stdout)
• It is equivalent to calling putc with stdout as
second argument
• Character
– The int promotion of the character to be written
– The value is internally converted to an unsigned char
when written
• On success, the character written is returned.
• If a writing error occurs, EOF is returned and the
error indicator (ferror) is set.
putchar() Example
/* putchar example: printing the alphabet */
#include <stdio.h>
int main ()
{
char c;
for (c = 'A' ; c <= 'Z' ; c++)
{
putchar(c);
}
return 0;
}
putchar() – See Also
putc Write character to stream (function )
fputc Write character to stream (function )
getchar Get character from stdin (function )
puts()
int puts ( const char * str );
• Write string to stdout
• Writes the C string pointed by str to the standard output (
stdout) and appends a newline character ('\n').
• The function begins copying from the address specified
(str) until it reaches the terminating null character ('\0').
This terminating null-character is not copied to the
stream.
• puts() not only differs from fputs() in that it uses stdout as
destination, but it also appends a newline character at
the end automatically (which fputs() does not).
puts()
str
C string to be printed.
puts() Example
/* puts example : hello world! */
#include <stdio.h>
int main ()
{
char string [] = "Hello world!";
puts(string);
}
gets()
char * gets ( char * str );
• Get string from stdin
• Don’t use this. It potentially does unwanted
things

You might also like