0% found this document useful (0 votes)
155 views24 pages

Unit 1

This document provides an overview of the BCA-104 Programming in C course. It discusses the basics of the C language, including its history and importance. It outlines the structure of a C program and covers topics like data types, variables, constants, input/output functions, and keywords. The character set and rules for identifiers in C are also defined. Data types like integer, floating point, and character are described along with their sizes and ranges.

Uploaded by

Farhan Patel
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)
155 views24 pages

Unit 1

This document provides an overview of the BCA-104 Programming in C course. It discusses the basics of the C language, including its history and importance. It outlines the structure of a C program and covers topics like data types, variables, constants, input/output functions, and keywords. The character set and rules for identifiers in C are also defined. Data types like integer, floating point, and character are described along with their sizes and ranges.

Uploaded by

Farhan Patel
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/ 24

BCA-104 Programming in C

Unit 1 -Basics of C Language [10L] [15M]


Overview of C: History of C, Importance of C, Structure of a C Program.
Elements of C: C character set, identifiers and keywords, Data types, Constants and
Variables, Assignment statement, Symbolic constant.
Input/output: Unformatted & formatted I/O function in C,Input functions viz. scanf(),
getch(), getche(), getchar(), gets(), output functions viz. printf(), putch(), putchar(), puts().

History of C language
C language has evolved from three different structured language ALGOL, BCPL and B
Language. It uses many concepts from these languages while introduced many new concepts
such as datatypes, struct, pointer etc. In 1988, the language was formalised by American
National Standard Institute(ANSI). In 1990, a version of C language was approved by
the International Standard Organisation(ISO) and that version of C is also referred to as
C89.

The idea behind creating C language was to create an easy language which requires a simple compiler
and enables programmers to efficiently interact with the machine/system, just like machine
instructions. C language compiler converts the readable C language program into machine instruction

1 | Page By SwatiPhalak
BCA-104 Programming in C

Importance of ‘C’ language:

C language is a famous programming language due to its qualities.


Some qualities are:
1. It is robust language whose rich setup of built in functions and operator can be used to
write any complex program.
2. Program written in C are efficient due to several variety of data types and powerful
operators.
3. The C compiler combines the capabilities of machine language with the feature of high level
language. Therefore it is called as middle level language. That’s why c language is well
suited for writing both system software and business package.
4. There are only 32 keywords; several standard functions are available which can be used for
developing program.
5. C is portable language; this means that C programs written for one computer system can be
run on another system, with little or no modification.
6. C language is structured programming language, this requires user to think of a problems
in terms of function or modules or block. A collection of these modules make a program
debugging and testing easier.
7. C language has its ability to extend itself. A c program is basically a collection of functions
that are supported by the C library. We can continuously add our own functions to the library
with the availability of the large number of functions.
8. C programming language because it is easy to learn and understand.

Basic Structure of C Program


Any C program is consists of 6 main sections. Below you will find brief explanation of each of them.

2 | Page By SwatiPhalak
BCA-104 Programming in C

Basic Structure of C Program


Documentation Section
This section consists of comment lines which include the name of programmer, the author and other
details like time and date of writing the program. Documentation section helps anyone to get an
overview of the program.
Link Section
The link section consists of the header files of the functions that are used in the program. It provides
instructions to the compiler to link functions from the system library.
Definition Section
All the symbolic constants are written in definition section. Macros are known as symbolic constants.
Global Declaration Section
The global variables that can be used anywhere in the program are declared in global declaration
section. This section also declares the user defined functions.
main() Function Section
It is necessary have one main() function section in every C program. This section contains two parts,
declaration and executable part. The declaration part declares all the variables that are used in
executable part. These two parts must be written in between the opening and closing braces. Each
statement in the declaration and executable part must end with a semicolon (;). The execution of
program starts at opening braces and ends at closing braces.
Subprogram Section
The subprogram section contains all the user defined functions that are used to perform a specific
task. These user defined functions are called in the main() function.

3 | Page By SwatiPhalak
BCA-104 Programming in C
Character set
A character set is a set of alphabets, letters and some special characters that are valid in C
language.
Alphabets

Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z

C accepts both lowercase and uppercase alphabets as variables and functions.


Digits

0123456789

Special Characters

, < > . _

( ) ; $ :

% [ ] # ?

' & { } "

^ ! * / |

