Transcript

Chapter 2Fundamentals of C language

ConstantsNumeric Constants

Integer ConstantsFloating Point

ConstantsCharacter ConstantsExpressionsArithmetic OperatorsAssignment OperatorsRelational OperatorsLogical OperatorsIncrement And Decrement

Operators

Input And Output StatementsFormat SpecifiersEscape SequencesTesting and Debugging

Syntax errorsLogical errors

VariablesInteger VariablesFloating Point

VariablesCharacter Constants

auto else long switchbreak enum register typedefcase extern return unionchar float short unsignedconst for signed voidcontinue goto sizeof volatiledefault if static whiledo int struct _Packeddouble  

Reserve Words/ KeywordsThe following names are reserved by the C language. Their meaning is already defined, and they cannot be re-defined to mean anything else.

LANGUAGE

Constants Numeric Constants

Integer ConstantsFloating Point

Constants Character Constants

Constants are quantities whose values do not change during program execution.They may be numeric or character.

Integer Constants are a string of digits that does not include commas, decimal point etc. it can be positive, negative or unsigned. 654, -987, 0r +34 etc.Floating point constants are also real constants. They are used to represent values that are measured. For example 564.78 etc  5.6478 x 10 2

Character constants is one of the symbols in the C character set. For example +, ; , =, - , etc.

Variables: are symbolic name used to refer to a quantity. For example  A=L X W

A variable is just a named area of storage that can hold a single value (numeric or character). The C language demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it.

The Programming language C has two main variable types• Local Variables• Global Variables

Rules for constructing variable names

1) A Variable name consists of any combination of alphabets, digits and underscores. Some compiler allows variable names whole length could be up to 247 characters. Still it would be safer to stick to the rule of 31 characters. Please avoid creating long variable name as it adds to your typing effort.

2) The first character of the variable name must either be alphabet or underscore. It should not start with the digit.

3) No commas and blanks are allowed in the variable name.

4) No special symbols other than underscore are allowed in the variable name.

Fundamental data typesWhen programming, we store the variables in our computer's memory, but the computer has to know what kind of data we want to store in them, since it is not going to occupy the same amount of memory to store a simple number than to store a single letter or a large number, and they are not going to be interpreted the same way. The memory in our computers is organized in bytes.

Declaring a variable tells the computer its name and its type.

Declaration of a variable is preceded by its type qualifier for example int, float, char, long, double etc.

int a; float c; char lb; etc. %d %f %c

Name Description Size Range

charCharacter or small integer.

1 byte signed:       -128 to 127unsigned:   0 to 255

short int(short)

Short Integer. 2 bytes signed:       -32768 to 32767

unsigned:   0 to 65535

int Integer. 4 bytes signed:     -2147483648 to 2147483647unsigned: 0 to 4294967295

long int (long)

Long integer. 4 bytes signed:     -2147483648 to 2147483647

unsigned: 0 to 4294967295

floatFloating point number.

4 bytes +/- 3.4e +/- 38 (~7 digits)

double 8 bytes +/- 1.7e +/- 308 (~15 digits)long double 8 bytes +/- 1.7e +/- 308 (~15 digits)

The following program demonstrates the use of integer variables.It calculates how many apples will be divided amongst children and how many will be left over.

# include <stdio.h>void main(void){

int apples=20;

int children=6;

int perchild, leftover;

perchild=apples/children;

leftover=apples % children;

printf(“\n each child gets %d apples”, perchild);printf(“\n we have %d apples left over”, leftover);

}

The following program demonstrates the use of floating point variables to calculate the area of a rectangle.

# include <stdio.h>void main(void){

float length, width, area;length=6.2;width=4.4;area=length*width;printf(“\n the area of rectangle is %6.2f”,area);

}

%6.2f  means there are 6 places maximum reserved for the 

variable are with two decimal places. ----.--

length

rectangle

width

area=length x width

INPUT AND OUTPUT STATEMENTSscanf( ) printf( )

