0% found this document useful (0 votes)
7 views33 pages

IT1016 Part2 Lesson3

Uploaded by

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

IT1016 Part2 Lesson3

Uploaded by

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

Unit 3 : Declarations,

Input and Output Functions


Declarations
• Constants and variables must be declared before they can be
used.
• A constant declaration specifies the type, the name and the
value of the constant.
• A variable declaration specifies the type, the name and
possibly the initial value of the variable.
• When you declare a constant or a variable, the compiler:
1. Reserves a memory location in which to store the value of
the constant or variable.
2. Associates the name of the constant or variable with the
memory location. (You will use this name for referring to
the constant or variable.)

2
Constant declarations
• Constants are used to store values that never change during the
program execution.
• Using constants makes programs more readable and maintainable.
Syntax:
const type identifier = expression;
Examples:
const double US2HK = 7.8;
//Exchange rate of US$ to HK$
const double HK2TW = 3.98;
//Exchange rate of HK$ to TW$
const double US2TW = US2HK * HK2TW;
//Exchange rate of US$ to TW$

3
Variable declarations
• Variables are used to store values that can be changed during
the program execution.
• A variable is best thought of as a container for a value.
3445 y -3.14
Syntax:
< type > < identifier >;
< type > < identifier > = < expression >;
Examples:
int sum;
int total = 3445;
char answer = 'y';
double temperature = -3.14;

4
Variable declarations
• A variable has a type and it can contain only values of that
type. For example, a variable of the type int can only hold
integer values.
• Variables are not automatically initialized. For example, after
declaration
int sum;
the value of the variable sum can be anything (garbage).
• Thus, it is good practice to initialize variables when they are
declared.
• Once a value has been placed in a variable it stays there until
the program deliberately alters it.

5
Constant declarations
A convenient way to associate constant values with
names is using the #define statement.
#define
Examples
#define TRUE 1
#define TABLESIZE 100
Constants can be declared by const declaration.
They appear inside functions.
const data_type const_name = value
const int a=2, b=5;

6
Statements and Blocks
• An expression such as x = 0 or i++ or printf(. . .)
becomes a statement when it is followed by a semicolon.
• Block group any number of data definitions, declarations,
and statements into one statement.
• compound statement group statements into one statement
• Use a blocks or compound statements wherever a single
statement is allowed.
• We use braces {} to build block or compound -
statements

7
Input and output in C
• C programming provides a set of built-in functions
to read the given input and feed it to the program as
per requirement.
• C also provides a set of built-in functions to output
the data on the computer screen as well as to save it
in text or binary files.
• Typical input output functions are
• In <stdio.h>
• The scanf() and printf() Functions
• The getchar() and putchar() Functions
• In <conio.h>
• The getch() and putch() Functions
• The gets() and puts() Functions

8
Functions printf, scanf
• Input by using the scanf() function

• Output by using the printf() function

• It is required to declare the header <stdio.h>

9
The syntax of printf() function
printf(“[string]”[,list of arguments]);
List of arguments : expressions, separated by
commas.
The string is usually called the control string or the
format string.
Action:
◦ Scan the string from left to right
◦ Prints on the screen any characters it encounters -
except when it reaches a % character

10
How printf function works

11
The % Format Specifiers

12
Printing with Field Widths and Precisions

• Precision
• Meaning varies depending on data type
• Integers (default 1) - minimum number of digits to
print
• If data too small, prefixed with zeros
• Floating point - number of digits to appear after
decimal (e and f)
• For g - maximum number of significant digits
• Strings - maximum number of characters to be
written from string
Printing with Field Widths and Precisions

• Format
• Precision: use a dot (.) then precision number
after %
%.3f
• Can be combined with field width
%5.3f
• Can use integer expressions to determine field
width and precision
• Use *
• Negative field width - left justified
• Positive field width - right justified
• Precision must be positive

printf( "%*.*f", 7, 2, 98.736 );


Example
Using precision for integers
0873
1 #include <stdio.h> 000000873
2 Using precision for floating-point numbers
3 int main() 123.945
4 { 1.239e+02
124
5 int i = 873;
6 double f = 123.94536; Using precision for strings
Happy Birth
7 char s[] = "Happy Birthday";
8
9 printf( "Using precision for integers\n" );
10 printf( "\t%.4d\n\t%.9d\n\n", i, i );
11 printf( "Using precision for floating-point numbers\n" );
12 printf( "\t%.3f\n\t%.3e\n\t%.3g\n\n", f, f, f );
13 printf( "Using precision for strings\n" );
14 printf( "\t%.11s\n", s );
15
16 return 0;
17 }
Printing with Field Widths and Precisions

• Field width
• Size of field in which data is printed
• If width larger than data, default right justified
• If field width too small, increases to fit data
• Minus sign uses one character position in field
• Integer width inserted between % and conversion
specifier
• %4d: field width of 4
Example

1 #include <stdio.h>
2
3 int main()
4 {
5 printf( "%10s%10d%10c%10f\n\n", "hello", 7, 'a', 1.23 );
6 printf( "%-10s%-10d%-10c%-10f\n", "hello", 7, 'a', 1.23 );
7 return 0;
8 }

hello 7 a 1.230000

hello 7 a 1.230000
Using Flags in the printf Format-Control String

• Flags
• Supplement formatting capabilities
• Place flag immediately to the right of percent sign
• Several flags may be combined
Fla g Desc rip tion

- (minus sign) Left-justify the output within the specified field.


