unit -1: introduction to ‘c’ language

25
Department of Technical Education E-Content 1 UNIT -1: Introduction to ‘C’ Language Brief history of C language C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on UNIX. It was applied to re-implementing the kernel of the UNIX operating system. During the 1980s, C gradually gained popularity. It has become one of the most widely used programming languages, C language is improved version of B language where B language is improved version BCPL (Basic Combined programming Language). The letter „C‟ is the second letter of BCPL. Hence C stands for “combined”, C is a high level language. C can be used for developing application programs and OS and also for processing scientific and engineering data. In 1983, the American National Standards Institute (ANSI) formed a committee to establish a Standard definition of C which became known as ANSI Standard C. Today C is in widespread use with a rich standard library of functions. Features of C language 1. C is general purpose high level programming language. 2. Programs Written in C are efficient and fast. 3. C has rich set of Operators, reserved words, built in functions and supports variety of data types. 4. C is highly portable this means that programs once written can be run on another machines with little or no modification. 5. C programs can be easily extended. 6. C is case sensitive. - Uppercase and lowercase letters are different in C. 7. Highly flexible in developing application programs and OS. 8. It supports pointers, which helps in dynamic memory management, and saves memory. 9. The syntax style of C programming is easy which can be used to design applications. 10. C is portable C programs are capable of being written on one platform and being run on another with or without any modification

Upload: others

Post on 18-Dec-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

Department of Technical Education E-Content

1

UNIT -1: Introduction to ‘C’ Language

Brief history of C language

C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities

running on UNIX. It was applied to re-implementing the kernel of the UNIX operating system. During the

1980s, C gradually gained popularity. It has become one of the most widely used programming languages,

C language is improved version of B language where B language is improved version BCPL (Basic

Combined programming Language). The letter „C‟ is the second letter of BCPL. Hence C stands for

“combined”, C is a high level language. C can be used for developing application programs and OS and also

for processing scientific and engineering data.

In 1983, the American National Standards Institute (ANSI) formed a committee to establish a

Standard definition of C which became known as ANSI Standard C. Today C is in widespread use with a

rich standard library of functions.

Features of C language

1. C is general purpose high level programming language.

2. Programs Written in C are efficient and fast.

3. C has rich set of Operators, reserved words, built in functions and supports variety of data types.

4. C is highly portable this means that programs once written can be run on another machines with little

or no modification.

5. C programs can be easily extended.

6. C is case sensitive. - Uppercase and lowercase letters are different in C.

7. Highly flexible in developing application programs and OS.

8. It supports pointers, which helps in dynamic memory management, and saves memory.

9. The syntax style of C programming is easy which can be used to design applications.

10. C is portable C programs are capable of being written on one platform and being run on another with

or without any modification

Department of Technical Education E-Content

2

1.1 C character set. Character set: The character set is the fundamental raw material of any language and

they are used to represent information. Like natural languages, computer language will also have well

defined character set, which is useful to build the programs.

Sample C program

A C program basically consists of the following parts −

Preprocessor Commands

Functions

Variables

Statements & Expressions

Comments

Let us look at a simple code that would print the words "Hello World" −

Live Demo

#include <stdio.h>

int main() {

/* my first program in C */

printf("Hello, World! \n");

return 0;

}

Let us take a look at the various parts of the above program −

The first line of the program #includes <stdio.h> is a preprocessor command, which tells a C

compiler to include stdio.h file before going to actual compilation.

Department of Technical Education E-Content

3

The next line int main () is the main function where the program execution begins.

The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments

in the program. So such lines are called comments in the program.

The next line printf (...) is another function available in C which causes the message "Hello, World!"

to be displayed on the screen.

The next lines return 0; terminates the main () function and returns the value 0.

Steps to execute simple C program

Download Turbo C and install. Download link: Download Turbo C++ for Windows

Step 1: Locate the TC.exe file and open it. You will find it at location C:\TC\BIN\.

Step 2: File > New (as shown in above picture) and then write your C program

#include<stdio.h>

int main()

{

printf("hello World!");

return 0;

}

Department of Technical Education E-Content

4

Step 3: Save the program using F2 (OR file > Save), remember the extension should be “.c”. In the below

screenshot.

Step 4: Compile the program using Alt + F9 OR Compile > Compile (as shown in the below screenshot).

