0% found this document useful (0 votes)
80 views

BCA-202 Unit-1

Uploaded by

pawan.043181
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views

BCA-202 Unit-1

Uploaded by

pawan.043181
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT 1

Structure of C Program

The basic structure of a C program is divided into 6 parts which makes it easy to read, modify,
document, and understand in a particular format. C program must follow the below mentioned
outline in order to successfully compile and execute. Debugging is easier in a well-structured C
program.
Sections of the C Program
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs

1. Documentation

This section consists of the description of the program, the name of the program, and the
creation date and time of the program. It is specified at the start of the program in the form of
comments. Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.
or
/*
description, name of the program, programmer name, date, time etc.
*/
Anything written as comments will be treated as documentation of the program and this will
not interfere with the given code. Basically, it gives an overview to the reader of the program.

2. Preprocessor Section

All the header files of the program will be declared in the preprocessor section of the program.
Header files help us to access other’s improved code into our code. A copy of these multiple
files is inserted into our program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
3. Definition

Preprocessors are the programs that process our source code before the process of compilation.
There are multiple steps which are involved in the writing and execution of the program.
Preprocessor directives start with the ‘#’ symbol. The #define preprocessor is used to create a
constant throughout the program. Whenever this name is encountered by the compiler, it is
replaced by the actual piece of defined code.
Example:
#define long long ll

4. Global Declaration

The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used anywhere in the
program.
Example:
int num = 18;

5. Main() Function

Every C program must have a main function. The main() function of the program is written in
this section. Operations like declaration and execution are performed inside the curly braces of
the main program. The return type of the main() function can be int as well as void too. void()
main tells the compiler that the program will not return any value. The int main() tells the
compiler that the program will return an integer value.
Example:
void main()
or
int main()

6. Sub Programs

User-defined functions are called in this section of the program. The control of the program is
shifted to the called function whenever they are called from the main or outside the main()
function. These are specified as per the requirements of the programmer.
Example:
int sum(int x, int y)
{
return x+y;
}
Example: Below C program to find the sum of 2 numbers:
 C
// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/

// Link
#include <stdio.h>

// Definition
#define X 20

// Global Declaration
int sum(int y);

// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}

// Subprogram
int sum(int y)
{
return y + X;
}
Output
Sum: 75

Data Types in C

Each variable in C has an associated data type. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. It specifies the type
of data that the variable can store like integer, character, floating, double, etc. The data type is
a collection of data with values having fixed values, meaning as well as its characteristics.
The data types in C can be classified as follows:
Types Description

Primitive Data Arithmetic types can be further classified into integer and floating data
Types types.

The data type has no value or operator and it does not provide a result to
Void Types its caller. But void comes under Primitive data types.

User Defined It is mainly used to assign names to integral constants, which make a
DataTypes program easy to read and maintain

The data types that are derived from the primitive or built-in datatypes
Derived types are referred to as Derived Data Types.

Different data types also have different ranges up to which they can store numbers. These
ranges may vary from compiler to compiler. Below is a list of ranges along with the memory
requirement and format specifiers on the 32-bit GCC compiler.

Memory Format
Data Type (bytes) Range Specifier

short int 2 -32,768 to 32,767 %hd


Memory Format
Data Type (bytes) Range Specifier

unsigned
short int 2 0 to 65,535 %hu

unsigned
int 4 0 to 4,294,967,295 %u

-2,147,483,648 to
int 4 2,147,483,647 %d

-2,147,483,648 to
long int 4 2,147,483,647 %ld

unsigned
long int 4 0 to 4,294,967,295 %lu

long long
int 8 -(2^63) to (2^63)-1 %lld

unsigned
long long 0 to
int 8 18,446,744,073,709,551,615 %llu

signed
char 1 -128 to 127 %c

unsigned
char 1 0 to 255 %c
Memory Format
Data Type (bytes) Range Specifier

float 4 %f
1.2E-38 to 3.4E+38

double 8 %lf
1.7E-308 to 1.7E+308

long
double 16
3.4E-4932 to 1.1E+4932 %Lf

Enum in C
The enum in C is also known as the enumerated type. It is a user-defined data type that consists of
integer values, and it provides meaningful names to these values. The use of enum in C makes the
program easy to understand and maintain. The enum is defined by using the enum keyword.

The following is the way to define the enum in C:

enum flag{integer_const1, integer_const2,.....integter_constN};

In the above declaration, we define the enum named as flag containing 'N' integer constants. The
default value of integer_const1 is 0, integer_const2 is 1, and so on. We can also change the default
value of the integer constants at the time of the declaration.