- \ ~ +  

White space Characters


Blank space, newline, horizontal tab, carriage, return and form feed.

C Keywords
Keywords are predefined, reserved words used in programming that have special meanings to
the compiler. Keywords are part of the syntax and they cannot be used as an identifier. For
example:
1. int money;

4 | Page By SwatiPhalak
BCA-104 Programming in C
Here, int is a keyword that indicates money is a variable of type int (integer).
As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of
all keywords allowed in ANSI C.

Auto double int struct

Break else long switch

Case enum register typedef

Char extern return union

Continue for signed void

Do if static while

Default goto sizeof volatile

Const float short unsigned

C Identifiers
Identifier refers to name given to entities such as variables, functions, structures etc.
Identifiers must be unique. They are created to give a unique name to an entity to identify it
during the execution of the program. For example:
1. int money;
2. double accountBalance;
Here, money and accountBalance are identifiers.
Also remember, identifier names must be different from keywords. You cannot use int as an
identifier because int is a keyword.
Rules for naming identifiers
1. An Identifier can only have alphanumeric characters (a-z , A-Z , 0-9) and
underscore(_).

5 | Page By SwatiPhalak
BCA-104 Programming in C
2. The first character of an identifier can only contain alphabet(a-z , A-Z) or
underscore (_).
3. Identifiers are also case sensitive in C. For example name and Name are two
different identifiers in C.
4. Keywords are not allowed to be used as Identifiers.
5. No special characters, such as semicolon, period, whitespaces, slash or comma are
permitted to be used in or as Identifier.

Data types in C Language


Data types specify how we enter data into our programs and what type of data we enter.
C language has some predefined set of data types to handle various kinds of data that we can
use in our program. These datatypes have different storage capacities.
C language supports 2 different type of data types:
1. Primary data types:
These are fundamental data types in C namely integer(int), floating
point(float),(double) character(char).
2. Derived data types:
Derived data types are nothing but primary datatypes but a little twisted or grouped
together like array, stucture, union and pointer. These are discussed in details later.
Data type determines the type of data a variable will hold. If a variable x is declared as int. it
means x can hold only integer values. Every variable which is used in the program must be
declared as what data-type it is.

Integer type (int)


Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine:

Type Size(bytes) Range

int or signed int 2 -32,768 to 32767

unsigned int 2 0 to 65535

short int or signed short int 1 -128 to 127

unsigned short int 1 0 to 255

6 | Page By SwatiPhalak
BCA-104 Programming in C

long int or signed long int 4 -2,147,483,648 to 2,147,483,647

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

Floating point type (float, double)


Floating types are used to store real numbers.
Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

Float 4 3.4E-38 to 3.4E+38

Double 8 1.7E-308 to 1.7E+308

long double 10 3.4E-4932 to 1.1E+4932

Character type
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

char or signed char 1 -128 to 127

unsigned char 1 0 to 255

Constants
If you want to define a variable whose value cannot be changed, you can use
the const keyword. This will create a constant. For example,
1. const double PI = 3.14;
Notice, we have added keyword const.
Here, PI is a symbolic constant; its value cannot be changed.
1. const double PI = 3.14;
2. PI = 2.9; //Error

7 | Page By SwatiPhalak
BCA-104 Programming in C
Variables
In programming, a variable is a container (storage area) to hold data.
To indicate the storage area, each variable should be given a unique name (identifier).
Variable names are just the symbolic representation of a memory location. For example:
1. int playerScore = 95;
Here, playerScore is a variable of int type. Here, the variable is assigned an integer value 95.
The value of a variable can be changed, hence the name variable.
1. char ch = 'a';
2. // some code
3. ch = 'l';
Rules for naming a variable
1. A variable name can have only letters (both uppercase and lowercase letters), digits and
underscore.
2. The first letter of a variable should be either a letter or an underscore.
3. The length variable name can be upto 32 character
Note: You should always try to give meaningful names to variables. For
example: firstName is a better variable name than fn.
C is a strongly typed language. This means that the variable type cannot be changed once it
is declared. For example:
1. int number = 5; // integer variable
2. number = 5.5; // error
3. double number; // error
Assignment Statement:
C provides an assignment operator for this purpose, assigning the value to a variable using
assignment operator is known as an assignment statement in C.
The function of this operator is to assign the values or values in variables on right hand side
of an expression to variables on the left hand side.
The syntax of the assignment expression
Variable = constant / variable/ expression;