Step 5: Press Ctrl + F9 to Run (or select Run > Run in menu bar ) the C program.

Department of Technical Education E-Content

5

Step 6: Alt+F5 to view the output of the program at the output screen.

Character Set of C Consists Of:

Types Character Set

Lowercase Letters a-z

Uppercase Letters A to Z

Digits 0-9

Special Characters @#$%^&*!

White Spaces Tab Or New line Or Space

Valid C Characters: Special Characters are listed below:

Symbol Meaning

~ Tilde

! Exclamation-mark

# Number-sign

$ Dollar-sign

% Percent-sign

^ Caret

Department of Technical Education E-Content

6

& Ampersand

* Asterisk

( Left-parenthesis

) Right-parenthesis

_ Underscore

+ Plus-sign

| Vertical bar

\ Backslash

` Apostrophe

– Minus sign

= Equal to sign

{ Left brace

} Right brace

[ Left bracket

] Right bracket

: Colon

” Quotation mark

; Semicolon

< Opening angle bracket

> Closing angle bracket

? Question mark

Department of Technical Education E-Content

7

, Comma

. Period

/ Slash

Variables in C

A variable used to store some form of data. Variables are simply names used to refer to some location in

memory – a location that holds a value with which we are working.

char - 1 byte

int – 2 byte

float -4 byte

double-8 bytes

Different types of variables require different amounts of memory, Any variable to be used in the program

must be declared using declaration statement.

General syntax: data_type variable_list;

Examples for variable declarations:

1. int m1, m2, sum;

2. float average;

Here int and float are data types; m1, m2, sum and average are variables.

Rules and guidelines for naming variables:

1) A variable name can contain digits, alphabets and underscores.

2) The first character must be an alphabet or underscore.

3) Maximum number of characters in variable name is 8.

4) Variable names are case sensitive.

5) Variable name must not contain any special character except underscore.

6) Variable name must not be a reserved word.

Department of Technical Education E-Content

8

Examples for valid variable names:

cse

_cse

_123cse

cse12

Examples for invalid variable names

12_cse: invalid because first letter cannot be a digit.

cse@gmail: invalid because it contains a special character @.

for invalid because for is a keyword.

computer science: invalid because it contains a special character( blank space).

Identifiers: Identifiers are the names of variables denoting values, labels, functions, arrays etc. Identifier

must be unique. They are created to give unique name to identify it during the execution of the program.

For example

int money;

double accountBalance;

Here, money and accountBalance are identifiers. Also remember, identifier names must be different from

keywords. You cannot use int as an identifier because int is a keyword.

Rules for writing an identifier:

1. A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.

2. The first letter of an identifier should be either a letter or an underscore. However, it is discouraged to

start an identifier name with an underscore.

3. There is no rule on length of an identifier. However, the first 31 characters of identifiers are discriminated

by the compiler.

Data Types in C

Data types in c refer to type of a variable determines how much space it occupies in storage

C data types can be divided into:

Department of Technical Education E-Content

9

1.Primitive /basic/fundamental/built in data types:

The four built in data types are: char ,int , float , double,The size of these data types is fixed, and predefined

to compiler.

Ex: char,int,float,double.

char

The variable of char data type holds a character constant.A character constant is a c character enclosed

within a pair of single quotes. Char data type reserves 1 byte of memory for the variable storage.

Example: char s1,s2;

Here s1 and s2 are variables of char data type.

A character denotes any alphabet, digit or special symbol used to represent information.

C language supports all the alphabets from the English language.

Lower and upper case letters together support 52 alphabets.(lower case letters - a to z,UPPER CASE

LETTERS - A to Z)

C language supports 10 digits which are used to construct numerical values in C language.

Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

C language supports a rich set of special symbols that include symbols to perform mathematical

operations, to check conditions, white spaces, backspaces, and other special symbols.

Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL bell

backspace verticaltab etc.,

int

Integers are whole numbers that can have both positive and negative values but no decimal values.

Ex: 0, -5, 10

A variable of int data type holds integer numbers; int data type reserves 2 bytes of memory for the variable

storage.

Department of Technical Education E-Content

10

Example: int n1, n2;

Here n1 and n2 are variables of int data type

float

Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0 etc.

A variable of float data type holds real (fractional) numbers; float data types reserves 4 bytes of memory for

the variable storage; Variable of float data type holds a number with six decimal digits of precision.

Ex: float length, height;

Here length and height are variables of float data type

Double

Double type variables can hold real numbers such as: 475.25, -78.85, 345.0 etc.

A variable of double data type holds real or fractional numbers with high precision than float data type ; In

double data type the fractional numbers are stored in exponent form; Variable of double data type holds a

number with ten decimal digits of precision; double data type reserves 8 bytes of memory for the variable

storage.

Ex: double voltage, percentage;

Here voltage and percentage are variables of double data type

Department of Technical Education E-Content

11

2. Derived type: A derived type is formed by using one or more basic types in combination. Using

derived types, an infinite variety of new types can be formed,

ex: arrays

structures

unions

enum

pointers.

3. Void type

void type means no value. This is usually used to specify the type of functions which returns nothing. We

will get acquainted to this data type as we start learning more advanced topics in C language, like functions,

pointers etc.

C Keywords or reserved words.

Keywords are those whose meaning is already defined in C compiler. Keywords are also called as reserved

words;

Keywords are written in lower case.

Keywords cannot be used as identifiers.

Compilers show error message when keywords are declared as variables/ constants.

They cannot store values

C has 32 keywords.

Ex : int, float, char ,if etc.

List of 32 keywords:

Department of Technical Education E-Content

12

C has many built-in operator types and they are classified as follows:

1. Arithmetic Operators: These are the operators used to perform arithmetic/mathematical operations on

operands. Examples: (+, -, *, /, %,++,–).

Arithmetic operator are of two types:

Unary Operators: Operators that operates or works with a single operand are unary operators.

For example: (++ , –)

Binary Operators: Operators that operates or works with two operands are binary operators. For

example: (+ , – , * , /)

2. Relational Operators: These are used for comparison of the values of two operands. For example,

checking if one operand is equal to the other operand or not, an operand is greater than the other

operand or not etc. Some of the relational operators are (==, >= , <= ).

Logical Operators: Logical Operators are used to combine two or more conditions/constraints or to

complement the evaluation of the original condition in consideration. The result of the operation of a logical

operator is a boolean value either true or false.

For example, the logical AND represented as ‘&&’ operator in C returns true when both the

conditions under consideration are satisfied. Otherwise it returns false. Therefore, a && b returns

true when both a and b are true (i.e. non-zero).

Department of Technical Education E-Content

13

3. Bitwise operators is used to perform bit-level operations on the operands. The operators are first

converted to bit-level and then the calculation is performed on the operands. The mathematical

operations such as addition, subtraction, multiplication etc. can be performed at bit-level for faster

processing. For example, the bitwise AND represented as & operator in C takes two numbers as

operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.

4. Assignment operators are used to assign value to a variable. The left side operand of the assignment

operator is a variable and right side operand of the assignment operator is a value. The value on the

right side must be of the same data-type of variable on the left side otherwise the compiler will raise

an error.

Ex:“=”: This is the simplest assignment operator. This operator is used to assign the value on the

right to the variable on the left.

For example:

a = 10;

b = 20;

ch = 'y';

Other Operators: Apart from the above operators there are some other operators available in C or C++ used

to perform some specific task. Some of them are discussed here:

sizeof operator: sizeof is a much used in the C programming language. It is a compile time unary

operator which can be used to compute the size of its operand, The result of sizeof is of unsigned

integral type which is usually denoted by size_t.

Comma Operator: The comma operator (represented by the token ,) is a binary operator that

evaluates its first operand and discards the result, it then evaluates the second operand and returns this

value (and type). Comma acts as both operator and separator.

Conditional Operator: Conditional operator is of the form Expression1 ? Expression2 : Expression3 .

Here, Expression1 is the condition to be evaluated. If the condition (Expression1) is True then we will

execute and return the result of Expression2 otherwise if the condition (Expression1) is false then we

will execute and return the result of Expression3. We may replace the use of if_else statements by

conditional operators.

Operator precedence chart

The below table describes the precedence order and associativity of operators in C / C++ . Precedence

of operator decreases from top to bottom.

Department of Technical Education E-Content

14

Operator

Description Associativity

() Parentheses (function call) left-to-right

[] Brackets (array subscript) left-to-right

. Member selection via object name left-to-right

-> Member selection via pointer left-to-right

++/– Postfix increment/decrement left-to-right

Operator Description Associativity

++/– Prefix increment/decrement right-to-left

+/- Unary plus/minus right-to-left

!~ Logical negation/bitwise complement right-to-left

(type) Cast (convert value to temporary value of

type) right-to-left

* Dereference right-to-left

& Address (of operand) right-to-left

sizeof Determine size in bytes on this

implementation

right-to-left

Operator Description Associativity

*,/,% Multiplication/division/modulus left-to-right

+/- Addition/subtraction left-to-right

<< , >> Bitwise shift left, Bitwise shift right left-to-right

< , <= Relational less than/less than or equal to left-to-right

Department of Technical Education E-Content

15

> , >= Relational greater than/greater than or equal to left-to-right

== , != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left

= Assignment right-to-left

, expression separator left-to-right

Operator precedence determines the grouping of terms in an expression and decides how an expression is

evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has

a higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than

+, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at

the bottom. Within an expression, higher precedence operators will be evaluated first.

If the expression contains the operators of same hierarchy, then the expression is evaluated as per

associativity; if the expression contains many parentheses, then contents of inner most parenthesis is

evaluated first, the next innermost as second step and so on.

Example:

- 4 % 3 * 1 + 16 / 2 % 5

- 4 % 3 * 1 + 16 / 2 % 5

- 1 *1 + 16 / 2 % 5

- 1 + 16 / 2 % 5

- 1 + 8 % 5

- 1 + 3

– 1 + 3

Constants and Literals.

Department of Technical Education E-Content

16

Constants refer to fixed values that the program may not alter during its execution. These fixed values

are also called literals. Constants can be of any of the basic data types like an integer constant, a

floating constant, a character constant, or a string literal.

Types of C Constants C constants can be divided into two major categories:

(a) Numeric Constants

(b) Character Constant

Basic input/output statement in C : C supports standard built-in functions to read the data from input

devices (like keyboard) and to display the data on output devices (like monitor).

These functions are classified as :

1. Formatted I/O functions scanf() and printf()

2. Unformatted I/O functions getch(), getche(),getchar(),gets(), putch(),putchar(),puts().

Format specifier/ Conversion specifiers: Format specifiers indicate the data type of the value to be read or

displayed when used in formatted I/O functions ( scanf() and printf() ).

Department of Technical Education E-Content

17

The list of format specifiers and associated data types are listed below.

Formatted I/O function These use format specifiers like (%d,%f,%c) to specify the data type of the

variable to be read or displayed.

scanf() and printf() are formatted I/O functions.

scanf() function:

It is an input function It is used to read the value from keyboard.

scanf stands for scan formatted or scan function.

The general form or general syntax of scanf(“control string”,arg1,arg2,arg3,……argn);

As shown above scanf() function contains two parts :control string and argument list

Control string: It contains format specifiers to indicate the data types of the values to be read. These format

specifiers are %d,%f,%c etc. Format specifiers are always included within double quotes.

Argument list This contains variables names into which the read values are stored. The data type of format

specifiers and variables must match.

Example: 1)scanf(“%d”, &num1);

Here one integer is read from keyboard and stored in the variable num1.

2) scanf(“%d%d”,&a,&b);

Here two integer values are read and stored in the variables a and b.

Department of Technical Education E-Content

18

printf() function:

It is an output function

It is used to display the values or text message on monitor.

printf stands for print formatted or print function.

The general form or general syntax of printff(“control string”,arg1,arg2,arg3,……argn);

As shown above printf() function contains two parts :control string and argument list Control string: It may

contain format specifiers or any text message or both. These format specifiers are %d,%f,%c etc

Format specifiers and text messages are always included within double quotes.

Argument list This contains variables names whose values are to be displayed. The data type of format

specifiers and variables must match.

Example: 1)printf(“Hardwork is the key to success”);

Output

Hardwork is the key to success

2) float a=56.565

Printf(“ The area of the circle is=%f”,a);

output The area of the circle is=56.565000

Unformatted I/O function

These do not use format specifiers .The default data type is char. These are used for reading or displaying the

value of character constant or string constant.

Examples: getch(), getche(), getchar()/fgetchar(), putch() and puts().

getch()

It is an unformatted input function.

It is used to read a character constant from keyboard.

It does not echo typed character on the screen. Ex: char p; p=getch();

getche()

It is an unformatted input function.

It is used to read a character constant from keyboard.

It echoes typed character on the screen. Ex: char p; p=getche();

Department of Technical Education E-Content

19

getchar/fgetchar()

It is an unformatted input function.

It is used to read a character constant from keyboard.

It echoes typed character on the screen. Ex: char p; p=getche();

gets()

It is an unformatted input function.

It is used to read a character string from keyboard.

End of the string is indicated by pressing ENTER key

putch()

It is an unformatted output function.

It is used to display a character constant on monitor.

Example: putch(„g‟); /* it will display g on the monitor*/

puts()

It is an unformatted output function

It is used to display a sequence of characters(string) on monitor.

Example: puts(“ Hi! Good morning”); It will display Hi! Good morning on the monitor

Simple 'C' programs.

1. /*Program to find sum of two variables*/

#include<stdio.h>

#include <conio.h>

void main()

{

int a,b,c; //declaration of variables

printf(“enter 1st integer value\n”);

scanf(“%d”,&a); printf(“enter 2nd integer value\n”);

scanf(“%d”,&b); c=a+b; printf(“sum of given values is %d\n” , c);

getch();

Department of Technical Education E-Content

20

}

Output: enter 1st integer value 10 enter 2nd integer value 20 sum of given values is 30

2. /*Program to swap the values of 2 variables without using third variable*/

#include<stdio.h>

#include <conio.h>

void main()

{

clrscr();

int A, B;

printf("Enter value of A and B \n");

scanf("%d%d", &A,&B);

printf(“Before swapping A=%d and B=%d \n”,A,B);

A=A+B; /*formula*/

B=A-B;

A=A-B;

printf("After swapping A=%d and B=%d \n", A, B);

getch();

}

Output

Enter value of A and B

-34 47

Before swapping

A=-34 and B=47

After swapping

A=47 and B=-34

Department of Technical Education E-Content

21

3.write a C program to read 3 integers and to print sum and average of three integer numbers.

#include<stdio.h>

#include <conio.h>

void main()

{

clrscr();

int a,b,c,sum;

float average;

printf("Enter any 3 integer numbers\n");

scanf("%d%d%d", &a,&b,&c);

sum=a+b+c; average=sum/3;

printf(“The sum of 3 numbers =%d”,sum);

printf(“The average of three numbers=%f”,average); getch();

}

Output

Enter any 3 integer numbers 5 20 12

The sum of 3 numbers =37

4.Write a C language to accept temperature in Fahrenheit and to convert it in to centigrade. Formula: C=(F-

32)/1.8

#include<stdio.h>

#include <conio.h>

void main()

{

clrscr();

float fah_temp,cent_temp;

printf("Enter the temperature value in Fahrenheit \n");

scanf("%f", &fah_temp);

Department of Technical Education E-Content

22

cent_temp=(fah_temp-32)/1.8;

printf(“Equivalent temperature value in centigrade =%f”,cent_temp);

getch();

}

Output

Enter the temperature value in Fahrenheit 68.0

Equivalent temperature value in centigrade =20.000000

Algorithm Definition:

Algorithm can be defined as collection of unambiguous(clear/not confusing) instructions occurring in

specific sequence, such an algorithm should produce output for given set of input in finite amount of time.

Notion of Algorithm

Characteristics of an Algorithm

An algorithm should have the following characteristics −

Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and their

inputs/outputs should be clear and must lead to only one meaning.

Input − An algorithm should have 0 or more well-defined inputs.

Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output.

Finiteness − Algorithms must terminate after a finite number of steps.

Feasibility − Should be feasible with the available resources.

Department of Technical Education E-Content

23

Independent − An algorithm should have step-by-step directions, which should be independent of any

programming code.

Design an algorithm to add two numbers and display the result

Step 1 − START

Step 2 − declare three integers a, b & c

Step 3 − define values of a & b

Step 4 − add values of a & b

Step 5 − store output of step 4 to c

Step 6 − print c

Step 7 – STOP

Alternatively, the algorithm can be written as

Step 1 − START ADD

Step 2 − get values of a & b

Step 3 − c ← a + b

Step 4 − display c

Step 5 – STOP

Flow chart

A flowchart can also be defined as a diagrammatic representation of an algorithm, a step-by-step approach to

solving a task.

A flowchart is a pictorial representation of an algorithm in which steps are drawn in the form of different

shapes of boxes and the logical flow is indicated by interconnecting arrows.

Department of Technical Education E-Content

24

Department of Technical Education E-Content

25