Programming in c unit 1 by K K Bohra Lachoo College

21
Programming in C [BCA I Sem] UnitI (1) K K Bohra (LMSCT, 2014) BCA I Year Semester I PROGRAMMING IN C [BCA111] UNIT I Concept of Programming, Algorithm and Flow Chart, Data Types, Structure of C program , Constants and variables, Arithmetic Operators, Library Functions, Expression, Input / Output Statement, compound statements and blocks. ===================================================================== »» Concept of Programming Computer Program: It is sequence of instructions written to perform a specified task assigned to computer. Computer Programming: It is shorthand to programming / coding / program development it is the process of designing, writing, testing, debugging / trouble shooting and maintaining the source code of computer program. Programming Languages: It is an artificial language designed to express computations that can be performed by a machine, particular a computer. It is basically used to control the behavior of a machine. Programming languages have some form of written specification of their SYNTAX (form) and semantics (meaning). Some languages are defined by specification document. Generation of Programming Languages: 1. First GPL (Machine LL) 2. Second GPL (Assembly LL) -> Convertor(Assembler) -> Machine LL 3. Third GPL (HLL) -> Convertor(Compiler) -> Machine LL 4. Fourth GPL (Report Generation) 5. Fifth GPL (AI / Expert System) First GPL (Machine LL/ Low LL) It is machine understandable language. Entered through the front panel switches of computer

description

Notes of C language for BCA I Semester Students Unit I

Transcript of Programming in c unit 1 by K K Bohra Lachoo College

Page 1: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (1)

K K Bohra (LMSCT, 2014)

BCA I Year Semester I PROGRAMMING IN C

[BCA111]

UNIT I Concept of Programming, Algorithm and Flow Chart, Data Types, Structure of C program , Constants and variables, Arithmetic Operators, Library Functions, Expression, Input / Output Statement, compound statements and blocks. =====================================================================

»» Concept of Programming Computer Program: It is sequence of instructions written to perform a specified task assigned to computer. Computer Programming: It is shorthand to programming / coding / program development it is the process of designing, writing, testing, debugging / trouble shooting and maintaining the source code of computer program. Programming Languages: It is an artificial language designed to express computations that can be performed by a machine, particular a computer. It is basically used to control the behavior of a machine. Programming languages have some form of written specification of their SYNTAX (form) and semantics (meaning). Some languages are defined by specification document. Generation of Programming Languages:

1. First GPL (Machine LL) 2. Second GPL (Assembly LL) -> Convertor(Assembler) -> Machine LL 3. Third GPL (HLL) -> Convertor(Compiler) -> Machine LL 4. Fourth GPL (Report Generation) 5. Fifth GPL (AI / Expert System)

First GPL (Machine LL/ Low LL)

• It is machine understandable language. • Entered through the front panel switches of computer

Page 2: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (2)

K K Bohra (LMSCT, 2014)

Advantages: Can run very fast and efficiently. Directly executed to computer.

Disadvantages: Difficult to learn. Debugging is difficult. Problem in editing. Portability significantly reduced

Second GPL (Assembly LL/ Middle LL)

• Code can be read and written by programmer easily. • Conversation needed from assembly to machine with the help of software

(assembler) • Language is specific to particular processor family.

Third GPL (High LL) • Refinement of 2 GL. • Structured programming • More logical and user(programmer) friendly • Conversation needed from high LL to machine LL with the help of software

(compiler)

The evolution of programming

Basic Programming Concept

Solving a problem using computer program is multistep process. This process consists of 4 major elements/ stages.

1. Definition of problem 2. Generation of Algorithm 3. Program Development Process 4. Debugging

Page 3: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (3)

K K Bohra (LMSCT, 2014)

Definition of problem

It is also known as analysis of problem. If these steps go well than the remaining stages will be simplified or the all stages will be in serious zone.

»» Algorithm and Flow Chart

It is map/ outline to problem solution i.e. order in which the program will executed). To make a computer do anything, you have to write a computer program. To write a computer program, you have to tell the computer, step by step, exactly what you want it to do. The computer then "executes" the program, following each step mechanically, to accomplish the end goal.

When you are telling the computer what to do, you also get to choose how it's going to do it. That's where computer algorithms come in. The algorithm is the basic technique used to get the job done.

Algorithm is a set of steps for solving a particular problem, having set of standards that must be unambiguous and have a clear stopping point. Algorithms can be expressed in any language, from natural languages.