Program that reads two numbers from keyboard and prints their sum on screen.

# include <stdio.h>void main(void){int num1,num2;printf(“\n enter the first number:”)scanf(“%d”, &num1);printf(“\n enter the second number:”)scanf(“%d”, &num2);printf(“\n\n the sum of two numbers is: %d”, num1+num2);}

enter the first number:  6

enter the second number:78

the sum of two numbers is: 84

A format specifier is used to control what format will be used by printf( ) to print out a particular variable.

Format specifier Characters matched

%c any single character

%d Signed decimal integer

%u Unsigned decimal integer

%o octal integer

%x hexa integer

%f floating point number

%s String, sequence of characters

%e Exponential notation

We can modify our last program with by using the input (scanf) statement.

# include <stdio.h>void main(void){

int apples, children, perchild, leftover;printf(“\n enter the no’ of apples:”)scanf(“%d”, &apples);printf(“\n enter the no’ of children:”)scanf(“%d”, &children);

perchild=apples/children;

leftover=apples % children;

printf(“\n each child gets %d apples”,

perchild);printf(“\n we have %d apples left over”, leftover);

}

Program: Write a program that prompts the user to enter weight in kilograms, converts it into pounds and prints result.

# include <stdio.h># include <conio.h>void main(void){

float kgs,lbs;clrscr( );printf(“\n please enter your weight in kilograms:”);scanf(“%f”, &kgs);lbs=kgs*2.2;printf(“%6.2f kilograms = %6.2f pounds”, kgs, lbs);getch( );

}

The following program uses the single character format specifier, %c, for printing characters.

# include <stdio.h>void main(void){char ch1, ch2;ch1=‘a’;ch2=‘b’;printf(\n” the sample characters are %c and %c”, ch1,ch2);}

Outputthe sample characters are a and b

Today, C is used for writing all kindsof application programs

If we want to print the above message, we can use the program.

#include <stdio.h>void main(void){

printf(“Today, C is used for writing all kinds”);printf(“of application programs”);

}Now the result will not be as desired it will be in single line asToday, C is used for writing all kinds of application programsIf we want to print result in two lines we will have to add an escape sequence \n.printf(“Today, C is used for writing all kinds\n”);printf(“of application programs”);Now the result will be as such,

Today, C is used for writing all kindsof application programs

The combination of \n is known as an escape sequence.The backslash \ indicates that a special effect is needed and the character following the backslash specifies what to do.The following are commonly used escape sequences.

\n To issue a new line\t To issue a tab character, tab over 8 characters\b To backspace\f To form feed\’ To print single quote\” To bring double quote\\ To print backslash

ExpressionsExpressions consist of constants and variables combined together with operators. Commonly used operators are:Arithmetic operators + - * /

%Assignment operator = Relational operator == != < >

<= >= Logical operators ! (not) && (and) (or)Increment and decrement operators ++

- -

Arithmetic operators + - * / %Precedence level is BEDMAS

An arithmetic expression is an expression that results in a numeric value. Parentheses may be used to control the order in which the operators are applied. If you don't use parentheses, operations with higher precedence are done first.Operator Description      A=10, B=20 Example

+ Adds two operands A + B will give 30- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200/ Divide numerator by denomenator B / A will give 2

% Modulus Operator and remainder of after an integer division

B % A will give 0

Assignment operator =

= Simple assignment operator, Assigns values from right side operands to left side operand

C = A + B will assign value of A + B into C

+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand

C += A is equivalent to C = C + A

-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

C - = A is equivalent to C = C - A

Operator

Relational Operators Description

Example

== Checks if the value of two operands is equal or not, if yes then condition becomes true.

(A == B) is not true.

!= Checks if the value of two is equal or not, if values are not equal then condition is true.

(A != B) is true.

> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

Logical operators ! (not) && (and) (or)

&& Called Logical AND operator. If both the operands are non zero then then condition becomes true.

