Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

C programming notes for BCA, Lecture notes of C programming

C programming notes for BCA degree in bharathiar university

Typology: Lecture notes

2018/2019
On special offer
30 Points
Discount

Limited-time offer


Uploaded on 06/13/2019

babythangarasu
babythangarasu 🇮🇳

4.7

(3)

9 documents

1 / 134

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Basic structure of C program
Structure of C program is defined by set of rules called protocol, to be followed by programmer while
writing C program. All C programs are having sections/parts which are mentioned below.
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Main function
6. User defined function definition section
Description for each section of a C program:
Let us see about each section of a C basic program in detail below.
Please note that a C program mayn’t have all below mentioned sections except main function and
link sections.
Also, a C program structure mayn’t be in below mentioned order.
S.No Sections Description
1 Documentation
section
We can give comments about the program, creation or modified date, author name
etc in this section. The characters or words or anything which are given between “/
*” and “*/”, won’t be considered by C compiler for compilation process.These will
be ignored by C compiler during compilation.
Example : /* comment line1 comment line2 comment 3 */
2 Link Section Header files that are required to execute a C program are included in this section
3 Definition Section In this section, variables are defined and values are set to these variables.
4 Global declaration
section
Global variables are defined in this section. When a variable is to be used
throughout the program, can be defined in this section.
6 Main function Every C program is started from main function and this function contains two
major sections called declaration section and executable section.
7 User defined
function section
User can define their own functions in this section which perform particular task as
per the user requirement.
Example C program
/* C basic structure program Documentation section
Author: fresh2refresh.com
Date : 01/01/2012
*/#include <stdio.h> /* Link section */
int total = 0; /* Global declaration and definition section */
int sum (int, int); /* Function declaration section */
int main () /* Main function */
{
printf (“This is a C basic program \n”);
total = sum (1, 1);
printf (“Sum of two numbers : %d \n”, total);
return 0;
}
int sum (int a, int b) /* User defined function */
{ /* definition section */
return a + b;
}
Output:
This is a C basic program
Sum of two numbers : 2
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64
Discount

On special offer

Partial preview of the text

Download C programming notes for BCA and more Lecture notes C programming in PDF only on Docsity!

Basic structure of C program

Structure of C program is defined by set of rules called protocol, to be followed by programmer while writing C program. All C programs are having sections/parts which are mentioned below.

  1. Documentation section
  2. Link Section
  3. Definition Section
  4. Global declaration section
  5. Main function
  6. User defined function definition section

Description for each section of a C program:

  • Let us see about each section of a C basic program in detail below.
  • Please note that a C program mayn’t have all below mentioned sections except main function and link sections.
  • Also, a C program structure mayn’t be in below mentioned order.

S.No Sections Description 1 Documentation section

We can give comments about the program, creation or modified date, author name etc in this section. The characters or words or anything which are given between “/ ” and “/”, won’t be considered by C compiler for compilation process.These will be ignored by C compiler during compilation. Example : /* comment line1 comment line2 comment 3 */ 2 Link Section Header files that are required to execute a C program are included in this section 3 Definition Section In this section, variables are defined and values are set to these variables. 4 Global declaration section

Global variables are defined in this section. When a variable is to be used throughout the program, can be defined in this section. 6 Main function Every C program is started from main function and this function contains two major sections called declaration section and executable section. 7 User defined function section

User can define their own functions in this section which perform particular task as per the user requirement.

Example C program

/* C basic structure program Documentation section Author: fresh2refresh.com Date : 01/01/ */#include <stdio.h> / Link section / int total = 0; / Global declaration and definition section / int sum (int, int); / Function declaration section / int main () / Main function / { printf (“This is a C basic program \n”); total = sum (1, 1); printf (“Sum of two numbers : %d \n”, total); return 0; } int sum (int a, int b) / User defined function / { / definition section / return a + b; }

Output:

This is a C basic program Sum of two numbers : 2

C – Tokens

C tokens, Identifiers and Keywords are the basics in a C program.

C tokens:

  • C tokens are the basic buildings blocks in C language which are constructed together to write a C program.
  • Each and every smallest individual units in a C program are known as C tokens.
  • C tokens are of six types. They are, C Tokens

Keywords Iden�fiers Constants Strings Special symbols Operators

  1. Keywords (eg: int, while),
  2. (^) Iden�fiers (eg: main, total),
  3. Constants (eg: 10, 20),
  4. Strings (eg: “total”, “hello”),
  5. Special symbols (eg: (), {}),
  6. Operators (eg: +, /,-,)*

C tokens example program:

int main() { int x, y, total; x = 10, y = 20; total = x + y; Prin� (“Total = %d \n”, total); }.

