Unit 1-1
Unit 1-1
Why to use C ?
Because it produces code that runs nearly as fast as code written in assembly language. Some
examples of the use of C might be:
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Data Bases
• Language Interpreters
• Utilities
Advantages of C
• C is the building block for many other programming languages.
• Programs written in C are highly portable.
• Several standard functions are there (like in-built) that can be used to develop programs.
• C programs are collections of C library functions, and it's also easy to add functions to
the C library.
• The modular structure makes code debugging, maintenance, and testing easier.
Disadvantages of C
• C does not provide Object Oriented Programming (OOP) concepts.
• C does not provide binding or wrapping up of data in a single unit.
• C does not provide Constructor and Destructor.
History of C Language
The programming languages that were developed before C language are as follows:-
Language Year Developed By
Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
1
BCA 202-PROGRAMMING IN C Unit-1
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions
and hence the lesser overhead.
8) Pointer
We can directly interact with the memory by using the pointers. We can use pointers for
memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function.
10) Extensible
it can easily adopt new features.
Structure of C programming
2
BCA 202-PROGRAMMING IN C Unit-1
The structure of a C program means the specific structure to start the programming in the C
language. Without a proper structure, it becomes difficult to analyze the problem and the
solution. It also gives us a reference to write more complex programs.
C program is divided into different sections. There are six main sections to a basic c program.
The six sections are,
1. Documentation section
2. Pre-processor section/ link section
3. Definition section
4. Global declaration
5. Main function
6. User defined functions/ sub program section
Documentation section
A set of comment lines giving the name of the program, the author and other details.
Example
/**
* File Name: Helloworld.c
* Author: Manthan Naik
* date: 09/08/2019
* description: a program to display hello world
* no input needed
*/
Link section
Provides instructions to the compiler to link functions from the system library.
Example
#include<stdio.h>
Definition section
defines all symbolic constants.
Example #define PI=3.14
3
BCA 202-PROGRAMMING IN C Unit-1
Example
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
• The first line of the program #include <stdio.h> is a preprocessor command, which
tells a C compiler to include stdio.h file before going to actual compilation.
• 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.
4
BCA 202-PROGRAMMING IN C Unit-1
• The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
• The next line return 0; terminates the main() function and returns the value 0.
5
BCA 202-PROGRAMMING IN C Unit-1
INTEGER TYPES
• Integer occupy one word of storage, and word sizes of machines vary (16 or 32 bits).
• The signed integer uses one bit for sign and 15 bits for the magnitude of the number.
• Smallest to largest.
CHARACTER TYPE
A single character can be defined as a character (char) type data.
Characters are stored in 8 bits of internal storage.
The qualifier signed or unsigned may be explicitly applied to char.
VOID TYPE
has no values.
Used to specify the type of functions.
The type of function is said to be void when it does not return any value to the calling
function.
Play the role of a generic type, ie it can represent any of the other standard type.
6
BCA 202-PROGRAMMING IN C Unit-1
Pointers used to access the memory and deal with their addresses.
User Defined Data Types
C allows the feature called type definition which allows programmers to define their identifier
that would represent an existing data type. There are three such types:
Data Types Description
Structure It is a package of variables of different types under a single name. This is done
to handle data efficiently. "struct" keyword is used to define a structure.
Union These allow storing various data types in the same memory location.
Programmers can define a union with different members, but only a single
member can contain a value at a given time.
Enum It consists of integral constants, and each of them is assigned with a specific
name. "enum" keyword is used to define the enumerated data type.
Variables in C
• Variable is a data name which is used to store data value .
• The value of the variable can be change during the execution.
• The rule for naming the variables is same as the naming identifier.
Rules :
1) They begin with a letter. Some systems permit underscore as the first character.
2) Upto 31 characters (ANSI)
3) Case Sensitive ie. Uppercase and lowercase are significant. A ≠ a
4) It should not be a keyword
5) White space is not allowed.
DECLARATION OF VARIABLES
Declaration does two things
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
Primary type declaration
A variable can be used to store a value of any data type.
data_type v1,v2,v3,….,vn;
v1,v2,v3,…vn are the name of the variables.
• Variables are separated by commas.
• Declaration statement end with a semicolon.
Example:
int count;
float total;
double ratio;
7
BCA 202-PROGRAMMING IN C Unit-1
1. “type definition” – allows users to define an identifier that would represent an existing data
type.
The user-defined data type identifier can be used to declare variables later.
typedef type identifier;
Where type refers to an existing data type, identifier refers to the new name given to the data
type.
The existing data type may belong to any class of type, including the userdefined type.
Example:
typedef int units;
typedef float marks;
Here, units symbolizes int and marks symbolizes float.
units batch1,batch2;
marks name[10];
Advantage of typedef
We can create meaningful data type names for increasing the readability of the program.
2. “enumerated”
Enum identifier (value1,value2,…..,valuen);
The ‘identifier’ is a user-defined enumerated data type which can be used to declare variables
That can have one of the values enclosed within the braces – enumerated constants.
enum identifier v1,v2,…..,vn;
The enumerated variables v1,v2,…..,vn can have one of the values value1,value2,…..,valuen.
V1=value3;
V3=value5;
Example:
Enum day(Moday,Tuesday,…..,Sunday);
Enum day week_st,week_end;
Week_st=Monday;
Week_end=Friday;
8
BCA 202-PROGRAMMING IN C Unit-1
scanf() function
The scanf() function is used for input. It reads the input data from the console.
1. scanf("format string",argument_list);
Program to print cube of given number
Let's see a simple example of c language that gets input from the user and prints the cube of
the given number.
1. #include<stdio.h>
2. int main(){
3. int number;
4. printf("enter a number:");
5. scanf("%d",&number);
6. printf("cube of number is:%d ",number*number*number);
7. return 0;
8. }
Output
enter a number:5
cube of number is:125
The scanf("%d",&number) statement reads integer number from the console and stores the
given value in number variable.
The printf("cube of number is:%d ",number*number*number) statement prints the cube
of number on the console.
9
BCA 202-PROGRAMMING IN C Unit-1
Integer Constants
An integer constant refers to a sequence of digits.
10
BCA 202-PROGRAMMING IN C Unit-1
Real Constants
These numbers are decimal notation,havinfg whole number followed by a decimal point and
the fractional part.
It is possible to omit digits before the decimal part, or digits after the decimal part.
A real number may expressed in exponential notation.
mantissa e exponent
The mantissa is either a real number expressed in decimal notation or integer.
The exponent is an integer number with an optional + or – sign.
The letter e can be written in either uppercase or lowercase.
Embedded white space is not allowed.
The e notation is called floating-point form.
Floating –point constants are represented as double-precision quantities.
f or F --- Single-precision
l or L --- Double-precision
Valid real numbers: 78688L,25636l,444.643f,321.55F,2.5e+05,374e-04
Invalid real numbers: 1.5E+0.5,$25,ox7B,7.5 e -0.5,1,00,00.00
Character Constants
11
BCA 202-PROGRAMMING IN C Unit-1
SYMBOLIC CONSTANTS
Symbolic constant is defined as follows
#define symbolic_name value-of-constant
Example:
#define PI 3.14159
#define MAXMARKS 100
Rules
1) Symbolic names have the same form as variable names.
2) No blank space between the # sign define is permitted.
3) # must be the first character in the line.
4) A blank space is required between #define and symbolic name and between the symbolic
name and constant.
5) #define statements must not end with a semicolon.
6) After definition, the symbolic name should not be assigned any other value within the
program by using an assignment statement.
7) Symbolic names are not declared for data types. Its data type depends on the type of constant.
8) #define statements may appear anywhere in the program but before it is referenced in the
program.
C - Operators
• A symbol use to perform some operation on variables, operands or with the constant is known
as operator.
•Some operator required 2 operand or Some required single operand to perform operation.
• C operators can be classified into a number of categories.
1) Arithmetic operators 5) Increment and decrement operators
2) Relational operators 6) Conditional operators
3) Logical operators 7) Bitwise operators
4) Assignment operators 8) Other operators
An expression is a sequence of operands and operators that reduces to a single value.
The value can be any type other than void.
Arithmetic Operators
12
BCA 202-PROGRAMMING IN C Unit-1
< Checks if the value of left operand is less than the value of right (A < B) is true.
operand. If yes, then the condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value (A >= B) is not
of right operand. If yes, then the condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the value of (A <= B) is true.
right operand. If yes, then the condition becomes true.
Logical Operators
Assume variable A holds 1 and variable B holds 0, then −
Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then (A && B) is
the condition becomes true. false.
|| Called Logical OR Operator. If any of the two operands is non-zero, (A || B) is true.
then the condition becomes true.
! Called Logical NOT Operator. It is used to reverse the logical state of !(A && B) is
its operand. If a condition is true, then Logical NOT operator will true.
make it false.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and
^ is as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
Assume variable 'A' holds 60 and variable 'B' holds 13, then −
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in (A & B) = 12, i.e., 0000
both operands. 1100
| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e., 0011
1101
^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) = 49, i.e., 0011
but not both. 0001
~ Binary One's Complement Operator is unary and has the (~A ) = ~(60), i.e,. -
effect of 'flipping' bits. 0111101
<< Binary Left Shift Operator. The left operands value is moved A << 2 = 240 i.e., 1111
left by the number of bits specified by the right operand. 0000
>> Binary Right Shift Operator. The left operands value is moved A >> 2 = 15 i.e., 0000
right by the number of bits specified by the right operand. 1111
Assignment Operators
The following table lists the assignment operators supported by the C language −
13
BCA 202-PROGRAMMING IN C Unit-1
14
BCA 202-PROGRAMMING IN C Unit-1
Examples
m=5;
Operators Precedence in C
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.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
If statement
The single if statement in C language is used to execute the code if a condition is true. It is also
called one-way selection statement.
15
BCA 202-PROGRAMMING IN C Unit-1
Syntax
if(expression)
{
//code to be executed
}
Example
1. main() 8. c=a-b;
2. { 9. printf(“the difference is%d”,c);
3. int a,b,c; 10. }
4. printf(“enter the value of a and 11. }
b\n”); Output
5. scanf(“%d%d”,&a,&b); enter the value of a and b
6. if (a-b!=0) 53
7. { the difference is 2
If-else statement
The if-else statement in C language is used to execute the code if condition is true or false. It
is also called two-way selection statement.
Syntax
if(expression)
{
//Statements
}
else
{
//Statements
}
16
BCA 202-PROGRAMMING IN C Unit-1
Example
1. main() 8. printf(“a is positive”);
2. { 9. }
3. int a; 10. else
4. printf(“Enter the value of a \n”); 11. {
5. scanf(“%d%d”,&a,&b); 12. printf(“a is negative”);
6. if (a>=0) 13. }
7. { 14. }
Output
Enter the value of a 5
a is positive
Enter the value of a -12
a is negative
17
BCA 202-PROGRAMMING IN C Unit-1
Example
1. #include<stdio.h> 17. printf("c is greatest");
2. #include<conio.h> 18. }
3. void main( ) 19. }
4. { 20. else
5. int a,b,c; 21. {
6. clrscr(); 22. if(b>c)
7. printf("Please Enter 3 number"); 23. {
8. scanf("%d%d%d",&a,&b,&c); 24. printf("b is greatest");
9. if(a>b) 25. }
10. { 26. else
11. if(a>c) 27. {
12. { 28. printf("c is greatest");
13. printf("a is greatest"); 29. }
14. } 30. }
15. else 31. getch();
16. { 32. }
If..else If ladder
The if-else-if statement is used to execute one code from multiple conditions. It is also called
multipath decision statement. It is a chain of if..else statements in which each if statement is
associated with else if statement and last would be an else statement.
Syntax
if(condition1)
{
//statements
}
else if(condition2)
{
//statements
}
else if(condition3)
{
//statements
}
else
{
//statements
}
If..else If ladder Example
1. #include<stdio.h> 9. {
2. #include<conio.h> 10. printf("divisible by both 5 and 8");
3. void main( ) 11. }
4. { 12. else if( a%8==0 )
5. int a; 13. {
6. printf("enter a number"); 14. printf("divisible by 8");
7. scanf("%d",&a); 15. }
8. if( a%5==0 && a%8==0) 16. else if(a%5==0)
18
BCA 202-PROGRAMMING IN C Unit-1
Example
• Program to read the customer number and power consumed and prints the amount o
be paid by the customer. Consumption rate of charges units
0-200 Rs. 0.50 per unit
201-400 Rs. 100+0.65 per unit excess of 200
401-600 Rs. 230+0.80 per unit excess of 400
601 and above Rs 390+Rs.1 per unit excess of 600
Program
1. main() 14. charge=390+(units-600);
2. { 15. printf(“\n Customer No:%d”,num);
3. int units,num; 16. printf(“\nUnits Consumed
4. float charge; :%d”,units);
5. printf(“enter the customer no and 17. printf(“\n Charge : Rs.
units consumed\n”); %.2f”,charge);
6. scanf(“%d%d”,&units,&num); 18. }
7. if (units<=200) Output
8. charge=units*0.50; Enter customer no units consumed
9. else if (units<=400) 1
10. charge=100.00+0.65*(units-200); 500
11. else if 9units<=600) Customer No:1
12. charge=230+0.80*(units-400); Units Consumed :500
13. else Charge: Rs. 310.00
Switch Statement
switch statement acts as a substitute for a long if-else-if ladder that is used to test a list of cases.
A switch statement contains one or more case labels which are tested against the switch
expression. When the expression match to a case then the associated statements with that case
would be executed.
Syntax
Switch (expression)
{
case value1:
//Statements
break;
case value 2:
//Statements
break;
case value 3:
//Statements
case value n:
//Statements
break;
Default:
//Statements
}
19
BCA 202-PROGRAMMING IN C Unit-1
20
BCA 202-PROGRAMMING IN C Unit-1
WHILE STATEMENT
while is entry-control loop.
Syntax
while (test condition)
{
Body of the loop
}
The test condition is evaluated and if the condition is true then the body of the loop is
executed.
After execution of the body, the testcondition is once again evaluated and if it is true then
the body of the loop is executed once again.
The process of repeated execution of the body continues until the testcondition becomes
false and the control is transferred out of the loop.
On exit, the program continues with the statement immediately after the body of loop.
The body of the loop may have one or more statements.
21
BCA 202-PROGRAMMING IN C Unit-1
The body of the loop may not be executed at all if the condition is not satisfied at very first
attempt.
Example 1
1. main() 9. {
2. { 10. sum = sum + i;
3. int i, n, sum; 11. i = i+1;
4. printf(“Enter the value of n\n”); 12. }
5. scanf(“%d”, &n); 13. printf(“sum of natural numbers up to %d
6. i=1; = %d”, n, sum);
7. sum=0; 14. }
8. while(i<=n)
Example2
Program to evaluate the equation y=xn
Program
1. main() 9. while(count<=n)
2. { 10. {
3. int count,n; 11. y=y*x;
4. float x,y; 12. count++;
5. printf(“enter the value of x and n” ); 13. }
6. scanf(“%f %d”, &x ,&n); 14. printf(“\nx= %f; = %d; x to power n =
7. y=1.0; f\n”,x,n,y);
8. count=1; 15. }
DO STATEMENT
Do statement is exit-controlled loop.
Syntax
do
{
body of the loop
} while (test condition);
22
BCA 202-PROGRAMMING IN C Unit-1
FOR STATEMENT
For statement is entry-controlled loop.
Syntax
for(initialization;test-condition,increment)
{
body of the loop;
}
23
BCA 202-PROGRAMMING IN C Unit-1
Example
#include <stdio.h> When the above code is compiled and
executed, it produces the following result
int main () { −
value of a: 10
int a; value of a: 11
value of a: 12
/* for loop execution */ value of a: 13
for( a = 10; a < 20; a = a + 1 ){ value of a: 14
printf("value of a: %d\n", a); value of a: 15
} value of a: 16
value of a: 17
return 0; value of a: 18
} value of a: 19
Example
#include <stdio.h>
When the above code is compiled and
int main () { executed, it produces the following result
−
/* local variable definition */ value of a: 10
int a = 10; value of a: 11
value of a: 12
/* while loop execution */ value of a: 13
while( a < 20 ) { value of a: 14
printf("value of a: %d\n", a); value of a: 15
a++; value of a: 16
} value of a: 17
value of a: 18
return 0; value of a: 19
}
Example
#include <stdio.h> }
When the above code is compiled and
int main () { executed, it produces the following result
−
/* local variable definition */ value of a: 10
int a = 10; value of a: 11
value of a: 12
/* do loop execution */ value of a: 13
do { value of a: 14
printf("value of a: %d\n", a); value of a: 15
a = a + 1; value of a: 16
}while( a < 20 ); value of a: 17
value of a: 18
return 0; value of a: 19
Example1:Program to generate prime numbersnbetween 1 and n.
1. #include<stdio.h> 4. {
2. #include <conio.h> 5. int i,j,n;
3. void main() 6. lbl: printf(“enter the value of n\n”);
24
BCA 202-PROGRAMMING IN C Unit-1
Example2:
Program To Print N Fibonacci Number
1. #include <stdio.h> 10. for(i=1;i<=n-2;i++)
2. #include <conio.h> 11. {
3. void main() 12. fib=n1=+n2;
4. { 13. printf(“\t%d”,fib);
5. int n1=0,n2=1,n,i,fib; 14. n1=n2;
6. clrscr(); 15. n2=fib;
7. printf (“enter the value of n\n”); 16. }
8. printf(“%d”,&n) 17. getch();
9. printf(“%d\t%d”,n1,n2); 18. }
Additional features of for loop
1. More than one variable can be initialized at a time in the for statement. Example
p=1;
for(n=0;n<10;n++)
Can be written as
for(p=1,n=0;n<10;n++)
2. The increment section may also have more than one part. Example
for (n=0;n<10;n++,m--)
3. Test condition may have any compound relation and the testing need not be limited
only to the loop control variable. Example
sum=0
for (i=0;i<10&& sum <100;i++)
{
sum=sum+i;
}
4. Expression can be used in the assignment statements of initialization and increment
section. Example
for(x=(m+n)/2;x>0;x=x/2)
5. One or more section can be omitted in for loop.----
m=5;
for(;m<10;)
{
printf(“%d\n”,m);
m=m+2;
}
6. We can set up the time delay loops using for statement. Example
for(j=1;j<1000;j++);
25
BCA 202-PROGRAMMING IN C Unit-1
break statement in C
The break statement in C programming has the following two usages −
• When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
• It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops, the break statement will stop the execution of the innermost
loop and start executing the next line of code after the block.
26
BCA 202-PROGRAMMING IN C Unit-1
Syntax
The syntax for a break statement in C is as
follows −
break;
Example
1. #include <stdio.h> 12. printf("value of a: %d\n", a);
2. int main () { 13. a++;
3. /* local variable definition */ 14. } while( a < 20 );
4. int a = 10; 15. return 0;
5. /* do loop execution */ 16. }
6. do {
Output −
7. if( a == 15) {
value of a: 10
8. /* skip the iteration */ value of a: 11
9. a = a + 1; value of a: 12
10. continue; value of a: 13
11. } value of a: 14
27
BCA 202-PROGRAMMING IN C Unit-1
value of a: 16 value of a: 18
value of a: 17 value of a: 19
goto statement in C
A goto statement in C programming provides an unconditional jump from the 'goto' to a
labeled statement in the same function.
NOTE − Use of goto statement is highly discouraged in any programming language because
it makes difficult to trace the control flow of a program, making the program hard to
understand and hard to modify. Any program that uses a goto can be rewritten to avoid them.
Syntax
The syntax for a goto statement in C is as
follows −
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program
above or below to goto statement.
Example
1. #include <stdio.h> 14. }while( a < 20 );
2. int main () { 15. return 0;
3. /* local variable definition */ 16. }
4. int a = 10; Output −
5. /* do loop execution */ value of a: 10
6. LOOP:do { value of a: 11
7. if( a == 15) { value of a: 12
8. /* skip the iteration */ value of a: 13
9. a = a + 1; value of a: 14
10. goto LOOP; value of a: 16
11. } value of a: 17
12. printf("value of a: %d\n", a); value of a: 18
13. a++; value of a: 19
28