Unit 2: 2000 Prentice Hall, Inc. All Rights Reserved
Unit 2: 2000 Prentice Hall, Inc. All Rights Reserved
Topics
Outline 1 Introduction to C 2 A Simple C Program: Printing a Line of Text 3 Constants and Variables 4 Rules for constants and variables 5 Expressions 6 Operators 7 Operator precedence 8 Program control structure
Decision Making: Decision control structures
2.1
Introduction
C programming language
1972 Dennis Ritchie C was designed for implementing system software it is also widely used for developing portable application software.
It is much easier to write software in high level languages than machine languages and assembly languages. C is a high-level programming language. Writing codes in high level languages is easier for human beings. It makes programming faster, easier to understand and maintain. In general it increases programmers productivity. C is a very powerful, general-purpose, machine-independent, portable and popular programming language.
It provides simple data types and mechanism for building complex data structures. It allows text substitutions and inclusions of other files and facilitates program modularization. It promotes code reuse (library functions).
Welcome to C!
Comments
Text surrounded by /* and */ is ignored by computer Used to describe program
#include <stdio.h>
Preprocessor directive
Tells computer to load contents of a certain file
Right brace }
Indicates end of main has been reached
Linker
When a function is called, linker locates it in the library Inserts it into object program If function name is misspelled, the linker will produce an error because it will not be able to find function in the library
2000 Prentice Hall, Inc. All rights reserved.
2. Secondary constants
1. Array, pointers, structure, union and enum
A variable is a name given to the location in memory where this constant is stored.
10
11
Rules for constructing real constant Must have at least one digit Must have a decimal point Either positive or negative No commas or blanks Rules for constructing character constants Single alphabet, a single digit or single special symbol enclosed within commas.
12
char long do
13
14
A visual representation
integer1 45
15
2.3
When executing the program the user responds to the scanf statement by typing in a number, then pressing the enter (return) key
1 2 3 4 5 6 7 8 9 10 11 12 13
16
Outline
1. Initialize variables
3. Print
printf( "Enter second integer\n" ); /* prompt */ scanf( "%d", &integer2 ); sum = integer1 + integer2; /* read an integer */ /* assignment of sum */
14 15
16 17 }
/* print sum */
return 0;
Program Output
17
Wrtie a C program which reads fahrenheit temperature value and then print the equilavent Centigrade temperature? c-=5/9 * (F-32) Write a C program which reads principal amount, rate, time and then calculate simple interest. SI= ptr/100 Write a C program which reads room length, breadth, height and then calculates the surface area and volume of the room?
2000 Prentice Hall, Inc. All rights reserved.
Outline
Expressions
Expressions are statements with the combination of operands and operators. Eg. A=B+C*D;
19
2.5
Arithmetic
Arithmetic calculations
Use * for multiplication and / for division
Operator precedence
Some arithmetic operators act before others (i.e., multiplication before addition)
Use parenthesis when needed
20
C exp ression f p b x r + * / % 7 c m y s
*, /, or % + or -
21
2.6
= not =
Relational Operators
x is equal to y x is not equal to y x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y
22
Logical operators ( !, &&, || ) The Operator ! is the operator to perform the Boolean operation NOT, it has only one operand, located at its right. For example: !(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true. !(6 <= 4) // evaluates to true because (6 <= 4) would be false. !true // evaluates to false !false // evaluates to true. The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds with Boolean logical operation AND. For example: ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ). ( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
23
Comma operator ( , ) The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered. For example, the following code: a = (b=3, b+2); Would first assign the value 3 to b, and then assign b+2 to variable a. Increase and decrease (++, --) B=3; A=++B; // A contains 4, B contains 4B=3; A=B++; // A contains 3, B contains 4
24
25
Integer Type : Integers are whole numbers with a machine dependent range of values. A good programming language as to support the programmer by giving a control on a range of numbers and storage space. C has 3 classes of integer storage namely short int, int and long int. All of these data types have signed and unsigned forms. A short int requires half the space than normal integer values. Unsigned numbers are always positive and consume all the bits for the magnitude of the number. The long and unsigned integers are used to declare a longer range of values. Floating Point Types : Floating point number represents a real number with 6 digits precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision. To extend the precision further we can use long double which consumes 80 bits of memory space. Void Type : Using void data type, we can specify the type of a function. It is a good practice to avoid functions that does not return any values to the calling function. Character Type : A single character can be defined as a defined as a character type of data. Characters are usually stored in 8 bits of internal storage. The qualifier signed or unsigned can be explicitly applied to char. While unsigned characters have values between 0 and 255, signed characters have values from 128 to 127.
27
2.6
Executable statements
Perform actions (calculations, input/output of data) Perform decisions
May want to print "pass" or "fail" given the value of a test grade
if control structure
Simple version in this section, more detail later If a condition is true, then the body of the if statement executed
0 is false, non-zero is true
28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* Fig. 2.13: fig02_13.c Using if statements, relational operators, and equality operators */ #include <stdio.h> int main() { int num1, num2; printf( "Enter two integers, and I will tell you\n" ); printf( "the relationships they satisfy: " ); scanf( "%d%d", &num1, &num2 if ( num1 == num2 ) printf( "%d is equal to %d\n", num1, num2 ); if ( num1 != num2 ) printf( "%d is not equal to %d\n", num1, num2 ); if ( num1 < num2 ) printf( "%d is less than %d\n", num1, num2 ); ); /* read two integers */
29
Outline
1. Declare variables 2. Input 2.1 if statements 3. Print
22 23 24
25 26 27 28 if ( num1 <= num2 ) printf( "%d is less than or equal to %d\n", num1, num2 );
if ( num1 > num2 ) printf( "%d is greater than %d\n", num1, num2 );
30
Outline
3.1 Exit main
31
32 33 34 35 }
return 0;
Enter two integers, and I will tell you the relationships they satisfy: 3 7 3 is not equal to 7 3 is less than 7 3 is less than or equal to 7
Program Output
Enter two integers, and I will tell you the relationships they satisfy: 22 12 22 is not equal to 12 22 is greater than 12 22 is greater than or equal to 12
31
32
Greatest of two numbers Greatest of three numbers If (a>b) && (a>c) A is greater Else if (b>c) B is greater Else c is greater Result of a student
34
For Loop
35
36
37
Prime number
38
#include<stdio.h> Armstrong Number #include<conio.h> main() { int number, sum = 0, temp, remainder; printf("Enter a number\n"); scanf("%d",&number); temp = number; while( temp != 0 ) { remainder = temp%10; sum = sum + remainder*remainder*remainder; temp = temp/10; } if ( number == sum ) printf("Entered number is an armstrong number."); else printf("Entered number is not an armstrong number."); getch(); return 0; } 2000 Prentice Hall, Inc. All rights reserved.
39
main() { Prime Number int i,j=2,ch=0; clrscr(); printf("\nENTER ANY NUMBER"); scanf("%d",&i); while(j<=i/2) { if(i%j==0) { printf("%d IS NOT PRIME",i); ch=1; break; } else { j++; } } if(ch==0) { printf("%d IS PRIME",i); } }
2000 Prentice Hall, Inc. All rights reserved.
Switch-Case Structures
The switch - case syntax is:
switch (integer expression test value) {
case case _1_fixed_value :
action(s) ;
case case_2_fixed_value :
action(s) ;
default :
action(s) ;
}
Switch-Case Structures
The switch is the "controlling expression"
Can only be used with constant integer expressions. Remember, a single character is a small positive integer. The expression appears in ( )
Goto statement
Goto g1; Exit() - function is a standard library function which terminates the execution of the program.
Prime number
For example, the variable i declared within the block of the following main function has block scope: int main() { int i; /* block scope */ . . . return 0; } Usually, a variable with block scope is called a local variable.
2000 Prentice Hall, Inc. All rights reserved.
Storage Classes in C
Storage class tells us
Where the variable is stored. What is the initial value of a variable What is the life of the variable What is the scope of the variable
main() { auto int i=1; { auto int i=2; { auto int i=3; Printf(%d,i) } Printf(%d,i) } Printf(%d,i) }
2000 Prentice Hall, Inc. All rights reserved.
1 2 3
C formatted Input/Output
Formatted function allow us to supply the input in a fixed format and the output is printed in the specified form. Formatted Input Scanf(format string, list of variables); Formatted output Printf(format string, list of variables); The format string can contain : - characters that are printed as they are
Conversion specifications that begin with a %sign Escape sequence that begin with a \sign
2000 Prentice Hall, Inc. All rights reserved.