Chapter2 3
Chapter2 3
• 3.1. Declarations
• 3.2. Simple input and output functions in C
• 3.3. Other input and output functions
2
3.1. 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.)
3
Constant declarations
• Constants are used to store values that never change during the program
execution.
• Using constants makes programs more readable and maintainable.
Constants can be declared by const declaration.
They can appear inside functions or before the main function
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$
4
Constant declarations using preprocessor commands
5
Variable declarations
Examples:
int sum, avg;
int total = 3445, x = 1,
char answer = 'y';
double temperature = -3.14;
6
Variable declarations
7
Statements and Blocks
8
3.2.Simple input and output functions in C
9
Functions printf, scanf
10
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
11
How printf function works
12
The % Format Specifiers
13
The syntax of scanf() function
14
Actions
15
Example 1
16
program
1. #include<stdio.h>
2. #include<math.h>
3. main()
4. {
5. float xa,ya,xb,yb,d;
6. printf("\nInput co-ordinates of point A");
7. scanf("%f %f",&xa,&ya);
8. printf("\nInput co-ordinates of point B");
9. scanf("%f %f",&xb,&yb);
10. d= sqrt((xa-xb)*(xa-xb)+(ya-yb)*(ya-yb));
11. printf("\nDistance between A and B: %1.2f",d);
12. }
17
3.3. 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
18
Exercise
19
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. }
20