Unit-1 Basics of C' Programming
Unit-1 Basics of C' Programming
In 1972, Dennis Ritchie developed C language, combining the features of B and BCPL
language at bell laboratories.
2.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. Anything written as comments will be treated as documentation of the program
and this will not interfere with the given code.
Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.
Single line comments //: used when there is a single line to comment
Multiline comments /* */: used when there is multiple lines to comment.
Pre-processor directives start with the ‘#’ symbol. The #define pre-processor 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.
This section contains all Symbolic constants
Example
# define PI 3.14
#define long long ll
2.4 Global declaration section
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;
int a;
main ()
{
}
2.5 main () function
Each and every C program should have only one main () function.
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.
The execution of C program begins at this function.
The main() section is divided into two portions
i) Declaration part: It describes the data that will be used in the function. Data
declared within the function are known as local declaration.
ii) Executable part: contains s set of statements executed by the computer.
Example:
Types Description
Primitive Data Arithmetic types can be further classified into integer and floating data
Types types.
Void Types The data type has no value or operator and it does not provide a result to
Types Description
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.
unsigne 4 0 to 4,294,967,295 %u
int 4 -2,147,483,648 to %d
unsigne 8 0 to %llu
unsigne 1 0 to 255 %c
1. Integer Types
The integer data type in C is used to store the whole numbers without decimal
values. Octal values, hexadecimal values, and decimal values can be stored in int
data type in C.
Unsigned int data type in C is used to store the data values from zero to positive
numbers but it can’t store negative values like signed int. Unsigned int is larger in
size than signed int and it uses “%u” as a format specifier in C programming
language.
Range: -2,147,483,648 to 2,147,483,647
Size: 2 bytes or 4 bytes
Format Specifier: %d
Example 1:
// C program to print Integer data types.
#include <stdio.h>
int main()
{
// Integer value with positive data.
int a = 9;
Output
Integer value with positive data: 9
Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998
2. Character Types
Character data type allows its variable to store only a single character. The storage
size of the character is 1. It is the most basic data type in C. It stores a single character
and requires a single byte of memory in almost all compilers.
Example 3:
// C Program to demonstrate use of Floating types
#include <stdio.h>
int main()
{
float a = 9.0f;
float b = 2.5f;
// 2x10^-4
float c = 2E-4f;
printf("%f\n",a);
printf("%f\n",b);
printf("%f",c);
return 0;
}
Output
9.000000
2.500000
0.000200
4. Double Types
A Double data type in C is used to store decimal numbers (numbers with floating
point values) with double precision. It is used to define numeric values which hold numbers
with decimal values in C. Double data type is basically a precision sort of data type that is
capable of holding 64 bits of decimal numbers or floating points.
Range: 1.7E-308 to 1.7E+308
Size: 8 bytes
Format Specifier: %lf
Example 4:
// C Program to demonstrate use of double data type
#include <stdio.h>
int main()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;
printf("%lf\n", a);
printf("%lf\n", b);
printf("%lf", c);
return 0;
}
Output
123123123.000000
12.293123
2312312312.123123
4. KEYWORDS
Keywords are predefined or reserved words that have special meanings to the compiler.
These are part of the syntax and cannot be used as identifiers in the program.
Keywords are reserved words whose meaning has already explained to the compiler.
C is a case sensitive language, all keywords must be written in lowercase.
Keywords are part of the syntax and they cannot be used as an identifier.
There are 32 reserved keyword.
A list of keywords in C or reserved words in the C programming language are mentioned
below:
Eg int marks;
int is a keyword
mark is a variable
5. VARIABLES
A variable in C is a memory location with some name that helps store some form
of data and retrieves it when required.
Can store different types of data in the variable and reuse the same variable for
storing some other data any number of times.
You can assign any name to the variable as long as it follows the following rules:
Example:
5.2 Types of Variables in C
The C variables can be classified into the following types:
Local Variables
Global Variables
Static Variables
Automatic Variables
Extern Variables
#include <stdio.h>
void function()
{
int x = 10; // local variable
printf("%d", x);
}
int main()
{
function();
}
Output
10
Example
#include "myfile.h"
#include <stdio.h>
void printValue()
{
printf("Global variable: %d", x);
}
5.3.6. Register Variables in C
Register variables in C are those variables that are stored in the CPU register
instead of the conventional storage place like RAM.
Their scope is local and exists till the end of the block or a function.
These variables are declared using the register keyword.
The default value of register variables is a garbage value.
6. OPERATORS in C
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=50,b=10,c;
clrscr();
c=a+b;
printf("The sum:%d",c);
getch();
}
Output:
The sum is 60
6.2.2 Relational Operators
A relational operator checks the relationship between two operands. If the relation is
true, it returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Operator Meaning Example value
> Greater than 2>3 0
< Less than 2<3 1
>= Greater than or equal to 2 >= 3 0
<= Less than or equal to 2 <= 3 1
== Equal to 2 == 3 0
!= Not equal 2!=3 1
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=50,b=10;
clrscr();
printf("%d", a>b);
getch();
}
Output:
1
6.2.3 Logical Operators
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=9,c;
clrscr();
c=(a<b)||(a>b);
printf("c is %d",c);
getch();
}
Output:
c is 1
6.2.4 Assignment Operators
= a=5 a=5
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=10;
clrscr();
sum=sum+10;
printf("The sum:%d",sum);
getch();
}
Output:
a = 10;
b = 20;
ch = 'y';
b) “+=”
This operator is the combination of the ‘+’ and ‘=’ operators. This operator first adds
the current value of the variable on left to the value on the right and then assigns the result
to the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5.
Then (a += 6) = 11.
c) “-=”
This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts
the value on the right from the current value of the variable on left and then assigns the
result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8.
Then (a -= 6) = 2.
d) “*=”
This operator is a combination of the ‘*’ and ‘=’ operators. This operator first multiplies the
current value of the variable on left to the value on the right and then assigns the result to
the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5.
Then (a *= 6) = 30.
e) “/=”
This operator is a combination of the ‘/’ and ‘=’ operators. This operator first divides the
current value of the variable on left by the value on the right and then assigns the result to
the variable on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
Other Operators
Apart from the above operators, there are some other operators available in C used
to perform some specific tasks.
Some of them are discussed here:
6.2.1 sizeof operator
sizeof is much used in the C programming language.
It is a compile-time unary operator which can be used to compute the size of its
operand.
Basically, the sizeof the operator is used to compute the size of the variable.
6.2.3 Comma Operator
The comma operator (represented by the token) is a binary operator that
evaluates its first operand and discards the result, it then evaluates the
second operand and returns this value (and type).
The comma operator has the lowest precedence of any C operator.
Comma acts as both operator and separator.
6.2.4 Conditional Operator
The conditional operator is of the form Expression1? Expression2: Expression3
Here, Expression1 is the condition to be evaluated.
If the condition(Expression1) is True then we will execute and return the result of
Expression2 otherwise if the condition(Expression1) is false then we will execute and return
the result of Expression3.
We may replace the use of if..else statements with conditional operators.
To know more about the topic refer to this article.
6.2.5 dot (.) and arrow (->) Operators
Member operators are used to referencing individual members of classes, structures,
and unions.
The dot operator is applied to the actual object.
The arrow operator is used with a pointer to an object.
6.2.6 Cast Operator
Casting operators convert one data type to another.
For example, int(2.2000) would return 2.
A cast is a special operator that forces one data type to be converted into
another.
6.2.7 &,* Operator
Pointer operator & returns the address of a variable. For example &a; will give the
actual address of the variable.
The pointer operator * is a pointer to a variable. For example *var; will pointer to a variable
var.
6.2.6 Increment and Decrement Operators
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1.
These two operators are unary operators, meaning they only operate on a single
operand.
Operator Meaning
++a Pre increment
--a Pre decrement
a++ Post increment
a-- Post decrement
Prefix
The operator precedes the operand (e.g., ++a). The value of operand will be altered
before it is used.
Postfix
The operator follows the operand. he value operand will be altered after it is used.
Program
#include <stdio.h>
#include<conio.h>
void main()
{
int c=2;
clrscr();
printf("c=%d\n",c++); //this statement displays 2 then,only incremented by 1to 3.
printf("c=%d",c); //this statement increments 1 to c then,only c is displayed.
getch();
}
Output:
C=2
C=3
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=2,c;
clrscr();
c=a>b?a:b;
printf("The value of c is %d",c);
getch();
}
Output
The value of c is 10
6.2.7 Bitwise Operators
These operators are used to manipulate data at bit level. It operates on integers only.
A b a^b
0 0 1
0 1 0
1 0 0
1 1 0
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=2,c;
clrscr();
c=a>b;
printf("The value of c is%d",c);
getch();
}
Ouput:
The value of c is 1
E.g. 12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)
7<< 2 (Shift Left)
0011 1100=12
3 >> 1 (Shift Right)
11 1=1
6.2.8 Special Operators
Operator Meaning
, Comma operators are used to link
related expressions together
& Address of operator
* Pointer to a variable
Sizeof () Returns length of variable in bytes
Program
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
}
Output:
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
Expression is a sequence of operands and operators that specifies the computation of the
value.
Example: a=2+3
2, 3 operands
+ = operator
Simple Expression:
If it has only one operator then it is called simple expression.
Example a=2+3
Compound Expression:
If it has more than one operator then it is called Compound expression
Example: A=2+3*5\4
scanf ()
The function scanf () stands for scan formatting.
It is used to read formatted data from the keyword.
It ignores any blank spaces, tabs, new lines entered by the user.
Syntax:
scanf(“control string”,&var1,&var2….,&varn);
Example:
int age;
scanf(“%d”,age);
control string specifies type and format of the data that has to be obtained from
the keyboard and stored in the memory location of the variable.& is a unary
operator, stores the value in the address of a variable
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf("Enter the number");
scanf("%d",&num);
printf("The number is %d",num);
getch();
}
Output:
Enter the number 45
The number is 45
Example
char ch;
a=getchar();
putchar(a);
Progrm
#include<stdio.h>
#include<conio.h>
void main()
{
char a;
clrscr();
printf("Enter the charcter\n");
a=getchar();
putchar(a);
}
Output:
Enter the Character
a
a
Example:
gets(a);
puts(a);
Program
#include<stdio.h>
#include<conio.h>
void main()
{
char a[10];
clrscr();
printf("Enter the string\n");
gets(a);
puts("The string is");
puts(a);
getch();
}
Output:
Enter the string
C programming
The string is
C programming
c) getch() and putch()
getch(): getch() is used to get a character from keyboard but does not echo to the output
screen.
putch(): putch() is used to writes a character directly on the output screen.
Syntax:
char variablename=getch();
putch(variablename);
Example:
char ch;
ch= getchar();
putch(ch);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter the character \n");
ch= getchar();
printf("\nEntered charcter is\n");
putch(ch);
getch();
}
Output:
Enter the character
A
Entered character is
A
c) getche(): getche() reads a single character from the keyboard and echoes it to the output
screen
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter the string");
ch= getche();
printf("Input char %c",ch);
getch();
}
Output:
Enter the string t
Input char t.
The order in which program statements are executed is known as flow of control.
By default program control flows sequentially from top to bottom.
C supports two types of decision control statements that can alter the flow of a sequence
of instruction.
i)Conditional branching
ii) Unconditional branching
8.1 Conditional branching
The conditional branching statements help to jump from one part of the program to another
depending on a whether a particular condition is satisfied or not.
These decision control statements include
i) if statement
ii) if else statements
iii) if else if statement
iv) nested if else
v) switch
8.1.1 if statement
It is a simple decision making statement. It executes only true condition statements.
It checks for the condition .If the condition is true, if block statements are executed.
Syntax
if (condition)
{
statements;
}
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("Enter the number");
scanf("%d",&a);
if(a>=0)
{
printf("%d is a positive number ",a);
}
}
Output:
Enter the number
12
12 is a positive number
8.1.2 if..else statement
It is also called as two way decision statement
If the condition is true, if block statements are executed and else block is skipped.
If the condition is false, else block is executed and if block is skipped.
Syntax
if(condition)
{
Statements;
}
else
{
Statements;
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter the number");
scanf("%d",&a);
if(a>=0)
{
printf("\n %d is a positive number ");
}
else
{
printf("\n %d is a negative number");
}
getch();
}
Output:
Enter the number
-12
12 is a negative number
8.1.3 if else if statement
It is known as multiway decision making statement.
Each and every else block have if statement except last else block.
Syntax
if( condition)
{
Statements;
}
else if(condition)
{
Statements;
}
else if(condition)
{
Stateemnts;
}
else
{
Statements;
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
printf("Enter any number");
scanf("%d",&num);
if(num==0)
{
printf("The numeber is zero");
}
else if(num>0)
{
printf("The number is positive");
}
else
{
printf("The numeber is negative");
}
}
Output:
Enter any number -2
The number is negative
8.1.4 Nested if..else
An if statement or if..else statement in another if..else statement is called as Nesting
and the statement is called nested if..else statements.
syntax
if(condition1)
{
if(condition2)
{
true Statement of condition2;
}
else
{
False Statement of condition 2;
}
}
else
{
False Statement of condition 1;
}
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20,c=40;
if((a>b)&&(a>c))
{
printf("%d is greatest",a);
}
else
{
if(b>c)
{
printf("%d is greatest",b);
}
else
{
printf("%d is greatest",c);
}
}
}
Output:
40 is greatest
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
switch(i)
{
case 1:
printf("One”);
break;
case 2:
printf("Two”);
break;
default:
printf(“Above Three”);
}
getch();
}
Output:
One
9. LOOPING STATEMENTS
Iteration is a process of repeating the same set of statements again and again until
specified condition becomes false
There are 3 types
i) for
ii) while
iii) do-while
Loops are classified as
Counter controlled loops
Sentinel controlled loops
Counter controlled loops
The number of iterations is known in advance. They use a control variable called loop
counter.
Also called as definite repetitions loop.
E.g: for
Sentinel controlled loops
The number of iterations is not known in advance. The execution or termination of the
loop depends upon a special value called sentinel value.
Also called as indefinite repetitions loop.
E.g: while
Syntax:
Initialization section: It is used to initialize the staring value of the loop counter
Condition: The expression is evaluated.
1.if it evaluates true, body of the loop is executed
2. if it evaluates false, program control is transferred to statements
present next to the for loop
Increment/decrement: After the execution of body of the loop, increment and decrement of
loop counter is performed.
Execution of for loop
1. Initialization section is executed only once.
2. Condition is evaluated
a. If it is true, loop body is executed.
b. If it is false, loop is terminated
3. After the execution of loop, the manipulation expression is evaluated.
4. Steps 2 & 3 are repeated until step 2 condition becomes false.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("The numbers are");
for(i=1;i<=4;i++)
{
printf("\n%d",i);
}
getch();
}
Output:
The numbers are
1
2
3
4
They are also known as Entry controlled loops because here the condition is
checked before the execution of loop body.
The condition is checked first, if it is true it executes the body of the loop until the
condition becomes false.
The number of iteration need not be known in advance
Syntax
while(condition)
{
Statements;
}
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("The numbers are");
i=1;
while(i<4)
{
printf("\n%d",i);
i++;
}
getch();
}
Output:
The numbers are
1
2
3
They are also known as Exit controlled loops because here the condition is checked after
the execution of loop body.
The body of the loop is executed first and test condition is checked at the end of the
loop.
The body of the loop is executed atleast once even if the condition is false.
Number of iteration need not be known in advance
Syntax
do
{
Statements
}while(condition);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("The numbers are");
i=1;
do
{
printf("\n%d",i);
i++;
} while(i<4);
getch();
}
Output:
The numbers are
1
2
3
Example
int a[4]={20,45,67,89};
Sample program1:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4]={20,45,67,89};
printf(“%d \t%d\t%d\t%d”,a[0],a[1],a[2],a[3]);
getch();
}
Output:
20 45 67 89
Sample program2:
The efficient way of accessing array elements is using loop
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4]={20,45,67,89};
int i;
for(i=0;i<4;i++)
{
printf(“%d\t”,a[i]);
}
getch();
}
Output:
20 45 67 89
Note:
By default the elements of an array are not initialized. They may contain some garbage
value, so before using array we must initialize the array or read some meaningful data into it.
10.4.1.2 Run time initialization:
The value of an Array can be initialized during run time.
int a[4];
for(i=0;i<4;i++)
{
scanf(“%d”,&a[i]);
}
Sample program 3
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4],i;
printf(“Enter the Elements\n”);
for(i=0;i<4;i++)
{
scanf(“%d\t”,&a[i]);
}
Printf(“The Elements are\n”);
for(i=0;i<4;i++)
{
printf(“%d\t”,a[i]);
}
getch();
}
Output:
Enter the Elements
20 45 67 89
The Elements are
20 5 67 89
10.5 Two dimensional array
It is a collection of data elements of same data type arranged in rows and columns.
It is collection of one dimensional array.
An array with two subscript is called two dimensional arrays.
It enables us to store multiple rows of elements such as table of values or matrix.
Referring to Array Elements:
To access the elements of a two-dimensional array, we need a pair of indices: first
index selects the row and the second index selects the column.
Syntax:
datatype arrayname[size of row][size of column];
Example: int A[3][2];
Col Col
0 1
Row 0 A[0][0] A[0][1]
Row 1 A[1][0] A[1][1]
Row 2 A[2][1] A[2][2]
Col 0 Col 1
Row 0 10 20
Row 1 30 40
Row 2 50 60
Sample program 4:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[3][2]={{10,20},{30,40},{50,60}};
printf(“%d\t”,a[0][0]);
printf(“%d\n”,a[0][1]);
printf(“%d\t”,a[1][0]);
printf(“%d\n”,a[1][1]);
printf(“%d\t”,a[2][0]);
printf(“%d\n”,a[2][1]);
}
Output:
10 20
30 40
50 60
Sample program 5
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][2]={{10,20},{30,40},{50,60}};
int i,j;
printf("\nThe Matrix");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
{
printf("\t%d",a[i][j]);
}
}
getch();
}
Output:
10 20
30 40
50 60
int a[2][3];
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, &a[i][j]);
}
}
Sample program 5:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][3];
int i,j;
printf(“Enter the elements\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, &a[i][j]);
}
}
}
Output:
Enter the elements
1
2
3
4
The elements are
1 2
2 4
PROGRAM:
#include<stdio.h>
int main()
{
int n,sum=0,m;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
m=n%10;
sum=sum+m;
n=n/10;
}
printf("Sum is=%d",sum);
return 0;
}
Output:
Enter a number:654
Sum is=15
2. Write a C program to count no. of positive numbers, negative numbers and zeros in the
array.
ALGORITHM:
Step 1: Get the 10 values in an array
Step 2: if arr[i]>0
increment the positive count(countp)
else if arr[i]==0
increment the zero count (countz)
else
increment the negative count (countn)
Step 3: stop
PROGRAM:
#include<stdio.h>
#include<stdio.h>
#define N 10
int main()
{
int a[N], i, p = 0, n = 0, z = 0;
return 0;
}
OUTPUT:
Enter 10 numbers : 12
23
-56
0
-34
23
0
0
56
-76
Positive numbers=4
Negative numbers=3
Zero=3
3. Write a C program to find sum of two numbers using functions with arguments and
without return type.
ALGORITHM:
Step 1: Read the values of a and b
Step 2: Call the function sum with arguments a and b
Step 3: 3.1In the function definition
3.2 Compute the addition of x and y and store the result in z
3.3 print the result
Step 4: Function does not return any value
Step 5: stop
PROGRAM:
#include<stdio.h>
void main()
{
int a,b;
//clrscr();
printf("Enter Two Number : ");
scanf("%d%d",&a,&b);
sum(a,b);
getch();
}
sum(int x,int y)
{
int z;
z=x+y;
printf("Sum of Two Number is : %d",z);
}
Output :
Enter Two Number : 10 20
Sum of Two Number is : 30