where,

  • main – iden�fier
  • {,}, (,) – delimiter
  • int – keyword
  • x, y, total – iden�fier
  • main, {, }, (, ), int, x, y, total – tokens Do you know how to use C token in real time application programs? We have given simple real time application programs where C token is used. You can refer the below C programs to know how to use C token in real time program.

Keywords in C language:

  • Keywords are pre-defined words in a C compiler.
  • Each keyword is meant to perform a specific func�on in a C program.
  • Every C word is either keyword or an iden�fier.
  • Fixed meaning and can’t be changed.
  • It serves as basic building blocks for program statements.
  • It should be wri�en in lower case le�ers. C language supports 32 keywords which are given below.

uto double int struct const float short unsigned break else long switch continue for signed void case enum register typedef default goto sizeof volatile char extern return union do if static while

Identifiers in C language:

  • Each program elements in a C program are given a name called iden�fiers.
  • Names given to iden�fy Variables, func�ons and arrays are examples for iden�fiers.
  • These are user defined names and consists of a sequence of le�ers and digits.

Character constants

String constants

Backslash character constants

S.no Constant type data type Example 1 Integer constants int unsigned int long int long long int

53, 762, -478 etc 5000u, 1000U etc 483, 2,147,483, 2 Real or Floa�ng point constants float doule

3 Octal constant int 013 /* starts with 0 / 4 Hexadecimal constant int 0×90 / starts with 0x */ 5 character constants char ‘A’ , ‘B’, ‘C’ 6 string constants char “ABCD” , “Hai”

Rules for constructing C constant:

1. Integer Constants in C: - An integer constant must have at least one digit. - It must not have a decimal point. - It can either be posi�ve or nega�ve. - No commas or blanks are allowed within an integer constant. - If no sign precedes an integer constant, it is assumed to be posi�ve. - The allowable range for integer constants is -32768 to 32767. 2. Real constants in C: - A real constant must have at least one digit - It must have a decimal point - It could be either posi�ve or nega�ve - If no sign precedes an integer constant, it is assumed to be posi�ve. - No commas or blanks are allowed within a real constant. 3. Character and string constants in C: - A character constant is a single alphabet, a single digit or a single special symbol enclosed within single quotes. - The maximum length of a character constant is 1 character. - String constants are enclosed within double quotes. 4. Backslash Character Constants in C: - There are some characters which have special meaning in C language. - They should be preceded by backslash symbol to make use of special func�on of them. - Given below is the list of special characters and their purpose. - These are also called as escape sequences.

Backslash_character Meaning \b Backspace \f Form feed \n New line \r Carriage return \t Horizontal tab \” Double quote \’ Single quote

\ Backslash \v Ver�cal tab \a Alert or bell ? Ques�on mark \N Octal constant (N is an octal constant) \XN Hexadecimal constant (N – hex.dcml cnst)

How to use constants in a C program?

We can define constants in a C program in the following ways.

  1. By “const” keyword
  2. By “#define” preprocessor direc�ve 1. Example program using const keyword in C: #include <stdio.h>

void main() { const float number = 3.14; /Real constant/ const char letter = ‘A’; /char constant/ printf(“value of number : %f \n”, number ); printf(“value of letter : %c \n”, letter ); }

Output: value of number : 3. value of le�er : A

2. Example program using #define preprocessor directive in C: #include <stdio.h>

#define number 3. #define letter ‘A’ void main() { printf(“value of number : %f \n”, number ); printf(“value of letter : %c \n”, letter ); }

Output: value of number : 3. value of le�er : A

C – Variable

  • C variable is a named loca�on in a memory where a program can manipulate the data. This loca�on is used to hold the value of the variable.
  • The value of the C variable may get change in the program.
  • C variable might be belonging to any of the data type like int, float, char etc.

Rules for naming C variable:

  1. Variable name must begin with le�er or underscore.
  2. Variables are case sensi�ve
  3. They can be constructed with digits, le�ers.
  4. No special symbols are allowed other than underscore.
  5. (^) sum, height, _value are some examples for variable name

In a signed integer uses one bit for sign and 15 bits for magnitude C has three classes of integer storage short int

  1. int
  2. long int

It has a set of qualifiers i.e.,

  1. sign qualifier
  2. unsigned qualifier

short int uses half the range of storage amount of data, unsigned int use all the bits for the magnitude of the number and are positive.

short int

int

long int Datatype Size Range char or signed char 1 byte -128 to 127 unsigned char 1 byte 0 to 255 int or signed int 2 byte -32,768 to 32, 767 unsigned int 2 bytes 0 to 65535

Floating Point Datatype : Floating Point numbers are stored with 6 digits of precision. Those are defined with keyword float. When the accuracy is not sufficient then the datatype double can be used. double gives a precesion of 14 digits these known as double precesion numbers. Still for a better process we can use long double which uses 80 bits.