+ (plus sign) Display a plus sign preceding positive values and a minus sign preceding
negative values.
space Print a space before a positive value not printed with the + flag.
# Prefix 0 to the output value when used with the octal conversion specifier o.
Prefix 0x or 0X to the output value when used with the hexadecimal conver-
sion specifiers x or X.
Force a decimal point for a floating-point number printed with e, E, f, g or G
that does not contain a fractional part. (Normally the decimal point is only
printed if a digit follows it.) For g and G specifiers, trailing zeros are not
eliminated.
0 (zero) Pad a field with leading zeros.
Example

1 #include <stdio.h>
2
3 int main()
4 {
5 int c = 1427;
6 double p = 1427.0;
7
8 printf( "%#o\n", c );
9 printf( "%#x\n", c );
10 printf( "%#X\n", c );
11 printf( "\n%g\n", p );
12 printf( "%#g\n", p );
13
14 return 0;
15 }
02623
0x593
0X593

1427
1427.00
Printing Literals and Escape Sequences

• Printing Literals
• Most characters can be printed
• Certain "problem" characters, such as the quotation
mark ” must be represented by escape sequences
• Represented by a backslash \ followed by an escape
character
Printing Literals and Escape Sequences

Esc a p e Desc rip tion


seq uenc e
\' Output the single quote (') character.
\" Output the double quote (") character.
\? Output the question mark (?) character.
\\ Output the backslash (\) character.
\a Cause an audible (bell) or visual alert.
\b Move the cursor back one position on the current line.
\f Move the cursor to the start of the next logical page.
\n Move the cursor to the beginning of the next line.
\r Move the cursor to the beginning of the current line.
\t Move the cursor to the next horizontal tab position.
\v Move the cursor to the next vertical tab position.
Reading Input with Scanf

• Role
• Reading input values
• Capabilities
• Input all types of data
• Input specific characters
• Skip specific characters
• Format
scanf(format-control-string, other-arguments);
• format-control-string: describes formats of inputs
• other-arguments: pointers to variables where input will
be stored
Formatting Input
Example

int d,m,y,x; Result


char ch1,ch2;
float f;
scanf(“%c%c”, &ch1,&ch2); Ab // ch1=‘A’, ch2=‘b’
scanf(“%d”, &x); 4 // x=4
scanf(“%2d%2d%4d”, &d,&m,&y); 22062007// d=22,m=6,y=2007

scanf(“%d/%d/%d”, &d,&m,&y); 22/06/2007


// d=22, m=6, y=2007

scanf(“%f”, &f); 2.3 // f=2.300000


Formatting Input

• Scan sets
• Set of characters enclosed in square brackets []
• Preceded by % sign
• Scans input stream, looking only for characters in
scan set
• Whenever a match occurs, stores character in specified
array
• Stops scanning once a mismatch is found
• Inverted scan sets
• Use a caret ^: [^aeiou]
• Characters not in the scan set to be stored
Formatting Input

• Skipping characters
• Include characters to skip in format control
• Use: *
• %*c: skip character from the input
Example

•Using an inverted scan set

2 #include <stdio.h>
3
4 int main()
5 {
6 char z[9] = {'\0'};
7
8 printf("Enter a string: ");
9 scanf("%[^aeiou]", z );
10 printf("The input was \"%s\"\n", z );
11
12 return 0;
13 }
Enter a string: String
The input was "Str"
Example

•Reading characters and strings

1 #include <stdio.h>
2
3 int main()
4 {
5 char x, y[ 9 ];
6
7 printf( "Enter a string: " );
8 scanf( "%c%s", &x, y );
9
10 printf( "The input was:\n" );
11 printf( "the character \"%c\" ", x );
12 printf( "and the string \"%s\"\n", y );
13
14 return 0;
15 }

Enter a string: Sunday


The input was:
the character "S" and the string "unday"
Example: discarding characters

1 #include <stdio.h>
2
3 int main()
4 {
5 int month1, day1, year1, month2, day2, year2;
6
7 printf( "Enter a date in the form mm-dd-yyyy: " );
8 scanf( "%d%*c%d%*c%d", &month1, &day1, &year1 );
9 printf( "month = %d day = %d year = %d\n\n",
10 month1, day1, year1 );
10 printf( "Enter a date in the form mm/dd/yyyy: " );
14 scanf( "%d%*c%d%*c%d", &month2, &day2, &year2 );
15 printf( "month = %d day = %d year = %d\n",
16 month2, day2, year2 );
17
18 return 0;
19 } Enter a date in the form mm-dd-yyyy: 11-18-2000
month = 11 day = 18 year = 2000

Enter a date in the form mm/dd/yyyy: 11/18/2000


month = 11 day = 18 year = 2000
Character and String Input

• Except scanf, you can call


• getchar() to get a character from input
char ch;
ch = getchar();
• gets to get a string including blank characters
char s[10];
gets(s);
Other Input and Output Functions
getch
Reads a single character from standard input.
It requires the user to press enter after entering
putch
writes a single character to standard output.
gets
reads a line of input into a character array.
gets(name_ of_ string)
puts
Writes a line of output to standard output.
puts(name of string)
Those functions defined in conio.h header file
35
Exercise
• Write a program to compute area of a triangle, given
its three sizes
• Heron's formula states that the area of
a triangle whose sides have lengths a, b, and c is
where s is the semi perimeter of the triangle; that is

36
Solution
1. #include <stdio.h>
2. #include<math.h>
3. main()
4. {
5. float a,b,c,s,A;
6. puts("Enter three sizes of the
7. triangle, a,b,c:");
8. scanf("%f %f %f", &a,&b,&c);
9. s=(a+b+c)/2;
10. A= sqrt(s*(s-a)*(s-b)*(s-c));
11. printf ("Area of the triangle: %1.2f",A);
12.}

37

You might also like