Algorithm of: Addition of two numbers. Description: ... Step 1: Start/Begin Step 2: WRITE “Enter First Number:”. Step 3: READ num1. Step 4: WRITE “Enter Second Number:”. Step 5: READ num2. Step 4: sum←num1+num2. Step 5: WRITE “Sum of both the numbers is “,sum Step 6: Stop/End OR Step 1: Start Step 2: Declare variables a,b and c. Step 3: Read variables a,b and c. Step 4: If a>b If a>c Display a is the largest number. Else Display c is the largest number. Else If b>c Display b is the largest number. Else Display c is the greatest number. Step 5: Stop

Page 4: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (4)

K K Bohra (LMSCT, 2014)

Flow Chart

Flowchart is a diagrammatic representation of an algorithm. Flow charts are very helpful in writing program and explaining program to others.

Flowcharts use special shapes to represent different types of actions or steps in a process. Lines and arrows show the sequence of the steps, and the relationships among them. These are known as flow chart symbols.

Page 5: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (5)

K K Bohra (LMSCT, 2014)

Program Development Process

It is normally called coding or programming.

Debugging

In computers, debugging is the process of locating and fixing or bypassing bugs (errors; syntax or semantic) in computer program code or the engineering of a hardware device. To debug a program or hardware device is to start with a problem, isolate the source of the problem, and then fix it.

Debugging tools (called debuggers) help identify coding errors at various development stages. Some programming language packages include a facility for checking the code for errors as it is being written.

Page 6: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (6)

K K Bohra (LMSCT, 2014)

»» Data Types Every programming language deals with some data. For example to print any message it requires charterer or string type of data. To solve any mathematic expression it requires integral as well as real number (floating type) of data. C has a concept of 'data types' which are used to define a variable before its use. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location. The value of a variable can be changed any time. A C programmer has to employ proper data type as per his requirements Types of Data Types

o Primary/Primitive/Fundamental Integral Type

• Character o Signed / Unsigned

• Integer o short int(S/U) / int(S/U) / long int(S/U)

Floating point • Float, double, long double

Void o Secondary/User defined/Derived

Array Structure Pointer Union Enumeration Typedef

Character (Integral Type) There are signed and unsigned chars, both occupying 8 bits or 1 byte each, but having different ranges. A signed char is same as our ordinary char and has a range from -128 to +127, whereas an unsigned char has a range from 0 to 255.

Note: There is not a Boolean data type.

Note: short and long comes under

extended data types

Page 7: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (7)

K K Bohra (LMSCT, 2014)

a) char/signed char [1 Byte; 8 bits] [%c] Range = -27 to 27

b) unsigned char [1 Byte; 8 bits] [%c]

-1 = -128 to 127

Range = 0 to 27 -1 = 0 to 255 Example

char a = 'a'; char b = 'A'; char c = 126; char d = a + 14; ASCII of a and number is added and stored in d char e = 300;

Integer Type Integer is whole numbers with a range of values supported by a particular machine. The size of an integer that can be stored depends on the computer. If we use a 16 bit word length, the size of an integer value is limited to the range -32768 to +32767(i.e. 215 to 215-1). A signed integer uses one bit for sign and 15 bits for the magnitude of the number. Similarly a 32 bit word length can store an integer ranging from -2.147,483,648 to 2,147,483,647.C has three classes of integer storage, namely short int, int and long int, in both signed and unsigned forms. Short int represents fairly small integer values and requires half the amount of regular int number uses. For 16 bit machine, the range of unsigned integer numbers will be from 0 to 65535. We declare long and unsigned integers to increase the range of values. Example

int age = 10;

Page 8: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (8)

K K Bohra (LMSCT, 2014)

Short int a) signed int [1 Byte; 8 bits] [%d]

We check 8th bit If 8th bit = 1 then (-) If 8th bit = 0 then (+)

Range = -27 to 27

b) unsigned int [1 Byte; 8 bits] [%u]

-1 = -128 to 127 Because we consider 0 is a positive number.

By default = +ve Range = 0 to 28-1 = 0 to 255

int a) int/signed int [2 Bytes; 16 bits] [%d]

We check 16th bit If 16th bit = 1 then (-) If 16th bit = 0 then (+)

Range = -215 to 215