float

double

long double

Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Character Datatype : Character are usually stored in 8 bits

Void datatype : A void type has no value this is usually used to specify the return type of function , this function does not return any value to calling function

Declaration of variables

F 0B 7 C variable is a named location in a memory where a program can manipulate the data. This location is used to hold the value of the variable. F 0B 7 The value of the C variable may get change in the program.

F 0B 7 C variable might be belonging to any of the data type like int, float, char etc

Rules for naming C variable:

  1. Variable name must begin with le�er or underscore.
  2. Variables are case sensi�ve
  3. They can be constructed with digits, le�ers.
  4. No special symbols are allowed other than underscore.
  5. sum, height, _value are some examples for variable name Types of Variable declara�on :
  • Primary Type Declara�on
  • User Defined Declara�on No Type Syntax Example 1 Primary Type Declara�on^ data_type v1, v2, v3 … vn; int x, y, z;

char flat, ch; 2 User Defined Declara�on^ typedef data_type identifier; typedef int units;

typedef float marks;

units batch1, batch2;

marks sub1, sub2;

enum identifier {v1, v2, …vn}; enum day {mon, tue, …sun};

enum day week_st, week_end;

They include :

  1. Arithmetic
  2. Relational
  3. Logical
  4. Assignment
  5. Increment and Decrement
  6. Conditional
  7. Bitwise
  8. Special

Arithmetic Operators : C provides all the basic arithmetic operators, they are +, -, *, /, % Integer

division truncates any fractional part. The modulo division produces the remainder of an integer division.

Eg: a + b a – b a * b -a * b a / b a % b

Here „a‟ and „b‟ are variables and are known as operands. % cannot be used for floating point data. C does not have an operator for exponentiation.

Integer Arithmetic: When the operands in an expression are integers then the expression is an integer expression and the operation is called integer arithmetic. This always yields an integer value. For Eg. a = 14 and n = 4 then

a - b = 10 Note : During modulo division,the a + b = 18 sign of the result is always the sign a * b = 56 of the first operand (the dividend ) a / b = 3 - 14 % 3 = - a % b = 2 -14 % - 3 = 2 14 % -3 = 2 Real Arithmetic / Floating Pont Arithmetic:

Floating Point Arithmetic involves only real operands of decimal or exponential notation. If x, y & z are floats, then

x = 6.0/7.0 = 0.

y = -1.0/3.0 = 0.

z = 3.0/2.0 = 1.

% cannot be used with real operands

Mixed mode Arithmetic: When one of the operands is real and the other is integer the expression is

a mixed mode arithmetic expression.

Eg: 15/10.0 = 1.

Relational Operator: These are the operators used to Compare arithmetic, logical and character

expressions.the value of a relational express is either one or zero .it is 1 if one is the specified relation is true and zero if it is false For eg:

10 < 20 is true 20<10 is false

The relational operators in C are

Operator Meaning < is less than < = is less than or equal to

is greater than or equal to = is greater than or equal to = = is equal to

Shorthand operator

Assignment operator

a + = 1 a = a+ a - = 1 a=a- a * = n+1 a = a* (n + 1) a / = n+1 a = a/(n+1) a % = b a = a % b Increment and Decrement Operators: ++ and - -

The Operator + + adds 1 to the operand while -- subtracts 1, Both are unary operators

Eg : ++x or x ++ == > x+=1 == > x=x+

. -- x or x- - == > x-=1 == > x=x-

A Profix operator first adds 1 to the operand and then the result is assigned to the variable on left. A

postfix operator first assigns the value to the variable on the left and the increments the operand.

Eg: 1) m = 5; 2). m = 5 y = ++m; y = m++ O/P m =6, y=6 m=6, y= Conditional operator : is used to check a condition and Select a Value depending on the Value of the

condition.

Variable = (condition)? Value 1 : Value 2:

If the Value of the condition is true then Value 1 is e valued assigned to the varable, otherwise

Value2.

Eg: big = (a>b)? a:b;

This exxp is equal to

if (a>b)

big = a;

else

big = b;

Bitwise operator : are used to perform operations at binary level i. e. bitwise. these operators are used for testing the bits, or Shifting them right or left. These operators are not applicable to float or double. Following are the Bitwise operators with their meanings.

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise Exclusive – OR

<< Left Shift

Right Shift

~ Complement Eg‟ consider a = 13 & b = 6 as 8 bit short int (1byte) << Left Shift a = 13 Binary 00001101 b = 6 00000110 Consider a << 2 which Shifts two bits to left , that is 2 zeros are inserted at the right and two bits at the

left are moved out.

00001101

Moved

Finally the result is 00110100. Deci 52 (13x4)