The data type of the variable on left hand side should match the data type of
constant/variable/expression on right hand side with a few exceptions where automatic type
conversions are possible.
Examples of assignment statements,
8 | Page By SwatiPhalak
BCA-104 Programming in C
b = c ; /* b is assigned the value of c */
a = 9 ; /* a is assigned the value 9*/
b = c+5; /* b is assigned the value of expr c+5 */

Symbolic Constants in C 


Symbolic Constant is a name that substitutes for a sequence of characters or a numeric
constant, a character constant or a string constant.
When program is compiled each occurrence of a symbolic constant is replaced by its
corresponding character sequence.
The syntax of Symbolic Constants in C
#define name text
where name implies symbolic name in caps. text implies value or the text.
For example,
#define printf print
#define MAX 50
#define TRUE 1
#define FALSE 0
#define SIZE 15
The # character is used for preprocessor commands.
A preprocessor is a system program, which comes into action prior to Compiler, and it
replaces the replacement text by the actual text.
Advantages of using Symbolic Constants
They can be used to assign names to values.
Replacement of value has to be done at one place and wherever the name appears in the text
it gets the value by execution of the preprocessor.
This saves time. if the Symbolic Constant appears 20 times in the program; it needs to be
changed at one place only.
Input / Output :

9 | Page By SwatiPhalak
BCA-104 Programming in C

Input / Output
Formatted Unformatted
Input Output Input Output
getch() putch()
getche() putchar(),
scanf() printf()
getchar() puts().
gets()

Format Specifier:
Type Format specifier
Integer %d
Float %f
Char %c
Double %lf
Unsigned %u
Long %l
String %s
Octal %o
Hexadecimal %x
Formatted Input/Output Function:

The printf() and scanf() functions are inbuilt library functions declared and defined in
“stdio.h” header file. printf() is used to display the output and scanf() is used to read the
inputs.
1. printf() Function In C Language:

10 | Page By SwatiPhalak
BCA-104 Programming in C
The printf() function is used for output. It prints the given statement to the console.

Syntax: printf("format string",argument_list);

Format String is the formatted string or string with format specifier.


In C programming language, printf() function is used to print the “character, string, float,
integer, octal and hexadecimal values” onto the output screen.
Use ‘\n’ to generate a newline in printf() statement
The printf("cube of number is:%d ",number*number*number) statement prints the cube
of number on the console.
2. scanf() Function In C Language:
The scanf() function is used for input. It reads the input data from the keyboard or console.
Syntax: scanf("format string",argument_list);
The scanf("%d",&number) statement reads integer number from the console and stores the
given value in number variable.
e.g.
#include<stdio.h>    
void main()
{    
int x=0,y=0,result=0;  
  
printf("enter first number:");  
scanf("%d",&x);  
printf("enter second number:");  
scanf("%d",&y);  
  
result=x+y;  
printf("sum of 2 numbers:%d ",result);  
}    

Unformatted Input/Output Function:


In Unformatted input/output functions, we do not have to use any format specifiers in
them, to read or display a value. Following functions are defined in “conio.h”

11 | Page By SwatiPhalak
BCA-104 Programming in C
getch() Function:
The getch() function reads the alphanumeric character input from the user. But, that the
entered character will not be displayed.

getch.c

#include <stdio.h> //header file section


#include <conio.h>
void main()
{
printf("\nHello, press any alphanumeric character to exit ");
getch();
}

Output:
Hello, press any alphanumeric character to exit

getche() Function
getche() function reads the alphanumeric character from the user input. Here, character you
entered will be echoed to the user until he/she presses any key.
getche() C Program
getche.c

#include <stdio.h> //header file section


#include <conio.h>
void main()
{
printf("\nHello, press any alphanumeric character or symbol to exit \n ");
getche();
}

Output:
Hello, press any alphanumeric character to exit
K

getchar() Function

12 | Page By SwatiPhalak
BCA-104 Programming in C
The getchar() function reads character type data form the input. The getchar() function reads
one character at a time till the user presses the enter key.
getchar() C Program
getchar.c

#include <stdio.h>
void main()
{
char c;
printf("Enter a character : ");
c = getchar();
printf("\nEntered character : %c ", c);
}

Output:
Enter a character : x
Entered character : x