b) unsigned int [2 Bytes; 16 bits] [%d]

-1 = -32768 to 32767 Because we consider 0 is a positive number.

By default = +ve Range = 0 to 216-1 = 0 to 65535 Long int

a) signed int [4 Bytes; 32 bits] [%ld] We check 32th bit If 32th bit = 1 then (-) If 32th bit = 0 then (+)

Range = -231 to 231

b) unsigned int [4 Bytes; 32 bits] [%lu]

-1 = -2,147,483,648 to 2,147,483,647 Because we consider 0 is a positive number.

By default = +ve Range = 0 to 232-1 = 0 to 4,294,967,295

Page 9: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (9)

K K Bohra (LMSCT, 2014)

Floating point type The float data type is used to store fractional numbers (real numbers) with 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 and takes double space (8 bytes) than float. To extend the precision further we can use long double which occupies 10 bytes of memory space. Floating point describes a method of representing an approximation of a real number in a way that can support a wide range of values. The numbers are, in general, represented approximately to a fixed number of significant digits (the mantissa) and scaled using an exponent.

float [4 Bytes; 32 bits] [%f]

Range = -223[M]:27[E] to +223[M]:27[E] Exponent(E) is stored in 2’s compliment form(+ve and –ve values both can be

stored without using sign bit). Because we consider 0 is a positive number.

Example 1.2345 = 12345 X10

- has no value

-4 Mantissa Exponent

double [8 Bytes; 64 bits] [%lf] / double precision number

Example double [10 Bytes; 80 bits] [%Lf] Example

void type

- represents ‘Nothing’ (kuch nahi hona) - usually used in functions (when there is no return value) - generic type (means it can represent any of other standard types)

Page 10: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (10)

K K Bohra (LMSCT, 2014)

»» C Tokens

In C programs, the smallest individual units are known as tokens.

»» Structure of C program

C Tokens

Keywords

float,main,

int,if,...

Identifiers

mian,per,

total,

Constants

Numeric

Integer

Real

Character

Single character

String

Back Slash \character constant

SpecialCharacter Operators

•This section consists of a set of comments lines giving the name of the program, the author and other details which the programmer would like to use later.

Documentation Section

•This section provides instruction to the complier to link functions from the system library.

Link Section

•This section defines all symbolic constants.

Definition Section

Declaration (For Global Variables) Section

•Declaration(Local Variables) Sub-Section•Executable Sub-Section

main() function Section

•Function1•Function2•...•Note: It contains all the user-defined functions that are called in the main function.

Sub Program Section

Page 11: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (11)

K K Bohra (LMSCT, 2014)

»» Executing C program

»» Keywords and Identifiers Every C word is classified as either a keyword or an identifier. All keywords have fixed meanings and these meaning can’t be changed. Keywords serve as basic building blocks for program statements. All keywords must be written in lowercase. ANSI C Keywords: Auto break double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto size of volatile do if static while

Page 12: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (12)

K K Bohra (LMSCT, 2014)

Identifier refers to the names of variables, functions and arrays. These are user-defined names and consist of a sequence of letters and digits, with a letter as a first character. Both uppercase and lowercase letters are permitted. The underscore character is also permitted. Rules for Identifier Rule 1: Name of identifier includes alphabets, digit and underscore.

Valid name: world, addition23, sum_of_number, … Invalid name: factorial#, avg value, display*number, …

Rule 2: First character of any identifier must be either alphabets or underscore.

Valid name: _calulate, _5,a_,… Invalid name: 5_, 10_function, 123,…

Rule 3: Name of identifier cannot be any keyword of c program.

Invalid name: interrupt, float, return, enum, ... Rule 4: Must not contain white space.

Invalid name

»» Constants and variables Types of Constant Numeric Integer Constant

: world population, addition of number, …

Real Constant/ Fractional/ Floating Point

Character Single Character Constant String Constant Backslash

A C constant is usually just the written version of a number. For example 1, 0, 5.73, 12.5e9. We can specify our constants in octal or hexadecimal, or force them to be treated as long integers.

Note: Programmer can choose the name of identifier whatever they want. However, if the programmer choose meaningful name for an identifier, it will be easy to understand and work on, particularly in case of large program.

Page 13: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (13)

K K Bohra (LMSCT, 2014)

• Octal constants are written with a leading zero - 015. • Hexadecimal constants are written with a leading 0x - 0x1ae. • Long constants are written with a trailing L - 890L.