(A && B) is true.

|| Called Logical OR Operator. If any of the two operands is non zero then then condition becomes true.

(A || B) is true.

! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is false.

Increment and decrement operators ++ - -

++ Increment operator, increases integer value by one

A++ will give 11

-- Decrement operator, decreases integer value by one

A-- will give 9

If A =10 then,

Testing and DebuggingDebugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program.

While writing c programs, errors also known as bugs in the world of programming may occur unwillingly which may prevent the program to compile and run correctly as per the expectation of the programmer.

Basically there are three types of errors in c programming:• Runtime Errors• Compile Errors or syntax errors• Logical Errors

C Runtime ErrorsC runtime errors are those errors that occur during the execution of a c program and generally occur due to some illegal operation performed in the program.Examples of some illegal operations that may produce runtime errors are:• Dividing a number by zero• Trying to open a file which is not created• Lack of free memory spaceIt should be noted that occurrence of these errors may stop program execution, thus to encounter this, a program should be written such that it is able to handle such unexpected errors and rather than terminating unexpectedly, it should be able to continue operating.

Compile Errors: Compile errors are those errors that occur at the time of compilation of the

program. C compile errors may be further classified as:When the rules of the c programming language are not followed, the compiler will show syntax errors.For example, consider the statement, int a,b:The above statement will produce syntax error as the statement is terminated with : rather than ;

Semantic errors are reported by the compiler when the statements written in the c program are not meaningful to the compiler. For example, consider the statement, b+c=a;In the above statement we are trying to assign value of a in the value obtained by summation of b and c which has no meaning in c. The correct statement will be a=b+c;

Logical ErrorsLogical errors are the errors in the output of the program. The presence of logical errors leads to undesired or incorrect output and are caused due to error in the logic applied in the program to produce the desired output.Also, logical errors could not be detected by the compiler, and thus, programmers has to check the entire coding of a c program line by line.

x, y, z are integer variables and c is a float variable.Also let x = 9, y = 11, z = 16.

Then c = x / 5 + y / 2 + z / 5

R1 R2 R3

R4

R5

R1

9/5=1

R2

11/2=5

R3

16/5=3

R4

1+5=6

R5

6+3=9

Example of Arithmetic Operators

int i=7, x=11 , y=13 ;float z, a , b ;a = x / 3 + y / 2.5 – z / 3 ;b = i / 2.5 + x / 4 + y / 1.2 ;

a=4, b=3M=a + ( c + b * ( c + a ) / c – b / a ) + a – b / 2

X=9, b=5, c=2Z=2x – 5bc x * x – 5 * b * c

Solve the following arithmetic

expressions

Solve the following expression

A=2, b=3, c=1, d=6, e=11, g=4, h=9

1+2a + 4(b + c) (5 – d - e) - 6 7 + h 3 f g

Chapter 2Fundamentals of C language

ConstantsNumeric Constants

Integer ConstantsFloating Point

ConstantsCharacter ConstantsExpressionsArithmetic OperatorsAssignment OperatorsRelational OperatorsLogical OperatorsIncrement And Decrement

Operators

Input And Output StatementsFormat SpecifiersEscape SequencesTesting and Debugging

Syntax errorsLogical errors

VariablesInteger VariablesFloating Point

VariablesCharacter Constants

Fill in the Blanks:1. Quantities whose values do not change during

the execution of the program are called _______.

Answer: 2. A ----------- is a memory location that is identified by a name to store an item of data of particular types.

Answer:3. ---------- should be matched to the type of variable you want to print or read.

Answer: 4. You can enter control characters in a C program by means of an ___________.

Answer:

Quantities whose values do not change during the execution of the program are called Constants.

Back

A Variable is a memory location that is identified by a name to store an item of data of particular types.

Back

Back

Format Specifier should be matched to the type of variable you want to print or read.

Back

You can enter control characters in a C program by means of an Escape sequence.


Recommended