You are on page 1of 55

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

Loop control structures


Case control structures

9. C Formatted input output 10.Scope and storage classes


2000 Prentice Hall, Inc. All rights reserved.

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.

2000 Prentice Hall, Inc. All rights reserved.

Why should you learn C? (continues)

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.

C provides an easy to understand language syntax.


It has plenty of control operations for action selection (if, if else, switch), variety of looping (repetition) with exit conditions (for, while, break), statement blocking or grouping.

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).

2000 Prentice Hall, Inc. All rights reserved.

2.2 A Simple C Program: Printing a Line of Text


1 2 3 4 5 6 7 8 9 10 /* Fig. 2.1: fig02_01.c A first program in C */ #include <stdio.h> int main() { printf( "Welcome to C!\n" ); return 0; }

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

<stdio.h> allows standard input/output operations


2000 Prentice Hall, Inc. All rights reserved.

2.2 A Simple C Program: Printing a Line of Text int main()


C programs contain one or more functions, exactly one of which must be main Parenthesis used to indicate a function int means that main "returns" an integer value Braces ({ and }) indicate a block
The bodies of all functions must be contained in braces

2000 Prentice Hall, Inc. All rights reserved.

2.2 A Simple C Program: Printing a Line of Text printf( "Welcome to C!\n" );


Instructs computer to perform an action
Specifically, prints the string of characters within quotes ( )

Entire line called a statement


All statements must end with a semicolon (;)

Escape character (\)


Indicates that printf should do something out of the ordinary \n is the newline character

2000 Prentice Hall, Inc. All rights reserved.

2.2 A Simple C Program: Printing a Line of Text return 0;


A way to exit a function return 0, in this case, means that the program terminated normally

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.

Constants & variable


A quantity which does not change.
3X + Y = 20 3 and 20 are constants

Types of constants 1. Primary constants


1. Integer, real and character

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.

2000 Prentice Hall, Inc. All rights reserved.

10

Rules for integer constant


An integer constant must have at least one digit No decimal point Either positive or negative No commas or blanks Eg.
426 -800 Invalid 8,000

2000 Prentice Hall, Inc. All rights reserved.

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.

2000 Prentice Hall, Inc. All rights reserved.

12

Rules for variable names


Any combination of alphabet, digits or underscore. First character must be an alphabet No commas or blanks No special symbol other than an underscore. Eg. my_name Keywords Words whose meaning has already been fixed. Keywords cannot be used as variable names. Also called as Reserved words 32 keywords in C
Break If Else
2000 Prentice Hall, Inc. All rights reserved.

char long do

case scanf default

const printf while

13

Keyw o rd s auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

2000 Prentice Hall, Inc. All rights reserved.

14

2.4 Memory Concepts


Variables
Variable names correspond to locations in the computer's memory Every variable has a name, a type, a size and a value Whenever a new value is placed into a variable (through scanf, for example), it replaces (and destroys) the previous value Reading variables from memory does not change them

A visual representation
integer1 45

2000 Prentice Hall, Inc. All rights reserved.

15

Another Simple C Program: Adding Two Integers scanf( "%d", &integer1 );


Obtains a value from the user
scanf uses standard input (usually keyboard)

2.3

This scanf statement has two arguments


%d - indicates data should be a decimal integer &integer1 - location in memory to store variable & is confusing in beginning for now, just remember to include it with the variable name in scanf statements

When executing the program the user responds to the scanf statement by typing in a number, then pressing the enter (return) key

2000 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13

/* Fig. 2.5: fig02_05.c Addition program */ #include <stdio.h>

16

Outline
1. Initialize variables

int main() { int integer1, integer2, sum; /* declaration */

2. Input 2.1 Sum


printf( "Enter first integer\n" ); scanf( "%d", &integer1 ); /* prompt */ /* read an integer */

3. Print

printf( "Enter second integer\n" ); /* prompt */ scanf( "%d", &integer2 ); sum = integer1 + integer2; /* read an integer */ /* assignment of sum */

14 15
16 17 }

printf( "Sum is %d\n", sum );

/* print sum */

return 0;

/* indicate that program ended successfully */

Enter first integer 45 Enter second integer 72 Sum is 117

Program Output

2000 Prentice Hall, Inc. All rights reserved.

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;

2000 Prentice Hall, Inc. All rights reserved.

19

2.5

Arithmetic

Arithmetic calculations
Use * for multiplication and / for division

Integer division truncates remainder


7 / 5 evaluates to 1

Modulus operator(%) returns the remainder


7 % 5 evaluates to 2

Operator precedence
Some arithmetic operators act before others (i.e., multiplication before addition)
Use parenthesis when needed

Example: Find the average of three variables a, b and c


Do not use: a + b + c / 3 Use: (a + b + c ) / 3
2000 Prentice Hall, Inc. All rights reserved.

20

2.5 Arithmetic Arithmetic operators:


C op era tion Addition Subtraction Multiplication Division Modulus
Operator(s) () Operation(s) Parentheses

Arithm etic op era tor + * / %

Alg eb ra ic exp ression f+7 pc bm x/y r mod s

C exp ression f p b x r + * / % 7 c m y s

Rules of operator precedence:


Order of evaluation (precedence) Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right. Multiplication,Divi Evaluated second. If there are several, they are sion, Modulus evaluated left to right. Addition Evaluated last. If there are several, they are Subtraction evaluated left to right.

*, /, or % + or -

2000 Prentice Hall, Inc. All rights reserved.

21

2.6

Decision Making: Equality and Relational Operators


C equality or relational operator
== !=

Standard algebraic equality operator or relational operator