Character constants are usually just the character enclosed in single quotes; 'a',

'b', 'c'. Some characters can't be represented in this way, so we use a 2 character sequence as follows.

'\n' newline '\t' tab '\\' backslash '\'' single quote '\0' null ( Used automatically to terminate character string )

In addition, a required bit pattern can be specified using its octal equivalent. '\044' produces bit pattern 00100100. Character constants are rarely used, since string constants are more convenient.

A string constant is surrounded by double quotes eg "Brian and Dennis". The string is actually stored as an array of characters. The null character '\0' is automatically placed at the end of such a string to act as a string terminator.

A character is a different type to a single character string. This is important poing

to note. Constants

ANSI C allows you to declare constants. When you declare a constant it is a bit

like a variable declaration except the value cannot be changed. The const keyword is to declare a constant, as shown below:

int const a = 1; const int a = 2;

You can declare the const before or after the type. Choose one and stick to it. It is usual to initialize a const with a value as it cannot get a value any other way.

Page 14: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (14)

K K Bohra (LMSCT, 2014)

Integer Constants:

An integer constant refers to a sequence of digits. These are of three types a. Decimal b. Octal c. Hexadecimal

Real Constants: These quantities are represented by numbers containing fractional parts like 17.548. Such numbers are called real constants.

Single Char Constants: These contains a single character enclosed within a pair of single quote marks. Example: ‘5’ ‘X’

String Constants: A string constant is a sequence of characters enclosed in double quotes. The characters may be letters, numbers, special characters and blank space. Examples: “Hello!” “1987” “WELL DONE”

Backslash Character Constants C supports some special backslash character constants that are used in output functions. For example, the symbol ‘\n’ stands for new line character. Although they contain two character but they represent a single character. Example

Constants Meaning ‘\b’ Backspace ‘\n’ New line ‘\r’ Carriage return ‘\’’ Single quote ‘\”’ Double quote ‘\?’ Question mark ‘\\’ Backslash

Page 15: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (15)

K K Bohra (LMSCT, 2014)

Variables As a programmer, you will frequently want your program to "remember" a value. For example, if your program requests a value from the user, or if it calculates a value, you will want to remember it somewhere so you can use it later. The way your program remembers things is by using variables. For example:

int b; //Declaration of variable named b. int cnt=1; //Initialization of cnt variable with value 1.

This line says, "I want to create a space called b that is able to hold one integer value." A variable has a name (in this case, b) and a type (in this case, int, an integer). You can store a value in b by saying something like:

b = 5; //Assigning value 5 to variable b. You can use the value in b by saying something like:

printf ("%d", b);

In C, there are several standard types for variables:

int - integer (whole number) values float - floating point values char - single character values (such as "m" or "Z")

»» Operators and Expression Arithmetic Operators

Operator Meaning + Addition or unary plus - Subtraction or unary minus * Multiplication / Division % Modulo Division (Modulus)(Remainder)

Note: C does not have an operator for exponentiation (power)

Page 16: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (16)

K K Bohra (LMSCT, 2014)

Integer arithmetic When both the operands in a single arithmetic expression are integers, the expression is called Integer expression, and the operation is called integer arithmetic. Integer arithmetic always yields an integer value. Examples

Let a = 14, b = 4 a – b = 10 a + b = 18 a * b = 56 a / b = 3 (decimal part truncated) a % b = 2 (remainder of division)

Real arithmetic An arithmetic operation involving only real operands is called real arithmetic. The result is an approximation of correct value. Examples

6.0 / 7.0 = 0.857143 -2.0 / 3.0 = - 0.666667

Mixed Mode arithmetic When one of the operands is real and the other is integer, the expression is called a mixed mode arithmetic expression. If either operand is of the real type, then only real operation is performed and result is always a real number. Example 15 / 10.0 = 1.5 15 / 10 = 1

»» Library Functions C provides a rich set of built-in functions called as library functions. It helps in making programming easy. These are already created functions. If we want to use mathematical functions like sin, cos, etc we need to include math.h Similarly we can include other library functions as required:

Page 17: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (17)

K K Bohra (LMSCT, 2014)

stdio.h, conio.h, string.h, graphics.h, math.h,

»» Input / Output Statement (Basic I/O Functions)

UnFormatted input/output Function: Reading a Character