1. #include <stdio.h>
2. enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
3. int main()
4. {
5. enum weekdays w; // variable declaration of weekdays type
6. w=Monday; // assigning value of Monday to w.
7. printf("The value of w is %d",w);
8. return 0;
9. }I
In the above code, we create an enum type named as weekdays, and it contains the name of all the
seven days. We have assigned 1 value to the Sunday, and all other names will be given a value as
the previous value plus one.

Output

10.

Variables in C
A variable is a name of the memory location. It is used to store data. Its value can be changed,
and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

type variable_list;

The example of declaring the variable is given below:

1. int a;
2. float b;
3. char c;

Here, a, b, c are variables. The int, float, char are the data types.

There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Rules for defining variables
o A variable can have alphabets, digits, and underscore.
o A variable name can start with the alphabet, and underscore only. It can't start with a digit.
o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Global Variable
A variable that is declared outside the function or block is called a global variable. Any function
can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

1. int value=20;//global variable


2. void function1(){
3. int x=10;//local variable
4. }

Printing Out and Inputting Variables

C language has standard libraries that allow input and output in a program.
The stdio.h or standard input output library in C that has methods for input and output.

scanf()

The scanf() method, in C, reads the value from the console as per the type specified.
Syntax:
scanf(“%X”, &variableOfXType); where %X is the format specifier in C. It is a way to tell the
compiler what type of data is in a variable and & is the address operator in C, which tells the
compiler to change the real value of this variable, stored at this address in the memory.

printf()

The printf() method, in C, prints the value passed as the parameter to it, on the console screen.
Syntax:
printf(“%X”, variableOfXType); where %X is the format specifier in C. It is a way to tell the
compiler what type of data is in a variable .
Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint" etc.

The basic type in C includes types like int, float, char, etc. Inorder to input or output the
specific type, the X in the above syntax is changed with the specific format specifier of that
type. The Syntax for input and output for these are:

 Integer:
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);

 Float:
Input: scanf("%f", &floatVariable);
Output: printf("%f", floatVariable);

 Character:
Input: scanf("%c", &charVariable);
Output: printf("%c", charVariable);

Constants in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4,
"c programming" etc.

There are different types of constants in C programming.


2 ways to define constant in C

There are two ways to define constant in C programming.

1. const keyword
2. #define preprocessor

1) C const keyword

The const keyword is used to define constant in C programming.

const float PI=3.14;

2) C #define preprocessor

The #define preprocessor is also used to define constant.

#define BORN 2000

Arithmetic operators
Arithmetic operators are used to perform arithmetic/mathematical operations on operands.
For instance, the symbols “+” and “-” are used for addition and subtraction, respectively, while
“*” is used for multiplication on numeric values
Based on the number of operands, C Arithmetic operators can be of two types:
1. Binary Arithmetic Operators
2. Unary Arithmetic Operators

1. Binary Arithmetic Operators


The binary arithmetic operators operate or work on two operands. C provides 5 Binary
Arithmetic Operators for performing arithmetic functions which are as follows:

Name of the
Operator Operator Arithmetic Operation Syntax

Addition Add two operands.


+ x+y
Name of the
Operator Operator Arithmetic Operation Syntax

Subtract the second operand


Subtraction from the first operand.
– x–y

Multiplication Multiply two operands.


* x*y

Divide the first operand by the


Division second operand.
/ x/y

Calculate the remainder when the


first operand is divided by the X%Y
second operand.
% Modulus

2. Unary Arithmetic Operators


The unary arithmetic operators operate or work with a single operand. In C, we have two unary
arithmetic operators which are as follows:

Operator Symbol Operation Implementation

Decrement Decreases the integer value of the


Operator — variable by one. –h or h–

Increment Increases the integer value of the


Operator ++ variable by one. ++h or h++

Increment: The ‘++’ operator is used to increment the value of an integer. When placed
before the variable name (also called the pre-increment operator), its value is incremented
instantly. For example, ++x.
And when it is placed after the variable name (also called post-increment operator), its value is
preserved temporarily until the execution of this statement and it gets updated before the
execution of the next statement. For example, x++.
Decrement: The ‘ – – ‘ operator is used to decrement the value of an integer. When placed
before the variable name (also called the pre-decrement operator), its value is decremented
instantly. For example, – – x.
And when it is placed after the variable name (also called post-decrement operator), its value
is preserved temporarily until the execution of this statement and it gets updated before the
execution of the next statement. For example, x – –..

Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.

The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values
are known as Boolean values.

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y


<= Less than or equal to x <= y

Order of Precedence
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


Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't represent itself when
used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new
line.

List of Escape Sequences in C

Escape Sequence Meaning

\a Alarm or Beep

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Tab (Horizontal)

\v Vertical Tab