Note : when you shift a bit towards left its Decimal Value is multiplied by Two (2).

a =13 13= 00001101

High priority ===> * / %

Low priority ===> + -

Rules for evaluation of expression

  • First parenthesized sub expression left to right are evaluated. If parentheses are nested, the evaluation begins with the innermost sub expression.
  • The precedence rule is applied in determining the order of application of operators in evaluating sub expressions. The associability rule is applied when two or more operators of the same precedence level appear in the sub expression.
  • Arithmetic expressions are evaluated from left to right using the rules of precedence. When Parentheses are used, the expressions within parenthesis assume highest priority.

Type Conversions in Expressions:

Normally before an operation takes pace both the operands must have the same type. C converts One or

both the operands to the appropriate date types by “Type conversion”. This can be achieved in 3 ways.

Implicit Type conversion : In this the data type /Variable of lower type (which holds lower range of values or has lower precision ) is converted to a higher type (which holds higher range of values or has high precision). This type of conversion is also called “promotion”.

If a Char is converted into int, it is called as Internal promotion

Eg: int i;

char c;

c = ‘a’;

i = c;

Now the int Variable i holds the ASCII code of the char ‘a’

a) An arithmetic operation between an integer and integer yields an integer result.

b) Operation between a real yields a real

c) Operation between a real & an integer always yields a real result

Eg: 5/2 = 2 2/5 = 0 5.0/2 = 2.5 2.0/50. = 0. 5/2.0 = 2.5 2/5.0 = 0. 5.0/2.0 = 2.5 2.0/5.0 = 0.

Assignment Type Conversion: If the two Operands in an Assignment operation are of different data types the right side Operand is automatically converted to the data type of the left side.

Eg : Let „k‟ is an int var & „a‟ is a float var

int k; yes float a; yes k= 5/2 2 k=2/5 0 a = 5/2 2. k=5.0/2 2 k=2.0/5 0 a = 5.0/2 2. k=55.0/2 2 k=2/5.0 0 a = 5/2.0 2. k=5.0/2.0 2 k=2.0/5.0 0 a = 2/5 0. a = 2.0/5 0. a = 2.0/0.5 0. Explicit Type Conversion: When we want to convent a type forcibly in a way that is different from automatic type conversion, we need to go for explicit type conversion.

(type name) expression;

Type name is one of the standard data type. Expression may be a constant variable Or an expression this process of conversion is called as casting a value.

Eg: x = (int) 7.

A = (int) 21.3/(int) 4.

Y =( int) (a + b)

P = (double)sum/n

Operator - precedence & Associativity

precedence is nothing but priority that indicates which operator has to be evaluated first when there are more than one operator.

atan() Arc Tangent atan2() Arc Tangent of Quotient cos() Cosine sin() Sine

Hyperbolic functions

cosh() Hyperbolic Cosine sinh() Hyperbolic Sine tanh() Hyperbolic Tangent

Absolute Value functions

fabs() Absolute Value of Floating-Point Number

Nearest Integer, Absolute Value, and Remainder functions

ceil() Ceiling floor() Floor fmod() Floating Modulus

Exponential and Logarithmic functions

exp() Exponential frexp() Split into Fraction and Exponent ldexp() Combine Fraction and Exponent log() Natural Logarithm log10() Common Logarithm modf() Split into Integer and Fractional Parts

Power functions

pow() Power sqrt() Square Root

Managing Input and Output operations

i. Reading a character:

getchar ( ) function is used to read one character at a time from the key board

Syntax ch = getchar ( );

Where, i. ch is a valid ‘C’ variable

ii. It must be declared as a character data type.

Eg:

char name;

name = getchar();

Eg. Program:

main ( )

{

char ans;

printf(“What do you like to drink”);

printf(“type ‘y’ for coffee and ‘n’ for tea”);

ans = getchar();

if (ans==’Y’ || ans==’y’)

printf(“I need a coffee”);

else

printf(“I need a tea”);

getch();

O/P: What do you like to drink?

type ‘y’ for coffee and ‘n’ for tea Y

I need a coffee

When this function is executed, the computer will wait for a key to be pressed and assigns the value to the

variable when the “enter” key pressed.

C supports other similar functions

Func�on Test isalnum(c) Is c an alphanumeric character? isalpha(c) Is c an alphabe�c character? isdigit(c) Is c a digit? islower(c) Is c a lower case le�er? isprint(c) Is c a printable character? ispunct(c) Is c a punctua�on mark? isspace(c) Is c a white space character? isupper(c) Is c an upper case later?

ii. Writing a character:

putchar ( ) : Function is used to display one character at a time on the monitor.

Syntax: putchar (ch); Ex char ch = ‘m’ putchar (ch);