getc() File Handling getch()

getch() is also used to read a character from input(console input) device. getch() displays the character without accepting the carriage return(enter key). getch(); char c = getch();

getche() getche() reads a character from input(console input) device but the character will be displayed on the screen and also carriage return is not accepted. getche(); char c = getche();

getchar() getchar() reads a character from input(standard). Syntax: variable_name=getchar();

Page 18: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (18)

K K Bohra (LMSCT, 2014)

Example: char nam;

nam = getchar(); input :ramesh //only r will be stored in variable(nam) It will assign the character ‘H’ to the variable name when we

press the key H on the keyboard.

Display character

while key hit

Enter Required

It Echo Header Files

Function/Macro

getc() File Handling File Handling

File Handling

stdio.h Macro

getch() NO NO NO conio.h Function getche() YES NO YES conio.h Function getchar() YES YES YES stdio.h Function

Writing a Character putch() This is macro; code of putch() is replaced. putchar()

This function writes a character to the standard output device. Syntax: putchar(variable_name);

Where variable_name is type char variable containing a character. This statement displays character contained in the variable-name at the terminal.

Example: answer=’Y’; putchar(answer); Will display the character ‘Y’ on the screen.

Formatted input/output Function: printf()

The printf() function is used to print the character, string, float, integer, octal and hexadecimal values onto the output screen. To display the value of an integer

Page 19: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (19)

K K Bohra (LMSCT, 2014)

variable, we use printf statement with the %d format specifier/modifier. This library function is defined in header file named <stdio.h>.

Similarly %c for character, %f for float variable, %s for string variable, %lf for

double, %x for hexadecimal variable. To generate a newline, we use \n in C printf statement. Syntax

printf( “control string”, arg1, arg2, arg3,… ); Example

printf("LachooCollege"); // LachooCollege printf("%s\n"," LachooCollege "); // LachooCollege printf("%s is over %d years old.\n","LachooCollege

",30); #include <stdio.h> int main() { char ch = 'A'; char str[20] = "fresh2refresh.com"; float flt = 10.234; int no = 150; double dbl = 20.123456; printf("Character is %c \n", ch); printf("Float value is %f \n", flt); printf("Integer value is %d\n" , no); printf("Double value is %lf \n", dbl); printf("Octal value is %o \n", no); printf("Hexadecimal value is %x \n", no); return 0; }

Output

Character is A String is fresh2refresh.com Float value is 10.234000 Integer value is 150

Page 20: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (20)

K K Bohra (LMSCT, 2014)

Double value is 20.123456 Octal value is 226 Hexadecimal value is 96

You can see the output with the same data which are placed within the double quotes of printf statement in the program except

%d got replaced by value of an integer variable(no), %c got replaced by value of a character variable(ch), %f got replaced by value of a float variable(flt), %lf got replaced by value of a double variable(dbl), %s got replaced by value of a string variable(str),

%o got replaced by a Octal value corresponding to integer variable(no), %x got replaced by a hexadecimal value corresponding to integer variable(no), \n got replaced by a newline

scanf()

The scanf() function reads input from stdin, according to the given format, and stores the data in the other arguments. It works a lot like printf(). The format string consists of control characters, whitespace characters, and non-whitespace characters. The control characters are preceded by a % sign. This library function is defined in header file named <stdio.h>.

Syntax scanf( “control string”, arg1, arg2, arg3,… );

Example

int i; scanf("%d",&in); //Here ‘&’is “Address of” it means (Address of variable) scanf("%d%d",&in1,&in1); scanf("%d%f",&in1,&fl1); scanf("%c%f%d",&ch1,&fl1,&in1);

scanf() function is used to read a character, string, numeric data from keyboard(standard input). Consider the below example where the user enters a character and assign it to the variable ch and enters a string and assign it to the variable str.

Page 21: Programming in c unit 1  by K K Bohra Lachoo College

Programming in C [BCA I Sem] UnitI (21)

K K Bohra (LMSCT, 2014)

#include <stdio.h> int main() { char ch; printf("Enter any character \n"); scanf("%c", &ch); printf("Entered character is %c \n", ch); printf("Entered character is %d \n", ch); }

Output: Enter any character a Entered character is a Entered character is 65 The format specifier %d is used in scanf statement so that the value entered is received as an integer and %s for string. Ampersand is used before the variable name ch in scanf statement as &ch.