Notes
Notes
Arithmetic +,-,*,/,%
Relational <,>,<=,>=,==,!=
Logical &&,||,!
Bitwise &,|,^,<<,>>
Assignment =
Shorthand assignment +=, -=,*=,/=,
%=
Ternary ? :
DECISION STATEMENTS
It checks the given condition and then executes its sub-block. The decision statement decides the
statement to be executed after the success or failure of a given condition.
Decision making is about deciding the order of execution of statements based on certain conditions
or repeat a group of statements until certain specified conditions are met. C language handles
decision-making by supporting the following statements,
if statement
switch statement
goto statement
The if statement may be implemented in different forms depending on the complexity of conditions
to be tested. The different forms are,
1. Simple if statement
2. if....else statement
Simple if statement
The general form of a simple if statement is,
if(expression)
statement inside;
statement outside;
If the expression returns true, then the statement-inside will be executed, otherwise statement-
inside is skipped and only the statement-outside is executed.
Example:
if...else statement
The general form of a simple if...else statement is,
if(expression)
#include <stdio.h>
{
statement block1;
void
} main( )
{else
{ int x, y;
xstatement
= 15; block2;
} y = 13;
if (x > y )
x is greater than y
void main( )
int x, y; x =
15;
y = 18;
if (x > y )
else
y is greater than x
if( expression )
if( expression1 )
statement block1;
else
{
statement block2;
else
statement block3;
}
if expression is false then statement-block3 will be executed, otherwise the execution continues
and enters inside the first if to perform the check for the next if block, where if expression 1 is true
the statement-block1 is executed otherwise statement-block2 is executed.
Example:
#include <stdio.h>
void main( )
int a, b, c;
printf("Enter 3 numbers...");
if(a > b)
if(a > c)
else
}
else
if(b > c)
else
else if ladder
The general form of else-if ladder is,
if(expression1)
statement block1;
else if(expression2)
statement block2;
else if(expression3 )
statement block3;
else
default statement;
The expression is tested from the top(of the ladder) downwards. As soon as a true condition is
found, the statement associated with it is executed.
Example :
#include <stdio.h>
void main( )
int a;
printf("Enter a number...");
scanf("%d", &a);
else if(a%8 == 0)
printf("Divisible by 8");
else if(a%5 == 0)
printf("Divisible by 5");
else
printf("Divisible by none");
}
2. Explain the looping statement in c with example programs.
LOOP CONTROL STATEMENTS
Loop is a block of statements which are repeatedly executed for certain number of times. Types
1. For loop
2. Nested for loops
3. While loop
4. do while loop
While Loop
A while loop is the most straightforward looping structure. The basic format of while loop is as
follows:
while (condition) {
statements;
}
It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body of the
loop. If a condition is true then and only then the body of a loop is executed. After the body of a
loop is executed then control again goes back at the beginning, and the condition is checked if it is
true, the same process is executed until the condition becomes false. Once the condition becomes
false, the control goes out of the loop.
After exiting the loop, the control goes to the statements which are immediately after the loop. The
body of a loop can contain more than one statement. If it contains only one statement, then the curly
braces are not compulsory. It is a good practice though to use the curly braces even we have a single
statement in the body.
In while loop, if the condition is not true, then the body of a loop will not be executed, not even
once. It is different in do while loop which we will see shortly.
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; //incrementing operation
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
The above program illustrates the use of while loop. In the above program, we have printed series
of numbers from 1 to 10 using a while loop.
1. We have initialized a variable called num with value 1. We are going to print from 1 to 10
hence the variable is initialized with value 1. If you want to print from 0, then assign the
value 0 during initialization.
2. In a while loop, we have provided a condition (num<=10), which means the loop will
execute the body until the value of num becomes 10. After that, the loop will be terminated,
and control will fall outside the loop.
3. In the body of a loop, we have a print function to print our number and an increment
operation to increment the value per execution of a loop. An initial value of num is 1, after
the execution, it will become 2, and during the next execution, it will become 3. This
process will continue until the value becomes 10 and then it will print the series on console
and terminate the loop.
\n is used for formatting purposes which means the value will be printed on a new line.
Do-While loop
A do-while loop is similar to the while loop except that the condition is always executed after the
body of a loop. It is also called an exit-controlled loop.
The basic format of while loop is as follows:
do {
statements
} while (expression);
As we saw in a while loop, the body is executed if and only if the condition is true. In some cases,
we have to execute a body of the loop at least once even if the condition is false. This type of
operation can be achieved by using a do-while loop.
In the do-while loop, the body of a loop is always executed at least once. After the body is executed,
then it checks the condition. If the condition is true, then it will again execute the body of a loop
otherwise control is transferred out of the loop.
Similar to the while loop, once the control goes out of the loop the statements which are
immediately after the loop is executed.
The critical difference between the while and do-while loop is that in while loop the while is written
at the beginning. In do-while loop, the while condition is written at the end and terminates with a
semi-colon (;)
The following program illustrates the working of a do-while loop:
We are going to print a table of number 2 using do while loop.
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=10);
return 0;
}
Output:
2
4
6
8
10
12
14
16
18
20
In the above example, we have printed multiplication table of 2 using a do-while loop. Let's see
how the program was able to print the series.
1. First, we have initialized a variable 'num' with value 1. Then we have written a do-while
loop.
2. In a loop, we have a print function that will print the series by multiplying the value of num
with 2.
3. After each increment, the value of num will increase by 1, and it will be printed on the
screen.
4. Initially, the value of num is 1. In a body of a loop, the print function will be executed in this
way: 2*num where num=1, then 2*1=2 hence the value two will be printed. This will go on
until the value of num becomes 10. After that loop will be terminated and a statement which
is immediately after the loop will be executed. In this case return 0.
For loop
A for loop is a more efficient loop structure in 'C' programming. The general structure of for loop is
as follows:
for (initial value; condition; incrementation or decrementation )
{
statements;
}
The initial value of the for loop is performed only once.
The condition is a Boolean expression that tests and compares the counter to a fixed value
after each iteration, stopping the for loop when false is returned.
The incrementation/decrementation increases (or decreases) the counter by a set value.
2x0=0
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
The nesting of for loops can be done up-to any level. The nested loops should be adequately
indented to make code readable. In some versions of 'C,' the nesting is limited up to 15 loops, but
some provide more.
4. Explain operators in C
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:
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Special operators
ARITHMETIC OPERATORS
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic
operators.
Operator Description
% remainder of division
Operator Description
Logical operators
|| Logical OR (a || b) is true
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
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
Assignment Operators
Assignment operators supported by C language are as follows.
Conditional operator
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 if condition statement into a short and simple operator.
The syntax of a conditional operator is :
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.
Special operator
UNIT- II
Define Array
Array is a collection of similar type of values
All values are stored in continuous memory locations
All values share a common name
Linear data structure. The elements are organized in a sequential order.
#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and
100): "); scanf("%d", &r);
printf("Enter the number of columns (between 1 and
100): "); scanf("%d", &c);
printf("\nEnter elements of 1st
matrix:\n"); for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
// adding two
matrices for (i =
0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] +
b[i][j];
}
return 0;
}
1. What is a function?
Function is a set of instructions
Self contained block
Performs a specific task
Used to avoid redundancy of code
2. What is the need for functions?
To reduce the complexity of large programs
To increase the readability
To achieve reusability
To avoid redundancy of code
To save Memory
3. What are the uses of pointer?
Saves Memory Space
Used for dynamic memory allocation
Faster execution
Used to pass array of values to a function as a single argument
4. What is an Address operator & Indirection operator?
Address operator: & -used to assign the address to a pointer variable,
Referencing operator
Indirection operator : *- Dereferencing operator is used to access the value at
the pointer variable
Ex: int a=5;
i nt *p=&a;
printf(“%d”,*(p));
5. Compare actual parameter & formal argument
Actual argument: Specified in the function call statement. Used to supply the
input values to the function either by copy or reference
Formal argument: Specified in the function definition statement. It takes either copy
or address of the actual arguments
The pointer holds the address 2000. This value is added with 1.
The data type size of the constant is added with the address. p=
2000+(2*1)=2002
7. What is a function prototype?
Function prototype is a function declaration statement.
Syntax
return_type function_name( parameters_list)
Example:
void recursion()
}
int main()
recursion();
}
}
1. Explain about pointers and write the use of pointers in arrays with suitable example.
Ans: Pointers in C language is a variable that stores/points the address of another variable. A
Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable might
be belonging to any of the data type such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that ―p‖ is pointer variable and not a normal
variable. #include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p =
&a[0] for (i = 0; i < 5; i++)
{
printf("%
d", *p);
p++;
}
return 0;
}
STRUC
TRES
Structure Union
Every member has its own memory. All members use the same memory.
The keyword used is struct. The keyword used is union.
All members occupy separate memory location, Different interpretations for the same memory
hence different interpretations of the same location are possible. Conservation of memory
memory is
location are not possible. Consumes more space possible
compared to union.
3. Define Structure in C.
C Structure is a collection of different data types which are grouped
together and each element in a C structure is called member.
If you want to access structure members in C, structure variable should be declared.
Many structure variables can be declared for same structure and
memory will be allocated for each separately.
It is a best practice to initialize a structure to null while declaring, if we don‘t
assign any values to structure members.
4. What you meant by structure definition?
A structure type is usually defined near to the start of a file using a
typedef statement. typedef defines and names a new type, allowing its use
throughout the program. typedefs usually occur just after the #define and
#include statements in a file.
Here is an example
structure definition.
typedef struct { char
name[64];
char course[1 28];
int
ag
e;
int year;
} student;
This defines a new type student variables of type student can be declared as
follows. student st_rec;
5. How to Declare members in Structure?
A struct in C programming language is a structured (record) type that
aggregates a fixed set of labeled objects, possibly of different types, into a
single object.
The syntax for a structure definition in C is:
struct tag_name
{
type attribute;
type attribute2;
/* ... */
};
6. What is meant by Union in C?
A union is a special data type available in C that enables you to store
different data types in the same memory location. You can define a union with
many members, but only one member can contain a value at any given time.
Unions provide an efficient way of using the same memory location for multi-
purpose.
7. How to define a union in C.
To define a union, you must use the union statement in very similar
was as you did while defining structure. The union statement defines a new
data type, with more than one member for your program. The format of the
union statement is as follows:
union [union tag]
{
member
definition;
member
definition;
...
member definition;
} [one or more union variables];
1. Write a C program to create mark sheet for students using self referential structure.
#include<stdio.h>
#include<conio.h>
struct mark_sheet{
char name[20];
int marks[10];
int total;
float
average; char
rem[10];
char cl[20];
}students[100];
int main(){
int
a,b,n,flag=1;
char ch;
clrscr();
scanf("%d",&n);
for(a=1;a<=n;++a)
{
clrscr();
scanf("%s", students[a].name);
scanf("%ld", &students[a].rollno);
students[a].total=0;
for(b=1;b<=5;++b){
scanf("%d", &students[a].marks[b]);
students[a].total += students[a].marks[b];
if(students[a].marks[b]<40)
flag=0;
students[a].average = (float)(students[a].total)/5.0;
if((students[a].average>=75)&&(flag==1))
strcpy(students[a].cl,"Distinction");
else
if((students[a].average>=60)&&(flag==1))
strcpy(students[a].cl,"First Class");
else
if((students[a].average>=50)&&(flag==1))
strcpy(students[a].cl,"Second Class");
else
if((students[a].average>=40)&&(flag==1))
strcpy(students[a].cl,"Third Class");
if(flag==1)
strcpy(students[a].rem,"Pass");
else
strcpy(students[a].rem,"Fail");
flag=1;
for(a=1;a<=n;++a)
{ clrscr();
printf("\n\n\t\t\t\tMark Sheet\n");
printf("\n ");
for(b=1;b<=5;b++)
printf("\n\n \n");
ch = getche();
if((ch=="y")||(ch=="Y"))
continue;
return(0);
}
FILE PROCESSING
1. Why files are needed?
When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the
contents of the file using few commands in C.
You can easily move your data from one computer to another without any changes.
2. Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple text
editors. When you open those files, you'll see all the contents within the file as plain text.
You can easily edit or delete the contents. They take minimum effort to maintain, are easily
readable, and provide least security and takes bigger storage space.
Binary files
Binary files are mostly the .bin files in your computer. Instead of storing data in plain text, they store it
in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better security
than text files.
FILE *fptr;
r Open for reading. If the file does not exist, fopen() returns
NULL.
If the file exists, its contents are
w Open for writing.
overwritten. If the file does not exist, it
will be created.
Open for append. i.e, Data is
a If the file does not exists, it will be created.
added to end of file.
r+ Open for both reading and writing. If the file does not exist, fopen() returns
NULL.
If the file exists, its contents are
w+ Open for both reading and writing.
overwritten. If the file does not exist, it
will be created.
a+ Open for both reading and the file does not exists, it will be created.
appending.
6. How to close a file?
The file (both text and binary) should be closed after
reading/writing. Closing a file is performed using library
function fclose().
For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that,
fprint and fscanf expects a pointer to the structure FILE.
Files are not made for just reading the Contents, we can also Perform Some other
operations on the Files those are Explained below As :
1) Read Operation: Meant To Read the information which is Stored into the Files.
2) Write Operation: For inserting some new Contents into a File.
3) Rename or Change the Name of File.
4) Copy the File from one Location to another.
5) Sorting or Arrange the Contents of File.
6) Move or Cut the File from One Place to Another.
7) Delete a File
8) Execute Means to Run Means File Display Output.