gets() Function
The gets() function can read a full string even blank spaces presents in a string. But, the
scanf() function leave a string after blank space space is detected. The gets() function is used
to get any string from the user.
gets() C Program
gets.c

#include <stdio.h> //header file section


#include <conio.h>
void main()
{
char c[25];
printf("Enter a string : ");
gets(c);
printf("\n%s is awesome ",c);
}

Output:

13 | Page By SwatiPhalak
BCA-104 Programming in C
Enter String : C Language
C Language is awesome
putch() Function
The putch() function prints any alphanumeric character.
putch() C Program
putch.c

#include <stdio.h> //header file section


#include <conio.h>
void main()
{
char c;
printf("Press any key to continue\n ");
c = getch();
printf("Input : ");
putch(c);
}

Output:
Press any key to continue
Input : d
putchar() Function
putchar() function prints only one character at a time.
putchar() C Program
putchar.c

#include <stdio.h> //header file section


#include <conio.h>
void main()
{
char c = 'K';
putchar(c);
}

14 | Page By SwatiPhalak
BCA-104 Programming in C
K
Note:
Here, variable c is assigned to a character 'K'. The variable c is displayed by the putchar().
Use Single quotation mark ' ' for a character.

Unit 2 -Control Flow and Logical Expressions [10L] [15M]


Operators & Expression: Arithmetic, relational, logical, bitwise, unary, assignment,
conditional operators and special operators, operator hierarchy & associativity
Decision making & branching: Decision making with IF statement, IF-ELSE statement,
Nested IF statement, ELSE-IF ladder, switch statement, goto statement.
Loops control structure: while loop, for loop, do–while loop, nested loop, break , continue,
switch, go to, exit statement
==================================================================
Operators in C Language
C language supports a rich set of built-in operators. An operator is a symbol that tells the
compiler to perform a certain mathematical or logical manipulation. Operators are used in
programs to manipulate data and variables.
C operators can be classified into following types:
1. Arithmetic operators
2. Increment decrement operator
3. Relational operators
4. Logical operators
5. Assignment operators
6. Conditional operators
7. Bitwise operator
8. Special operators
1. Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic
arithmetic operators.

Operator Description

+ adds two operands

- subtract second operands from first

15 | Page By SwatiPhalak
BCA-104 Programming in C

* multiply two operand

/ divide numerator by denominator

% remainder of division

2. Increment/decrement operator

++ Increment operator - increases integer value by one

-- Decrement operator - decreases integer value by one


3. Relational operators
The following table shows all relation operators supported by C.

Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

4. Logical operators
C language supports following 3 logical operators. Suppose a = 1 and b = 0,

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false

5. Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also
perform shifting of bits from right to left. Bitwise operators are not applied to float or double
(These are datatypes, we will learn about them in the next tutorial).

Operator Description

16 | Page By SwatiPhalak
BCA-104 Programming in C

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

Now lets see truth table for bitwise &, | and ^

a b a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

The bitwise shift operator, shifts the bit value. The left operand specifies the value to be
shifted and the right operand specifies the number of positions that the bits in the value have
to be shifted. Both operands have the same precedence.

Example : 1
a=8 and b=3

a= 0 0 0 1 0 0 0

a<<b 1 0 0 0 0 0 0

Shift 3 bits left side Add 3 zeroes to right side


Example : 2

17 | Page By SwatiPhalak
BCA-104 Programming in C
a=11 and b=2

a= 0 0 0 1 0 1 1 Truncate 2 bits from right side

a>>b 0 0 0 0 0 1 0

Add 2 zeros to left Shift 2 bits right side

6. Assignment Operators

Operator Description Example

= assigns values from right side operands to left side operand a=b

+= adds right operand to the left operand and assign the result to a+=b is same as
left a=a+b

-= subtracts right operand from the left operand and assign the a-=b is same as
result to left operand a=a-b

*= mutiply left operand with the right operand and assign the a*=b is same as
result to left operand a=a*b

/= divides left operand with the right operand and assign the a/=b is same as
result to left operand a=a/b

%= calculate modulus using two operands and assign the result to a%=b is same as
left operand a=a%b

7. Conditional operator
The conditional operators in C language are known by two more names
1. Ternary Operator
2. ? : Operator
It is actually the if condition that we use in C language decision making, but using
conditional operator, we turn the ifcondition statement into a short and simple operator.