Equality Operators

Example of C Meaning of C condition condition

= not =
Relational Operators

x == y x != y x > y x < y x >= y x <= y

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

> < >= <=

> < >= <=

2000 Prentice Hall, Inc. All rights reserved.

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 ).

2000 Prentice Hall, Inc. All rights reserved.

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

2000 Prentice Hall, Inc. All rights reserved.

24

2000 Prentice Hall, Inc. All rights reserved.

25

2000 Prentice Hall, Inc. All rights reserved.

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.

2000 Prentice Hall, Inc. All rights reserved.

27

2.6

Decision control structures

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

Control always resumes after the if structure

2000 Prentice Hall, Inc. All rights reserved.

28

2000 Prentice Hall, Inc. All rights reserved.

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 );

2000 Prentice Hall, Inc. All rights reserved.

29 30 if ( num1 >= num2 )

30

Outline
3.1 Exit main

31
32 33 34 35 }

printf( "%d is greater than or equal to %d\n",


num1, num2 );

return 0;

/* indicate program ended successfully */

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

2000 Prentice Hall, Inc. All rights reserved.

31

If (expr) Statement Else if (expr) St Else St

2000 Prentice Hall, Inc. All rights reserved.

32

Area and perimeter of square and rectangle


Area = a * a Perimeter = 4a Area of rect = LB Perimeter = 2*(l+b)

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

2000 Prentice Hall, Inc. All rights reserved.

Loop control structures


Repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operations is done through a loop control structure
For statement While statement Do-while statement

2000 Prentice Hall, Inc. All rights reserved.

34

For Loop

2000 Prentice Hall, Inc. All rights reserved.

35

2000 Prentice Hall, Inc. All rights reserved.

36

2000 Prentice Hall, Inc. All rights reserved.

37

Even number upto a range Factorial Fibonacci series Armstrong number


A number is armstrong if the sum of cubes of individual digits of a number is equal to the number itself. For example 371 is an armstrong number as 33 + 73 + 13 = 371. Some other armstrong numbers are: 0, 1, 153, 370, 407.

Prime number

2000 Prentice Hall, Inc. All rights reserved.

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.

Case control structure


The control statement which allows us to make a decision from the number of choices Switch-case-default statement

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 :

Note use of colon!

action(s) ;
case case_2_fixed_value :

action(s) ;
default :

action(s) ;
}

2000 Prentice Hall, Inc. All rights reserved.

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 ( )

The case is a "label"


The label must be followed by a " : " Braces, { }, not required around statements

2000 Prentice Hall, Inc. All rights reserved.

Goto statement
Goto g1; Exit() - function is a standard library function which terminates the execution of the program.

2000 Prentice Hall, Inc. All rights reserved.

Prime number

2000 Prentice Hall, Inc. All rights reserved.

Scope and Storage Classes in C


Block Scope
In this section, a block refers to any sets of statements enclosed in braces ({ and }). A variable declared within a block has block scope. Thus, the variable is active and accessible from its declaration point to the end of the block. Sometimes, block scope is also called local scope.

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

Two kinds of locations where a value is kept


Memory CPU registers

There are four storage classes in C


Automatic storage class Register storage class Static storage class External storage class

2000 Prentice Hall, Inc. All rights reserved.

The auto Specifier


The auto specifier indicates that the memory location of a variable is temporary. In other words, a variable's reserved space in the memory can be erased or relocated when the variable is out of its scope. Only variables with block scope can be declared with the auto specifier. The auto keyword is rarely used, however, because the duration of a variable with block scope is temporary by default. main () { auto int i; Printf(%d,i); }
2000 Prentice Hall, Inc. All rights reserved.

main() { auto int i=1; { { { Printf(%d,i) } Printf(%d,i) } Printf(%d,i) } }


2000 Prentice Hall, Inc. All rights reserved.

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.

Register storage class


Storage = CPU register Default initial value Garbage value Scope local to the block in which the variable is defined. Life till the control remains within the block in which the variable is defined. A value stored in CPU register can always be accessed faster than the one which is stored in memory. If a variable is used in many places, better store it in register. Only 16 bit register, so float and double can not be used. main() { register int I; for (i=1;i<=10;i++) printf(%d,i); }

2000 Prentice Hall, Inc. All rights reserved.

Static storage class


The static Specifier The static specifier, on the other hand, can be applied to variables with either block scope or program scope. When a variable within a function is declared with the static specifier, the variable has a permanent duration. In other words, the memory storage allocated for the variable is not destroyed when the scope of the variable is exited, the value of the variable is maintained outside the scope, and if execution ever returns to the scope of the variable, the last value stored in the variable is still there. For instance, in the following code portion: int main() { int i; /* block scope and temporary duration */ static int j; /* block scope and permanent duration */ . . return 0; } the integer variable i has temporary duration by default. But the other integer variable, j, has permanent duration due to the storage class specifier static.
2000 Prentice Hall, Inc. All rights reserved.

increment() { auto int i=1; printf(%d,i) i=i+1; } Output 1 1 1


2000 Prentice Hall, Inc. All rights reserved.

increment() { static int i=1; printf(%d,i) i=i+1; }

1 2 3

External storage class


int i=4; main() { extern int x; i++; } External variable is declared outside the functions. Program scope

2000 Prentice Hall, Inc. All rights reserved.

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.

Unformatted input output


Input statement
getch() returns the character that is typed without echoing it on the screen. gets() receives a string from the keyboard Output statement Printf(Hello); Putc() Puts()

2000 Prentice Hall, Inc. All rights reserved.

You might also like