\\ Backslash

\' Single Quote

\" Double Quote

\? Question Mark

\nnn octal number


\xhh hexadecimal number

\0 Null

Escape Sequence Example


1. #include<stdio.h>
2. int main(){
3. int number=50;
4. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");
5. return 0;
6. }

Output:

You
are
learning
'c' language
"Do you know C language"

Conditionals (The if statement, The switch statement)

if-else statement

An if-else statement in C programming is a conditional statement that executes a different set of


statements based on the condition that is true or false. The 'if' block will be executed only when
the specified condition is true, and if the specified condition is false, then the else block will be
executed.

Syntax of if-else statement is given below:

1. if(expression)
2. {
3. // statements;
4. }
5. else
6. {
7. // statements;
8. }
switch statement

A switch statement is a conditional statement used in C programming to check the value of a


variable and compare it with all the cases. If the value is matched with any case, then its
corresponding statements will be executed. Each case has some name or number known as the
identifier. The value entered by the user will be compared with all the cases until the case is found.
If the value entered by the user is not matched with any case, then the default statement will be
executed.

Syntax of the switch statement is given below

switch(expression)
{
case constant 1:
// statements;
break;
case constant 2:
// statements;
break;
case constant n:
// statements;
break;
default:
// statements;
}
Similarity b/w if-else and switch

Both the if-else and switch are the decision-making statements. Here, decision-making statements
mean that the output of the expression will decide which statements are to be executed.

LOOPING STATEMENT
Loops are the statements that execute one or more statement several number of times. In C
programming language there are three types of loops; while, for and do-while.
Why use loop ?

When we need to execute a block of code several number of times then we use looping concept
in C language. In other words when we want to do a operation many times, we use loops.

Advantage with looping statement

 Reduce Code length

 Take less memory space.

 Burden on the developer is reducing.

Difference between conditional and looping statement

Conditional statement executes only once in the program


where as looping statements executes repeatedly several
number of time.

While loop

In while loop Firstly the condition is checked. If condition is


true then control goes inside the loop body other wise goes
outside the body. while loop will be repeats in clock wise
direction.

Syntax
while(condition)
{
Statements;
......
Increment/decrements (++ or --);
}
Note: If while loop condition never false then loop become infinite loop.
Example of while loop

#include<stdio.h>
#include<conio.h>

void main()
{
int i;
i=1;
while(i<5)
{
printf("\n %d",i);
i++;
}
getch();
}

Output
1
2
3
4

For loop

for loop is a statement which allows code to be repeatedly executed. For loop contains 3 parts
Initialization, Condition and Increment or Decrements
Example of for loop

void main()
{
int i;
for(i=1;i<5;i++)
{
printf("\n%d",i);
}

}
Output
1
2
3
4

do-while

A do-while loop is similar to a while loop, except that a do-while loop is execute at least one
time. In this, firstly the statements are executed after that condition is checked.
Syntax

do

Statements;

........

Increment/decrement (++ or --)

} while();
When use do..while Loop

When we need to repeat the statement block at least 1 time then we use do-while loop.

The break Statement


Sometime We want to jump out of a loop instantly, without checking conditional test. The keyword
break allows us to do this. When break is encountered inside any loop, control automatically goes
outside the loop. A break is usually associated with an if. As an example, let’s consider the
following example.
Example: Write a program to determine whether a number is prime or not.
main( )
{
Int num , i ;
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
i=2;
while ( i <= num - 1 )
{
if ( num % i == 0 )
{
printf ( "Not a prime number" ) ;
break ;
}
i++ ;
}
if ( i == num )
printf ( "Prime number" ) ;
}
In this program the as num % i becomes zero, the message “Not a prime number” is printed and
the control breaks out of the while loop.

The continue Statement


The continue statement in C programming works somewhat like the break statement. Instead of
forcing termination, it forces the next iteration of the loop to take place, skipping any code in
between.
For the for loop, continue statement causes the conditional test and increment portions of the
loop to execute. For the while and do...while loops, continue statement causes the program
control to pass to the conditional tests.
Syntax
The syntax for a continue statement in C is as follows −
continue;
Flow Diagram

Example

#include <stdio.h>

int main () {
/* local variable definition */
int a = 10;

/* do loop execution */
do {

if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}

printf("value of a: %d\n", a);


a++;

} while( a < 20 );

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

goto statement in C
The goto statement is a jump statement which is sometimes also referred to as unconditional jump
statement. The goto statement can be used to jump from anywhere to anywhere within a function.
Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;

In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a
label. Here label is a user-defined identifier which indicates the target statement. The statement
immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before
the ‘goto label;’ statement in the above syntax.

You might also like