18 | Page By SwatiPhalak
BCA-104 Programming in C

The syntax of a conditional operator is :

expression 1 ? expression 2: expression 3

Explanation:
● The question mark "?" in the syntax represents the if part.
● The first expression (expression 1) generally returns either true or false, based on
which it is decided whether (expression 2) will be executed or (expression 3)
● If (expression 1) returns true then the expression on the left side of " : " i.e
(expression 2) is executed.
● If (expression 1) returns false then the expression on the right side of " : " i.e
(expression 3) is executed.

8. Special operator:

Operator Description Example

Sizeof Returns the size of an variable sizeof(x) return size of the variable x

& Returns the address of an variable &x ; return address of the variable x

* Pointer to a variable *x ; will be pointer to a variable x

Precedence of operators
If more than one operators are involved in an expression, C language has a predefined rule of
priority for the operators. This rule of priority of operators is called operator precedence.

In C, precedence of arithmetic operators( *, %, /, +, -) is higher than relational operators(==,


!=, >, <, >=, <=) and precedence of relational operator is higher than logical operators(&&, ||
and !).

Example of precedence

19 | Page By SwatiPhalak
BCA-104 Programming in C

(1 > 2 + 3 && 4)

This expression is equivalent to:

((1 > (2 + 3)) && 4)

i.e, (2 + 3) executes first resulting into 5

then, first part of the expression (1 > 5) executes resulting into 0 (false)

then, (0 && 4) executes resulting into 0 (false)

Output is 0
Associativity of operators

If two operators of same precedence (priority) is present in an expression, Associativity of


operators indicate the order in which they execute.

Example of associativity

1 == 2 != 3

Here, operators == and != have same precedence. The associativity of both ==and != is left to


right, i.e, the expression on the left is executed first and moves towards the right.

Thus, the expression above is equivalent to :

((1 == 2) != 3)

i.e, (1 == 2) executes first resulting into 0 (false)

then, (0 != 3) executes resulting into 1 (true)

Output is 1

The table below shows all the operators in C with precedence and associativity.

Note: Precedence of operators decreases from top to bottom in the given table.

20 | Page By SwatiPhalak
BCA-104 Programming in C

Associativit
Operator Meaning of operator y

() Functional call
[] Array element reference
-> Indirect member selection
. Direct member selection Left to right

Logical negation
! Bitwise(1 's) complement
~ Unary plus
+ Unary minus
- Increment
++ Decrement
-- Dereference
& Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion) Right to left

* Multiply
/ Divide
% Remainder Left to right

+ Binary plus(Addition)
- Binary minus(subtraction) Left to right

<< Left shift


>> Right shift Left to right

< Less than


<= Less than or equal
> Greater than
>= Greater than or equal Left to right

== Equal to
!= Not equal to Left to right

& Bitwise AND Left to right

^ Bitwise exclusive OR Left to right

| Bitwise OR Left to right

&& Logical AND Left to right

|| Logical OR Left to right

?: Conditional Operator Right to left

21 | Page By SwatiPhalak
BCA-104 Programming in C

Simple assignment
= Assign product
*= Assign quotient
/= Assign remainder
%= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift Right to left

, Separator of expressions

Summary of C operators with precedence and associativity

Decision making & branching:

Printf function
When the c program needs to communicate with the user, We should use printf
function.

The communication can be,

Greeting the user


"welcome to c program"
Asking input from the user
"Enter your username/password" etc.
Note
printf function is defined in stdio.h header file.

22 | Page By SwatiPhalak
BCA-104 Programming in C
So if we want to use the printf function in our c program, we should
include stdio.h header file.

Syntax of printf

printf("");

It will print characters to the screen which is given inside the double quotes "" .
And it should end up with a semicolon ;.

Example

printf("Hello World");

printf("Enter two numbers");

printf("Bye");

Sample Program
Example

#include<stdio.h> //header section

int main() //main section


{
printf("Welcome to the C Programming");

return 0;
}

23 | Page By SwatiPhalak
BCA-104 Programming in C

Run it

Correct the below program


The below program has some syntax errors.
Correct the program by yourself and see the output.

Example

#include<stdio.h>

int main()
{
printf("Correct me!)

return 0;
}

Run it

24 | Page By SwatiPhalak

You might also like