SlideShare uma empresa Scribd logo
1 de 38
Start
Read A, B
Sum=A+B
Print Sum
Start
Q) Define algorithm and flowchart?
Ans:An algorithm is a step by step description of how to arrive at a solution. It is finite set of instructions which
when followed in sequence solves a particular task.
Once algorithm is written, it can be implemented in any high level language.
Algorithm to add two numbers
Step 1: Input the first number as A
Step2: Input the second number as B
Step3: Set Sum = A + B
Step4: Print Sum
Step 5: End
Flow chart is a graphical or symbolic representation of an algorithm.
Flow chart to add two numbers and display the sum is as shown in the figure
Q) What is Token and explain?
Ans: Tokens are basic building blocks of C Programming. Each and every smallest individual units in a C
program are known as C tokens.
No Token Type Example
1 Keyword Keywords are reserved words by compiler. while
2 Variables Variables are named locations in memory. sum
3 Constants Constants are assigned to variables 89
4 Special Symbols Used in different declarations in C ( ), {}
5 Operators Used in expressions /,*,+
6. String Sequence of characters “hello”
Q) Difference between while and do-while
Ans: The only difference is
In a do-while loop, test condition is tested after the body of the loop. Hence body of loop is executed atleast
once even if the condition is false. The do-while loop is also called post test or exit controlled loop.
In while loop, test condition is tested before the body of the loop. only if the condition is true, the body of the
loop is executed. The while loop is also called pre test or entry controlled loop.
Q) What is software?
Ans:
Software is a set of programs. A program is a set of instructions arranged in a sequence to guide a computer to
solve a problem.
True
False
Condition
?
Body of loop
StatementX
True
False
Flow chart for while loop
Flow chart for do-while loop
True
False
StatementX
Conditio
n?
Body of loop
Computer software is written by programmers using a programming language. Computer software is divided
into 2 categories
• System software
• Application software
System software allows a user to interact with the computer hardware.and provides a platform for running
application software. System software is responsible for controlling and managing hardware components of a
computer system. Ex: Operating System, Compiler, BIOS, Device Drivers.
Application Software performs specific task with the help of system software. Ex: Word processors, Image
editors, Spread sheets etc..
Q) Write about constants in C
Constants are identifiers whose value do not change during the execution of a program.
Constants can be declared using const keyword or using the preprocessor command define
Ex: const float pi = 3.14; pi is a constant whose value cannot be changed
#define PI 3.14
Types of C constants:
S.n
o
Constant type Example Rules for constructing C constant
1 Integer constants 53762, -478, • Must have atleast one digit
• It must not have a decimal point
2 Real or Floating point
constants
10.45, 0.5e2,14E-2 • Must have atleast one digit
• It must have a decimal point
5 character constants ‘A’ , ‘B’, ‘C’ Single character enclosed in single quotes
6 string constants “ABCD” , “Hai” Sequence of characters enclosed in double
quotes
Q) Write any two header files in C.
Ans:
It is not possible to write our own output functions every time we wanted to communicate with the computer.
So we use header files that have standard functions which can be included in our programs. Header files names
end with ‘dot h’ (.h) extension.
Example of standard header files are :
1. stdio.h : Contains standard Input and output and file operation functions. Some functions defined in
stdio.h are
S.no Function Description
1 printf() Prints the output on the screen
2 scanf() Reads a character, string, numeric data from keyboard.
3 gets() It reads line from keyboard
4 getchar() It reads character from keyboard
5 puts() It writes line to o/p screen
6 putchar() It writes a character to screen
7 fflush() flushes a file
2. conio.h: provide console input/output functions. Some of the functions defined in conio.h are
S.n
o
Function Description
1 clrscr() This function is used to clear the output screen.
2 getch() It reads character from keyboard
3 getche() It reads character from keyboard and echoes to o/p screen
Long Answer Questions
1. Explain data types in C .Explain with examples.
Ans: The data type of a variable determines how much space it occupies in memory. It defines the type of data and
operations that can be performed on the data.
Basic data types and their size in bytes in a 16 bit computer is shown in the table below.
Keyword
used
Size in
bytes
Range Use Example
character data
type
char 1 -128 to 127 To store characters char gender = ‘m’;
Integer data type int 2 -32767 to 32768 To store integers int num=10;
Floating point
data type
float 4 3.4E-38 to
3.4E+38
To store floating
point numbers
float discount = 12.5;
Double data type double 8 1.7E-308 to
1.7E+308
To store big floating
point numbers
double sal = 1234567.12345;
Valuless Void 0 --- ---
There are 4 type modifiers that can be applied to the basic data types. They are:
unsigned, signed, short and long.
All the modifiers (long, short, unsigned and signed) can be applied to integer data type.
Only signed and unsigned can be applied to character data type.
Only long can be applied to double data type.
Detailed list of data types
Keyword used Size in bytes Range Example
char
signed char
1 -128 to 127 signed char status= ‘u’
int
signed int
short int
signed short int
2 -32767 to 32768 short int num = -12;
unsigned int
unsigned short int
2 0 to 65535 unsigned short int num = 12;
long int
signed long int
4 -2147483648 to 2147483647 long int num = -12345678;
unsigned long int 4 0 to 4294967295 unsigned long int=1234567890;
long double 10 3.4E-4932 to 1.1E+4932 long double population = 123456789.1234567
Q) Explain decision making statements in C.
Ans: Many programs require a logical condition to become true for executing a particular statement / group of
statements. These statements are known as decision making statements.
a) If statement: The if statement is used to control the flow of execution of statements. The syntax and flowchart of is
statement is as shown below.
Example:
/* program to give a discount of Rs.500 if the total amount is above 5000*/
#include <stdio.h>
void main()
{
int amount = 6000;
if (amount > 5000)
{
amount = amount-500;
}
printf(“Total amount to be paid = %d”,amount);
}
if-else statement: In if else control statement, group of statements are executed when condition is true. If condition is
false, then else part statements are executed.
output: Total amount to be paid = 5500
Example:
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}
Switch statement:
The switch makes one selection when there are several choices to be made.
The break statement is used inside each case of switch . It causes
immediate exit from the switch statement and continue onto the next
statement outside the switch statement.
When we execute this form of switch statement, first the test
expression is evaluated. the value of expression is compared one –by-
one, with value-1, value--2 …valuen . When a match is found, the
Output:
m and n are not equal
program executes the following that case. The execution continues till a break statement is found or the switch
statement is completed.
If there is no match the statements in the default case gets executed. Syntax of switch is as follows
Switch(test expression)
{
case value-1: statementblock-1; break;
case value-2: statementblock-2; break;
.
.
default: defaultblock;
}
Q) Write a c program to perform all arithmetic operations using switch-case.
#include<stdio.h>
#include<conio.h>
void main()
{
int ch;
float a,b,res;
clrscr();
printf(“Enter two numbers:”);
scanf(“%f%f”,&a,&b);
printf(“nMenun1.Additionn2.Subtractionn3.Multiplicationn4.Division”);
printf(“nEnter your choice:”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: res=a+b;
break;
case 2: res=a-b;
break;
case 3: res=a*b;
break;
case 4: res=a/b;
break;
default: printf(“Wrong choice!!nPress any key…”);
}
printf(“nResult=%f”,res);
getch();
}
Q) Explain hardware components of a computer.
Ans: A computer is made up of many parts:
•Input/Output (I/O) devices – These allow you to send information to the computer or get information from the
computer.
•Central Processing Unit – CPU or Processor for short. The brain of a computer. Does all the
computation/work for the computer.
•Memory –any form of electronic storage is referred to as memory. There are two types of memories.
1. Primary memory
2. Secondary memory
Primary memory
a) RAM holds data and instructions as long as the program is being processed by the processor.
RAM is a volatile memory as data in the RAM is lost when the power is switched off.
The cpu can access any other location in memory directly in random manner and hence it is called random
access memory.
b) ROM: ROM is a non- volatile memory as data in the ROM is not lost when the power is switched off.
ROM can also be accessed randomly.
Secondary memories are used to store large amounts of data. They are inexpensive than primary memories.
They are also non-volatile.
A drive is used to read the contents of a hard disk, CD , DVD or a floppy.
a) hard disk drive (HDD)
Accessing the hard drive for information takes time.
b) CD ROM drive– A device used to read CD-ROMs. CD-RW drive is used to read data/ write data from/to
CD-RW disks.
c) DVD ROM drive – A device that is used to read DVDs. DVD-RW drive is used to read data/ write data
from/to DVD-RW disks.
c) Floppy Drive – A device that is used to read/write to floppy diskettes.
•Motherboard – A circuit board that allows the CPU to interact with other parts of the computer.
•Power Supply – Gives your computer power by converting alternating current (AC) supplied by the wall
connection to direct current (DC).
•Expansion Cards – Used to add/improve functionality to the computer.
a. Sound Card – Used to input and output sound under program control. Sound cards provide better sound
quality than the built in sound control provided with most computers.
b. Graphics Card – Used to convert the logical representation of an image to a signal that can be used as input
for a monitor.
c. Network Card – Used to provide a computer connection over a network. Transmit data at 10/100/1000 Mb/s.
• Fan – Keeps your computer cool. If the inside of your computer becomes too hot, then the computer can
overheat and damage parts.
• Heatsink – Used to disperse the heat that is produced inside the computer by
the CPU and other parts by increasing surface area.
• Ports – Means of connecting peripheral devices to your computer.
Q) Explain different sections of a C program. (or) Explain the structure of C
Ans:
Documentation section
pre-processor directives
global declarations
main()
{
local variables to function main ;
statements associated with function main ;
}
f1()
{
local variables to function 1 ;
statements associated with function 1 ;
}
f2()
{
local variables to function f2 ;
statements associated with function 2 ;
}
Preprocessor Directives: It is not possible to write our own output functions every time we wanted to
communicate with the computer. So we use header files that have standard functions which can be included in
our programs.
All pre-processor directives begin with a # and the must written in the beginning of the c program
#include <stdio.h>
Documentaion section contains a set of comments giving the name of the program, the author and other
details which the programmer would like to use later. Comments are non-executable
 Single Line Comment Starts with ‘//’ . used to comment out just Single Line in the Code written after //.
 Multi line comments starts with /* and ends with */.
Multi line comments comment out multiple lines written between /* and */
main()
All C programs will consist of at least one function. The only function that has to be present is the function
called main. Execution of a C program starts with main().
User Defined Functions
Any number of user defined functions can be written. All functions including main() are divided into 2 parts.
1. declaration section
2. statement section
declaration section is used to describe the data that will be used in the function. The data declared within a
function will be visible only within the function and will be removed from memory once the control goes out of
the function.
statement section contains the code that manipulates the data to perform a specified task.
Global declarations : globally declared variables are accessed through out the program and will be in memory
until the program runs.
Q)Explain different types of operators in C.
Ans:
S.no Types of Operators Description
1 Arithmetic operators These are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus
2 Assignment operators
(=)
These are used to assign values to variables.
3 Relational operators These are used to compare the values of two variables
4 Logical operators These operators are used to perform logical operations on expression.
5 Bit wise operators These operators are used to perform bit operations on variables.
6 Conditional (ternary)
operators
Conditional operators return one value if condition is true and returns
another value if condition is false.
7 Increment/decrement
operators
These operators are used to either increase or decrease the value of the
variable by one.
8 Special operators &, *, sizeof( )
Arithmetic Operators in C:
S.no Arithmetic Operators Operation Example
1 + Addition A+B
2 - Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
Assignment operators in C:
Operators Example Explanation
Simple assignment operator = sum = 10 10 is assigned to variable sum
Compound assignment operators
(+=, *=, /=, %=, etc..
+= sum +=
10
This is same as sum = sum + 10
Relational operators in C:
S.no Operators Example Description
1 > x > y x is greater than y
2 < x < y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y
Logical operators in C:
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and logical NOT (!).
S.no Operators Name Example Description
1 && logical AND (x>5)&&(y<5) It returns true when both conditions are true
2 || logical OR (x>=10)||(y>=10) It returns true when at-least one of the condition is true
3 ! logical NOT !
((x>5)&&(y<5))
It reverses the state of the operand
Bit wise operators in C:
Decimal values are converted into binary values and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR), << (left shift)
and >> (right shift).
Truth table for bit wise operation Bit wise operators
x y x|y x & y x ^ y Operator_symbol Operator_name
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
<< Left Shift
>> Right Shift
Conditional or ternary operators in C:
Conditional operators return one value if condition is true and returns another value is condition is false.
This operator is also called as ternary operator.
Syntax : (Condition? true_value: false_value);
Example : (A > 100 ? 0 : 1);.
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional
statements.
Increment/decrement Operators
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: - - var_name; (or) var_name - -;
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : - – i ; i – - ;
Special Operators in C:
Below are some of special operators that C language offers.
S.no Operators Description
1 & This is used to get the address of the variable.
Example : &a will give address of a.
2 * This is used as pointer to a variable.
Example : * a where, * is pointer to the variable a.
3 Sizeof () This gives the size of the variable.
Example : size of (char) will give us 1.
Q) Write a program to find biggest among three numbers.
#include <stdio.h>
void main()
{
float a, b, c;
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
if(a>b && a>c)
printf("Largest number = %f", a);
else if(b>c)
printf("Largest number = %f", b);
else
printf("Largest number = %f", c);
}
Q)Explain about the looping making statements in C.
loop control statements : repeatedly executes a statement/ block of statements as long as a given condition is
true.
Control comes out of the loop statements once condition becomes false.
Output:
Enter three numbers:3
4
5
Largest number = 5
Types of loop control statements in C:
There are 3 types of loop control statements in C language. They are,
1. for 2. while 3. do while
While loop:
/* Program to print the natural numbers from 1 to 5 using while loop*/
#include <stdio.h>
void main()
{
int i=1;
while(i < 5)
{
printf(“%dn”,i);
i++;
}
}
Do while loop:
/* Program to print the natural numbers from 1 to 5 using do - while loop*/
#include <stdio.h>
void main()
{
int i=1;
do
{
printf(“%dn”,i);
i++;
} while(i < 5);
}
For loop:
/* Program to print the natural numbers from 1 to 10 using for loop*/
#include <stdio.h>
void main()
{
Syntax of do while loop is as follows:
do {
statements;
}
while (condition);
The syntax of while loop is as follows:
while(condition)
{
statement(s);
}
Syntax of for loop is as follows:
for (exp1; exp2; expr3)
{
statements;
}
Where,
exp1 – variable initialization
( Example: i=0, j=2, k=3 )
exp2 – condition checking
( Example: i>5, j<3, k=3 )
exp3 – increment/decrement
( Example: ++i, j–, ++k )
int i;
for(i=1;i < 5;i++)
{
printf(“%dn”,i);
}
}
Output: 1
2
3
4
5
Q) Whys is clrscr() used?
clrscr() will clear the output of previous execution. It is defined in conio.h header file.
Q) Explain about the execution of c program.
Source code
is the program written by user.
ex: factorial.c
Compiler
converts the c program into
machine level language
Object code
ex: factorial.obj
LinkerObject code of header
files included
Ex: stdio.h
Executable
ex: factorial.exe
main()
{
int x, y;
y= f1(x);
…….
}
int f1(int z)
{
……
return z;
}
Functions
Definition: Functions are self contained and independent block of statements.
C allows a big program to be divided into segments known as functions.
Need for functions
1. Code reuse.
2. Dividing a program into functions allows each function to be tested separately.
3. A large program may not fit in main memory.
Using Functions
While using functions we use the following terminology
1. If a function f() uses another function g().
f() is called calling function and g() is called called function
2. Function call
When a function is called, the compiler jumps to the called function to execute the statements of called function.
When the called function is executed, the program control passes back to the calling function
Here main() is calling function and f1() is called function
3. Inputs given to function are called parameters / arguments.
Arguments are 2 types
i) Actual arguments: arguments given in function call.
Here x is actual argument
ii) Formal arguments : arguments given in function
definition. Here z is called formal argument.
4. Return statement:
return statement terminates the execution of a function and returns the control to the calling function.
5. Function declaration/ Function prototype
Before using function, the compiler must know about its return type and number and type of arguments the
function takes
Syntax: return_type function_name (datatype variable1…..);
6. Function definition
When a function is defined space is allocated for that function in memory
A function definition consists of
i) Function header :
Syntax: return_type function_name (datatype variable1…..)
ii) Function body :
contains code to perform specific task
Passing arguments to functions
Arguments can be passed by calling function in 2 ways
1. Call by value: In this method, the called function creates new variables and
copies the values of arguments passed to it.
If the values of arguments are modified, the modified values can be sent to caller using return statement.
Advantages: variables, literals (Ex: 6), expressions (x+1) can be passed using call by value
Disadvantage: copying arguments requires more memory and takes lot of time.
f1()
{
…..
…..
}
2. Call by reference : In this method, the function receives address of the
arguments. Changes made to arguments in called function will also change the values in calling function
Advantages: A function can return only one value. To return multiple values, call by reference is used
/* swapping using call by value */
void swap(int , int);
void main()
{
int a ,b;
clrscr();
printf(“enter two numbers”);
scanf(“%d%d”, &a,&b);
printf(“values before swapping = %d t%d”, a, b);
swap(a,b);
getch();
}
void swap ( int x, int y)
{
int temp;
temp =x;
x=y;
y=temp;
printf(“values after swapping = %dt %d”, x, y);
}
/* swapping using call by reference */
void swap(int *, int *);
void main()
{
int a ,b;
clrscr();
printf(“enter two numbers”);
scanf(“%d%d”, &a,&b);
printf(“values before swapping = %d t %d”, a, b);
swap(&a,&b);
getch();
}
void swap ( int *x, int *y)
{
int temp;
temp =*x;
*x=*y;
*y=temp;
printf(“values after swapping = %d t %d”, *x, *y);
}
Types of functions:
There are 2 types of functions
1. Built in / pre-defined functions: these are stored as library files. Ex: printf, scanf, abs(), strlen()
2. User defined functions: these functions are defined by the user with his own logic. Ex: main(), factorial()
Categories of functions
1. Functions with arguments and with return type
2. Functions with arguments and without return type
3. Functions without arguments and without return type
4. Functions without arguments and with return type
Recursion
Recursive function is a function that calls itself.
Every recursive function must have an exit condition/ terminating condition / stop condition. If not,
recursive function will call itself indefinitely.
When the problem can be defined in recursive manner, then recursion can be used.
Advantages:
1. Recursive solutions are shorter and simpler than non- recursive solutions.
2. Code is clearer and easier to use.
3. Follows divide and conquer to solve problems
Disadvantages:
1. Recursion is difficult concept to some programmers
2. Recursion uses system stack. If the system stack is limited, it is difficult to implement recursion
3. uses more memory and time to execute
4. it is difficult to find errors.
Example: 1 if a=1
factorial(a) =
a*factorial(a-1) if a > 1
Types of Recursion
1. Direct recursion: a function is said to be directly recursive if it is explicitly calls itself.
2. Indirect Recursion: a function is said to be indirectly recursive if it calls another function which
ultimately calls it.
3. Tail Recursion: if no operations are pending to be performed when the recursive function returns to its
caller.
4. Linear Recursion: when the pending operation (if any) does not make another recursive call to the
function
5. Non linear / Tree recursion: when the pending operation makes another recursive call to the function
Scope of a variable
Scope is accessibility and visibility of the variables.
Variables in C has 4 types of scope
1. block scope:
a statement block is a group of statements enclosing within { and }. If a variable is declared
within a statement block , as soon as control exits the block, the variable will be removed from
memory. Such a variable is said to have block scope.
2. function scope: variable is accessible and visible from the beginning to end of a function
3. program scope: variable is accessible and visible from the beginning to end of a program
4. file scope: variable is accessible and visible from the beginning to end of a file
Storage Classes
The storage class defines scope (visibility) and lifetime of variable and functions declared within a C program.
The storage class will determine
1. where the variable will be allocated memory ( in register or main memory etc...)
2. how long the variable stays in memory (life time )
3. scope of the variable i.e, the part of C program in which the variable is accessible or visible.
4. whether the variable will be automatically initialized or not.
C supports 4 storage classes.
1. automatic
2. register
3. external
4. static
Comparison of storage classes
Feature Storage class
auto extern register static
Accessibility Within function or block in
which it is declared
Within all
program files that
are part of a
program
Within function or
block in which it is
declared
Local: Within
function or block in
which it is declared
Global: Within the
program in which it
is declared
Storage Main memory Main memory CPU register Main memory
Existence Exists in memory as long as
the control is within the
block or function in which it
is declared. Once the control
returns from function or
block, it is removed from
memory
Exists through out
the execution of
the program
Exists in memory as
long as the control is
within the block or
function in which it is
declared. Once the
control returns from
function or block, it is
removed from memory
Local: Exists
through out the
execution of the
program
Global: Exists
through out the
execution of the
program files
Default
Value
Garbage Garbage Garbage zero
Array: It is collection of similar data type elements. All Elements of array are stored in contiguous memory
locations.
Declaration of Arrays:
An array can be declared by specifying 3 things
1. Data type: what kind of values it can store Ex: int , char , float etc..
2. Name: to identify the array
3. Size: the maximum number of values the array can hold
Syntax:
type name[size]
Example: int marks[3];
marks is an array of integer type and it can hold maximum 3 elements. marks is pointer that holds the address of
first element (&marks[0])
Initialization of array (or) storing values in arrays
All Elements of array are stored in contiguous memory locations.
Memory location
addresses
1000 1002 1004
95 96 97
marks[0] marks[1] marks[2]
1. Initialization at the time of declaration
int marks[3] = { 95,96,97}
Here since marks stores integer values. Each element in array requires 2 bytes. If marks[0] is stored at memory
location 1000 then second element (marks[1]) is stored at memory location 1002 and so on.
2. Taking values of all the array elements (marks[0], marks [1], marks[2]) from user
Ex:
for(i=0;i<3;i++)
{
printf (“enter marks of student no. %d”,i);
scanf(“%d”,&marks[i];
}
3. Giving values to individual elements
marks[0] = 95;
marks[1] = 96;
marks[2] = 97;
We can change the marks of individual elements using the above method. In marks[2] data element, 2 is the
index or subscript. It is the (index+1) i.e, 5th
element in the array marks as index starts with zero in arrays.
Displaying the elements of an array
for(i=0;i<5;i++)
{
printf (“%d”, marks[i]);
}
Operations that can be performed on arrays
1. Traversal: acessing every element of array
2. Insertion : inserting a new element
3. Deletion: deleting existing element
4. Merging: merge 2 arrays
5. Search : search for a value in an array
6. Sorting : arrange the values in array in either ascending or descending order.
Types of arrays:
1. One dimensional arrays (1D)
2. Two dimensional arrays (2D)
3. Multi dimensional arrays (3D)
1. 1D array is represented using one index ‘[ ]’ .It is mostly used for searching and sorting
2. 2D array is represented using two indexes ‘[][]’. One subscript denotes rows and other denotes columns.
It is mostly used for matrix representation. Example: int marks[3][3]; (3 rows and 3 columns)
3. Multi dimensional arrays have more than 2 indices. Example: int m[3][2][2]
m is an array of three 2D arrays.
Program to read and print the values of 1D
array
Find the sum of the elements of an array
void main()
void main()
{
int marks[5], i;
clrscr();
printf(“Enter marks of 5 students”);
for (i=0;i<5;i++)
{
scanf(“%d”,&marks[i]);
printf(“n marks = %d”, marks[i]);
}
getch();
}
{
int marks[5], i, sum;
clrscr();
sum=0;
printf(“Enter marks of 5 students”);
for (i=0;i<5;i++)
{
scanf(“%d”,&marks[i]);
sum = sum+ marks[i];
}
printf(“sum = %d”, sum);
getch();
}
Search an element in an array using linear search
void main()
{
int a [10], i, n, s, flag = 0;
printf(“Enter the number of elements”);
scanf(“%d”, &n);
printf (“enter %d elements”,n);
for (i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“enter the search element”);
scanf(“%d”, &s);
for (i=0;i<n;i++)
{
if ( s == a[i])
{
flag = 1;
break;
}
}
if( flag = = 1)
printf(“Element found”);
else
printf(“Element not found”);
getch();
}
Search an element in an array using binary search
void main()
{
int a [10], i, n, s, left, right, mid, flag=0;
printf(“Enter the number of elements”);
scanf(“%d”, &n);
printf (“enter %d elements”,n);
for (i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“enter the search element”);
scanf(“%d”, &s);
left=0;
right=n-1;
mid = (left+right)/2;
while (left < = right)
{
if ( s = = a[mid])
flag =1;
else if ( s< a[mid])
right = mid-1;
else
left = mid+1;
mid = (left+right)/2;
}
if( flag = = 1)
printf(“Element found”);
else
printf(“Element not found”);
getch();
}
Program to sort the given elements using bubble sort.
#include <stdio.h>
#include <conio.h>
Program to read and print values of 2D array
#include <stdio.h>
#include <conio.h>
void main()
{
int a [10], i, n, j, t;
printf(“Enter the number of elements”);
scanf(“%d”, &n);
for (i=0;i<n;i++)
scanf(“%d”,&a[i]);
for ( i=0; i< n; i++)
{
for ( j = i+1; j < = n; j++)
{
if( a[i] > a[j])
{
t= a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf(“n sorted array”);
for (i =0; i< n; i++)
printf(“%5d”, a[i];
getch();
}
void main()
{
int a[5][5],i,j,r,c;
clrscr();
printf(“enter the order of matrix”);
scanf(“%d %d”, &r,&c);
printf(“Enter %d elements”, r*c);
for(i=0; i<0r;i++)
for(j=0; j<c;j++)
scanf(“%d”, &a[i][j]);
for(i=0; i<r;i++)
{
for(j=0; j<c;j++)
printf(“%3d”, a[i][j]);
printf(“n”);
}
getch();
}
Two dimensional Arrays
Declaration:
Syntax:
data_type name [row_size][column_size];
Example:
int marks[3][2];
marks is a 2D array that can store 3*2 = 6 elements. (row_size * column_size)
Initialization of 2D array
1. Initialization at the time of declaration
int marks[3][2] ={ 80,81,82,83,84,85};
(or)
int marks[3][2] = {{80,81},{82,83},{84,85}};
2. Giving values to individual elements
marks[0][0]=80; marks[0][1]=81; marks[1][0]=82; marks[1][1]=83;
marks[2][0]=84; marks[2][1]=85;
3. Taking values of all array elements from user
for(i=0; i<3;i++)
for(j=0; j<2;j++)
scanf(“%d”, &marks[i][j]);
memory
addresses
1004 1008 1010 1012 1014 1016
80 81 82 83 84 85
One dimensional
arrays
One dimensional
arrays
Passing entire
array
Passing data
values
Passing
addresses
marks[0][0] marks[0][1] marks[1][0] marks[1][1] marks[2][0] marks[2][1]
marks[0] marks[1] marks[2]
The two dimensional matrix marks is an array of three 1D arrays (marks[0], marks[1] marks[2])
Arrays and Functions
1. 1D arrays and passing them as arguments to functions can be as shown in the diagram below
Passing entire array to function
When entire array is passed to function, they are always passed by address. In arrays there is no call by value
and there is only call by reference.
When the address of array is passed there is no way the function will come to know about the size of the array.
so size of the array must also be passed.
Example:
int soe(int *, int );
void main()
{
int marks[3] = {65,67,69};
int sum;
sum = soe(&marks[0], 3);
printf(“sum of elements in array =%d”,sum);
}
int soe(int *b, int size)
{
int i, s=0;
for ( i=0; i< size, i++)
s=s+(*(b+i));
return s;
}
Note: marks (or) &marks[0] (or) (marks + 0) are the same
&marks[1] (or) (marks+1) are same
marks[0] (or) *(marks+0) are the same.
/* program to perform matrix multiplication */
#include <stdlib.h>
void main()
{
int a[10][10], b[10][10], c[10][10], r1,c1,r2,c2, i,j,k;
clrscr();
printf(“enter the order of matrix A”);
scanf(“%d%d”,&r1,&c1);
printf(“enter the order of matrix B”);
scanf(“%d%d”,&r2,&c2);
printf(“enter the elements of matrix A”);
for (i = 0; i< r1; i++)
for (j=0; j<c1; j++)
scanf(“%d”, &a[i][j]);
printf(“enter the elements of matrix B”);
for (i = 0; i< r2; i++)
for (j=0; j<c2; j++)
scanf(“%d”, &b[i][j]);
if(r1 != c2)
{
printf(“n multiplication is not possible”);
exit(0);
}
else
{
for(i=0; i<r1; i++)
{
for (j=0; j<c2; j++)
{
c[i][j]=0;
for(k=0; k<c1; k++)
c[i][j] = c[i][j]+ a[i][k]* b[k][j];
}
}
}
printf(“the resultant matrix isn”);
for(i=0; i<r1;i++)
{
for(j=0; j<c2;j++)
printf(“%dt”, c[i][j]);
printf(“n”);
}
}
STRINGS
A String in C is defined to be a sequence of characters terminated by null character ‘0’. The null character
indicates the end of a string.
Declaration of Array of char type:
Syntax: char string_name[size];
Example: char str[20];
str is string name
20 is the size of string.
Example 2: char str[10]=”COMPUTER”;
C O M P U T E R 0
str
[0]
str
[1]
str
[2]
str
[3]
str
[4]
str
[5]
str
[6]
str
[7]
str
[8]
Initialization of arrays of char type:
Type 1: char str[6]={‘H’,’E’,’L’,’L’,’O’,’0’};
Type 2: char str[6]=”HELLO”;
Write a program to read and write strings using scanf and printf
#include <stdio.h>
void main()
{
char str[10];
printf(“Enter a string”);
scanf(“%s”, &str);
printf(“You entered %s”,str);
}
String Input/ Output Functions
1. Reading Strings
Strings can be read from user by using 3 ways
1. using scanf function
2. using gets() function
3. using getchar(), getch() and getche() functions
The main drawback of scanf() function is that it teminates as soon as it finds a blank space. So, we can use
gets() function which takes blank spaces .
getchar(), getch() and getche() functions read only single characters and has to call them repeatedly to read a
string.
2. Writing Strings
Strings can be displayed using three ways
1. using printf() function
2. using puts() function
3. using putchar() function repeatedly
Summary of functions to read and write a single character
Function Operation Usage
getchar() Used to read a character from keyboard and waits for ENTER
or TAB or ESC key to be pressed
char s =
getchar();
getch() Reads a character from keyboard and returns immediately and
does not wait for ENTER key to be pressed. It does not display
the character entered by user
char s =
getch();
getche() Reads a character from keyboard and returns immediately and
does not wait for ENTER key to be pressed. It displays the
character entered by user
char s =
getche();
putchar() Writes a character to screen putchar(s)
Write a program to read and write strings using puts() and gets()
Output:
Enter a string
mpcs student.
You entered mpcs
void main()
{
char str[20];
puts("Enter a string");
gets(str);
puts(str);
}
String manipulation functions
The string library functions which are in the header file “string.h”
The most commonly performed operations are
1. Finding the length of the string – strlen()
2. Copying one string to another string – strcpy()
3. Comparing two string --- strcmp()
4. Concatenation of two strings --- strcat()
5. Reverse the given string-- strrev()
6. Convert the input string to lower case strlwr()
7. Convert the input string to upper case strupr()
1. Finding the length
strlen() is used to find the number of characters in a string excluding the null character
Usage: int length = strlen(string)
Write a program to find the length of a string
#include <string.h>
void main()
{
char str[10];
int len;
printf(“enter a string”);
scanf(“%s”, &str);
len = strlen(str);
printf(“You entered %s”,str);
printf(“length of the string is %d”,len);
}
2. copying one string to another string
Usage: strcpy(string1, string2);
This function copies the string2 to string 1 including the null character. The contents if any in string1 will be
lost.
#include <string.h>
void main()
{
char str1[50],str2[50];
clrscr();
printf("enter a string");
gets(str2);
strcpy(str1,str2);
printf(“copied string in str1 is %s”,str1);
}
3. strcmp() is used to compare two strings
Output:
Enter a string
computers
You entered computers
Length of the string is 9
Output:
Enter a string
mpcs
copied string in str1 is mpcs
Usage: int ret = strcmp( string1, string2)
This function return values as follows:
• returns < 0 if str1 is less than str2.
• returns > 0 if str2 is less than str1.
• returns = 0 if str1 is equal to str2.
Write a program to compare two strings
#include <string.h>
void main()
{
char str1[50],str2[50];
int ret;
clrscr();
printf("enter first string");
gets(str1);
printf("enter second string");
gets(str2);
ret = strcmp(str1,str2);
if (ret == 0)
printf(“the two strings are equal”);
else
printf(“the two strings are not equal”);
}
4. Concatenation of two strings
The strcat() function appends the string2 to the end of the string1. The null character in string1 is overwritten.
The process stops when null character of string2 is copied. String1 must be big enough to store the contents of
string1 and string2.
Usage: strcat(string1, string2)
Write a program to concatenate two strings
#include <string.h>
void main()
{
char str1[50],str2[50];
clrscr();
printf("enter first string");
gets(str1);
printf("enter second string");
gets(str2);
strcat(str1,str2);
printf(“string1 =%s”,str1);
}
5. Reverse the input string
#include <string.h>
void main()
{
char str1[50],str2[50];
clrscr();
printf("enter a string ");
gets(str1);
printf(“reverse =%s”, strrev(str1));
Output:
Enter first string
mpcs
Enter second string
mecs
the two strings are not equal
Output:
Enter first string
mpcs
Enter second string
First year
String1 = mpcs First year
Output:
enter a string
mpcs
reverse = scpm
}
6. Convert the input string into lower case
#include <string.h>
void main()
{
char str1[50],str2[50];
clrscr();
printf("enter a string in capital letter ");
gets(str1);
printf(“lowercase =%s”, strlwr(str1));
}
7. Convert the input string into uppercase
#include <string.h>
void main()
{
char str1[50],str2[50];
clrscr();
printf("enter a string in lower case ");
gets(str1);
printf(“upper case =%s”, strupr(str1));
}
ARRAYS OF STRINGS
An array of string is declared as char names[5][30];
First index indicates how many strings are needed and Second index indicates the length of every individual
string.
char names[3][30] = {“RAM”,”SHYAM”,”SAI”};
3 names and each name can consist of maximum of 30 characters .
Memory representation of 2D array
names[0] R A M 0
names[1] S H Y A M 0
names[2] S A I 0
Write a program to print names of n students of a class
void main()
{
char names[10][30];
int i, n;
clrscr();
puts(“Enter the number of studentsn”);
scanf(“%d”, &n);
printf(“enter names of %d students”, n);
for ( i = 0; i<n;i++)
{
scanf(“%s”,names[i]);
}
for ( i = 0; i<n;i++)
{
puts(names[i]);
}
Output:
Enter the number of students
2
Enter names of 2 students
sita
gita
sita
gita
Output:
enter a string
MPCS
lowercase = mpcs
Output:
enter a string in lower case
mpcs
uppercase = MPCS
}
UNIT – VI Pointers
Pointer Variables
When a variable is declared some amount of memory is allocated to hold the value of that variable. The size of
memory allocated depends on the datatype of the variable. Each memory location has an address.
pointer is a variable that stores the address of another variable.
Applications of pointers
1. pointers are used to pass arrays and strings as function arguments.
2. using pointers one can pass functions as arguments to another function
3. pointers are used to create complex data structures like trees, stack, queues etc..
4. pointers are used for dynamic memory allocation
Declaring and initializing Pointers
Example 1:
int x = 6000;
int *ptr1;
ptr1=&x;
ptr1 will store the starting address (here 100) and will read 2 bytes as it points to a integer variable when
dereferenced using *ptr1.
Example2:
float sal = 100000.0;
float *ptr2;
ptr2=&sal;
ptr1 and ptr2 occupy same amount of memory. Memory enough to store the address of a memory location.
The datatype of pointer indicate that they contain the address of a variable of that datatype.
Indirection operator (or) Value at Address operator (*)
When * is used as unary operator after the pointer variable other than at the declaration of pointer variable, then
* is called indirection operator.
void main()
{
int x= 6000, *ptr;
ptr = &x;
printf(“%d”, *ptr);
}
The above program will print 6000 on the screen.
* operator deferences a pointer and will display the value present at the address stored in pointer.
printf (“%d”, *(&x) ; will also prints 6000 on the screen. Hence *ptr (or) x (or) *(&x) are same.
Addresses 10
0
10
1
10
2
10
3
104 105
6000 100
x ptr1
Addresses 10
6
10
7
10
8
10
9
11
0
111
100000.0 106
sal ptr2
ptr (or) &x are same.
Write a program to declare and access pointer variable
void main()
{
int x = 6000, *ptr;
ptr = &x;
printf(“ value of x = %d”,x);
printf(“ value of x = %d”,*ptr);
printf(“ value of x = %d”,*(&x));
printf (“address of x = %u”, ptr);
printf (“address of x = %u”, &x);
}
Generic pointers
It is a pointer variable that has void as its data type. Generic pointer can be used to point to variables of any data
type.
Ex: void *ptr;
Pointers and arrays
Example: int marks[10], *ptr ;
ptr = marks;
The array name marks holds the starting address of the array i.e, &marks[0]
Write a program to print the elements of array using pointers
void main()
{
int marks[3] = { 1,2, 3}, *ptr,i=0 ;
ptr=&marks[0];
printf(“elements in an array are”);
while( i<3)
{
printf(“%dt”, *ptr);
ptr++;
}
Write a program to pass string as arguments to functions using pointers
void print(char *);
void main()
{
char str[20]=”HELLO”;
print(str);
}
void print( char *c)
{
while(*c != 0)
{
printf(“%c”, *c);
c++;
}
}
Understanding Computer memory
Memory allocated to a Program or application is divided into 4 segments.
1. Code -- contains instructions
Output:
HELLO
2. Static/ Global memory --stores static and global variable that have program lifetime
3. Stack memory
4. Heap memory.
A fixed size Stack is allocated by the system and the stack is filled from bottom to top. Also the last element
added to stack is removed first (hence it is called LIFO data structure). All the variables declared within main()
are allocated space on stack. All the parameters passed to called function are also stored on stack. Stack is
faster, smaller and expensive than HEAP memory.
A fixed size HEAP is allocated by the system and is used when need arises in random fashion.
what is static memory and dynamic memory allocation?
1. Static memory allocation: The process of allocating memory to program at compile time is known as static
memory allocation. This memory cannot be changed during the execution of program. Example : stack and
global memory
when a program is executed, certain amout of memory from stack is taken and allocated for main() method.
This is called stack frame.
Similarly stack frame is created for each function called above the main()'s stack frame.
when a function is called, it is pushed onto the stack.
when control returns from function, it is popped from stack.
Whatever is on the top of the stack is executing.
At the time of program compilation itself, the amout of memory to be allocated for each function's stack frame
is decided by the compiler and do not change.
Hence it is called Static allocation.
2. Dynamic memory allocation: The process of allocating memory to the variables during program execution or
at run time is known as dynamic memory allocation. Example : heap memory.
If you want memory to be kept as long as you want, instead of getting cleared automatically when popped from
stack, we use dynamic memory.
In C, dynamic memory allocation is done using
1. malloc
2.calloc
3. realloc
Dynamic memory deallocation is done using free
1. malloc returns a void pointer that has address of first byte of block of memory allocated on heap , so we
typecast as shown below
ex: The below code allocates memory for 20 integers on heap
int *p;
p= (int *) malloc(20*sizeof(int));
2. free(p); is used to deallocate the memory.
3. calloc is same as malloc except
i. it takes 2 arguments. For ex: p=(int *)calloc(20, sizeof(int));
ii. it initializes all the memory allocated on heap to 'zero'
4. realloc is used to change the amout of memory previously allocated on heap
syntax:
void * realloc(void * ptr, size_t size)
ptr is pointer to existing block
size is the size of new block
size_t is data type that has only positive values For ex: unsigned integer.
Structures
A structure is a user defined data type. A structure stores related information. Structure is collection of variables
of DIFFERENT data types.
Declaring structures
A structure is declared using struct keyword followed by structure name.
All variables of structure are declared within structure and each variable is called member of the structure.
Memory is not allocated when the structure is declared.
Example:
struct student
{
int roll_no;
char name[10];
int marks;
}s1;
Structure initializations
Structures can be initialized in 3ways
1) 2) 3)
100
101
102
103
104
105
106
107
108
109
110
111
112
113
struct book
{
char title[20];
char author[40];
int price;
}b1 ={“ANSI
C”,”swamy”,350};
struct book
{
char title[20];
char author[40];
int price;
};
struct book b1 ={“ANSI
C”,”swamy”,350};
struct book b1,b2,b3;
b1.title=”ANSI C”;
b1.author=”guru
swamy”;
b1.price=350;
b2.title=” C”;
b2.author=”reema”;
b2.price=450;
Accessing the members of structure
A structure variable is accessed using a ‘.’ operator.
Write a program to print the details of 2 students such as rollno, name, course and fees.
#include <string.h>
void main()
{
struct student
{
int roll;
char name[40], course[10];
};
struct student s1={151301, “adi”,”IMPCS”};
struct student s2;
s2.roll=151302;
strcpy(s2.name,”naik”);
strcpy(s2.course,”IMPCS”);
printf(“rollno = %d t name=%s t course=%s n”, s1.roll, s1.name, s1.course);
printf(“rollno = %d t name=%s t course=%s n”, s2.roll, s2.name, s2.course);
}
typedef
By using typedef keyword an alternate name is given to existing data type.
When we precede a struct name with typedef keyword then the struct becomes a new data type.
write a program to create a user defined data type date
#include <string.h>
typedef struct date
{
int dd;
int mm;
int yy;
};
void main()
{
date d1 = {1,9,2015};
printf(“today’s date = %d - %d - %d”, d1.dd, d1.mm, d1.yy);
}
Now that we have added typedef keyword before structure name date, date becomes new data type. Therefore,
we can define variable of type date by writing just date d1,d2,d3;
Copying and comparing structures
We can assign a structure variable to another structure variable of same type.
Example: struct student s1={151301, “adi”,”IMPCS”,18000};
struct student s2;
s2=s1;
C does not allow comparing of two structure variable however; individual elements of one structure can be
compared with individual elements of another structure.
Nested Structures
A structure can be placed within another structure. That is, a structure may contain another structure as its
member. Such a structure is called a nested structure.
#include <stdio.h>
typedef struct date
{
int dd;
int mm;
int yy;
};
typedef struct student
{
char name[40];
date dob;
};
main()
{
student s1;
printf("enter name and date, month and year of birth of studentn");
scanf("%s %d %d %d", &s1.name, &s1.dob.dd, &s1.dob.mm, &s1.dob.yy);
printf("name =%s t date of birth =%d - %d - %d", s1.name, s1.dob.dd, s1.dob.mm, s1.dob.yy);
}
Arrays of structures
Example: student st[30];
To assign values to ith student, you should write
st[i].name = “ xyz”;
st[i].dob.dd = 21;
st[i].dob.mm=12;
st[i].dob.yy=1991;
Self referential Structures contains a pointer to data that is of same type as that of the structure.
example:
struct node
{
int val;
struct node *next;
}
Here the structure node will contain 2 types of data- an integer val and next, which is pointer to a node.
Structures and Functions
A structure can be passed to a function in 3 ways
1. Passing individual members
2. Passing the entire structure
3. Passing the address of the structure.
Difference between structure and unions
Structure Union
It is collection of variables of different data
type
Structure is declared using struct keyword
struct structure_name
{
datatype var1;
datatype var2;
}object;
It is collection of variables of different data
type
Union is declared using union keyword
union name
{
datatype var1;
datatype var2;
}object;
Each member within a structure is allocated
unique memory.
A common memory of size equal to largest
member size is allocated. Each member
struct book
{
char title[20];
char author[40];
int price;
}b1 ;
Memory allocated for b1 = 64 bytes
20 bytes for title variable +
40 bytes for author variable+
2 bytes for price variable+ 2 bytes padding
within union share the common memory.
union book
{
char title[20];
char author[40];
int price;
}b1 ;
Memory allocated for b1 = 40 bytes
Size of structure is >= sum of sizes of its
members
Size of union is equal to its largest member
size
All the members can be assigned values at a
time.
Only one member can be assigned value at a
time
All the members can be accessed at same
time
Only one member can be accessed at a time
Values assigned to one member will not
cause the change in other members.
Values assigned to one member may cause
change in values of other members.
Enumerated Data types
Enumerated data types is a user defined type. Keyword enum is used to defined enumerated data type.
Enumerated data type consists of integral constants and each integral constant is given a name.
Example:
enum month {JAN =1 ,FEB=2,MAR=3,APR=4,MAY=5,JUN=6,JUL=7,AUG=8,SEP=9,OCT=10,
NOV=11,DEC=12};
A user defined data type month is created. It has 12 values as given in pair of braces.
enum month rmonth;
“rmonth” variable is declared of type “month” which can be initialized with any data value amongst 12 values”.
Files
File is a collection of records stored in secondary memory such as hard disk. Record is collection of fields and
each field can carry a value.
Stream is a logical interface. Stream can be attached to any device to communicate with that device. The device
can be logical file or physical keyboard.
There are 3 standard streams in C language
1. standard input (stdin)----------- stream from which the program receives data.
2. standard output (stdout) ------- stream to which the program writes the data.
3. standard error (std err) ---------- stream to which the program writes the error messages.
stdin, stdout and stderr are the logical names given to these streams.
By default Standard input is connected to keyboard. Standard output and Standard error are connected to
monitor.
Buffer: When a stream is linked to a disk file, a buffer is automatically created.
Buffer is block of memory used for temporary storage of data. Buffers are needed as the disk drives are block
oriented.
Types of Files
There are 2 types of files.
1. ASCII text files
2. Binary files.
1. ASCII text file is a stream of characters that can be sequentially processed by a computer. In a text file, each
line of data ends with a new line character (n). Each file ends with a special character (EOF) marker
Example: Integer vaue 123 will be stored as a sequence of 3 characters. And so requires 3 bytes to store
int value will be represented as 2 bytes of memory internally, but externally the int value will be represented as
a string of characters. To convert internal representation into external, we use printf and fprintf functions.
To convert external representation to internal representation, scanf and fscanf functions are used.
2. Binary files may contains any type of data encoded in binary form. A binary file does not require any special
processing.
Binary files can be processed sequentially or randomly.
Integer vaue 123 will be stored in 2 bytes .
Using files in C
To use files in C, we must follow the below steps
1. Declare a FILE pointer variable
2. Open the file (fopen)
3. Process the file
4. Close the file.
Declaring a file pointer variable.
A file pointer variable that points to a structure FILE has to be declared as fopen functions return a FILE
pointer.
Syntax: FILE filepointer_variable;
Ex: FILE *fp;
Opening a file
a file must be opened before data can be read and write. fopen() function is used to open the file.
Syntax: filepointer_variable = fopen(“filepath”,”mode”);
ex: fp = fopen(“myfile.txt”, “r”);
File modes:
mode Description
"r" Opens a file for reading. The file must exist.
"w" Creates an empty file for writing. If a file with the same name already exists, its contents
are erased
"a" Appends data at the end of the file. The file is created if it does not exist.
"r+" Opens a file for reading and writing. The file must exist.
"w+" Creates an empty file for both reading and writing.
"a+" Opens a file for reading and appending.
note: the modes that can be used with binary files are rb,wb,ab, rb+,wb+,ab+
closing a file:
The C library function fclose closes the stream. All buffers are flushed.
syntax: fclose(filepointer_variable);
Example: fclose(fp);
Write a program to read student details from a file and display the details
#include <stdlib.h>
void main()
{
FILE *fp;
char name[40];
int roll;
fp = fopen("student.txt","r");
if( fp == NULL)
{
printf("file cannot be opened");
exit(0);
}
printf("enter rollno and name");
fscanf(fp,"%d%s", &roll,&name);
printf("n Roll no = %d t name = %s",roll, name);
fclose(fp);
}
Reading data from files
C provides the following set of functions to read data from a file.
Function name Description Example
fscanf() fscanf reads formatted
input from a stream.
fgets() fgets reads a line from the
stream and stores it into
the string pointed to by str.
char str[60];
if( fgets (str, 60, fp)!
It stops when either (n-1)
characters are read, the
newline character is read,
or the end-of-file is
reached, whichever comes
first.
=NULL )
{
/* writing content to
stdout */
puts(str);
}
fgetc() gets the next character
from the stream and
advances the position
indicator for the stream
do
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}while(1);
fread() fread function reads data
from the given stream into
the array pointed to, by ptr.
char c[] = "this is c
program";
char buffer[100];
fp = fopen("file.txt",
"w+");
/* Write data to the file
*/
fwrite(c, strlen(c) + 1, 1,
fp);
/* Seek to the beginning
of the file */
fseek(fp, SEEK_SET, 0);
/* Read and from file */
fread(buffer, strlen(c)+1,
1, fp);
writing data to files
1. fprintf() 2. fputs() 3.fputc() 4. fwrite()

Mais conteúdo relacionado

Mais procurados

C the basic concepts
C the basic conceptsC the basic concepts
C the basic concepts
Abhinav Vatsa
 
Pointers in c
Pointers in cPointers in c
Pointers in c
Mohd Arif
 

Mais procurados (20)

Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic concepts
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and Answer
 
best notes in c language
best notes in c languagebest notes in c language
best notes in c language
 
C PROGRAMMING
C PROGRAMMINGC PROGRAMMING
C PROGRAMMING
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
C standard library functions
C standard library functionsC standard library functions
C standard library functions
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
 
Printf and scanf
Printf and scanfPrintf and scanf
Printf and scanf
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
Programming in ansi C by Balaguruswami
Programming in ansi C by BalaguruswamiProgramming in ansi C by Balaguruswami
Programming in ansi C by Balaguruswami
 
Operators
OperatorsOperators
Operators
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
 
Introduction to problem solving in C
Introduction to problem solving in CIntroduction to problem solving in C
Introduction to problem solving in C
 
Introduction to c++ ppt 1
Introduction to c++ ppt 1Introduction to c++ ppt 1
Introduction to c++ ppt 1
 
C data type format specifier
C data type format specifierC data type format specifier
C data type format specifier
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 

Semelhante a C notes for exam preparation

C programming_MSBTE_Diploma_Pranoti Doke
C programming_MSBTE_Diploma_Pranoti DokeC programming_MSBTE_Diploma_Pranoti Doke
C programming_MSBTE_Diploma_Pranoti Doke
Pranoti Doke
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving Techniques
valarpink
 

Semelhante a C notes for exam preparation (20)

Unit1 C
Unit1 CUnit1 C
Unit1 C
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
C programming
C programmingC programming
C programming
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
C programming_MSBTE_Diploma_Pranoti Doke
C programming_MSBTE_Diploma_Pranoti DokeC programming_MSBTE_Diploma_Pranoti Doke
C programming_MSBTE_Diploma_Pranoti Doke
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
 
INTRODUCCIÓN A LA PROGRAMACIÓN
INTRODUCCIÓN A LA PROGRAMACIÓNINTRODUCCIÓN A LA PROGRAMACIÓN
INTRODUCCIÓN A LA PROGRAMACIÓN
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topics
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving Techniques
 
Chapter3
Chapter3Chapter3
Chapter3
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
 
Pc module1
Pc module1Pc module1
Pc module1
 
Complete c programming presentation
Complete c programming presentationComplete c programming presentation
Complete c programming presentation
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
 
Presentation 2.ppt
Presentation 2.pptPresentation 2.ppt
Presentation 2.ppt
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 

Mais de Lakshmi Sarvani Videla

Mais de Lakshmi Sarvani Videla (20)

Data Science Using Python
Data Science Using PythonData Science Using Python
Data Science Using Python
 
Programs on multithreading
Programs on multithreadingPrograms on multithreading
Programs on multithreading
 
Menu Driven programs in Java
Menu Driven programs in JavaMenu Driven programs in Java
Menu Driven programs in Java
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
 
Simple questions on structures concept
Simple questions on structures conceptSimple questions on structures concept
Simple questions on structures concept
 
Errors incompetitiveprogramming
Errors incompetitiveprogrammingErrors incompetitiveprogramming
Errors incompetitiveprogramming
 
Relational Operators in C
Relational Operators in CRelational Operators in C
Relational Operators in C
 
Recursive functions in C
Recursive functions in CRecursive functions in C
Recursive functions in C
 
Function Pointer in C
Function Pointer in CFunction Pointer in C
Function Pointer in C
 
Functions
FunctionsFunctions
Functions
 
Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
Singlelinked list
Singlelinked listSinglelinked list
Singlelinked list
 
Graphs
GraphsGraphs
Graphs
 
B trees
B treesB trees
B trees
 
Functions in python3
Functions in python3Functions in python3
Functions in python3
 
Dictionary
DictionaryDictionary
Dictionary
 
Sets
SetsSets
Sets
 
Lists
ListsLists
Lists
 
DataStructures notes
DataStructures notesDataStructures notes
DataStructures notes
 
Solutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structuresSolutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structures
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

C notes for exam preparation

  • 1. Start Read A, B Sum=A+B Print Sum Start Q) Define algorithm and flowchart? Ans:An algorithm is a step by step description of how to arrive at a solution. It is finite set of instructions which when followed in sequence solves a particular task. Once algorithm is written, it can be implemented in any high level language. Algorithm to add two numbers Step 1: Input the first number as A Step2: Input the second number as B Step3: Set Sum = A + B Step4: Print Sum Step 5: End Flow chart is a graphical or symbolic representation of an algorithm. Flow chart to add two numbers and display the sum is as shown in the figure Q) What is Token and explain? Ans: Tokens are basic building blocks of C Programming. Each and every smallest individual units in a C program are known as C tokens. No Token Type Example 1 Keyword Keywords are reserved words by compiler. while 2 Variables Variables are named locations in memory. sum 3 Constants Constants are assigned to variables 89 4 Special Symbols Used in different declarations in C ( ), {} 5 Operators Used in expressions /,*,+ 6. String Sequence of characters “hello” Q) Difference between while and do-while Ans: The only difference is In a do-while loop, test condition is tested after the body of the loop. Hence body of loop is executed atleast once even if the condition is false. The do-while loop is also called post test or exit controlled loop. In while loop, test condition is tested before the body of the loop. only if the condition is true, the body of the loop is executed. The while loop is also called pre test or entry controlled loop. Q) What is software? Ans: Software is a set of programs. A program is a set of instructions arranged in a sequence to guide a computer to solve a problem. True False Condition ? Body of loop StatementX True False Flow chart for while loop Flow chart for do-while loop True False StatementX Conditio n? Body of loop
  • 2. Computer software is written by programmers using a programming language. Computer software is divided into 2 categories • System software • Application software System software allows a user to interact with the computer hardware.and provides a platform for running application software. System software is responsible for controlling and managing hardware components of a computer system. Ex: Operating System, Compiler, BIOS, Device Drivers. Application Software performs specific task with the help of system software. Ex: Word processors, Image editors, Spread sheets etc.. Q) Write about constants in C Constants are identifiers whose value do not change during the execution of a program. Constants can be declared using const keyword or using the preprocessor command define Ex: const float pi = 3.14; pi is a constant whose value cannot be changed #define PI 3.14 Types of C constants: S.n o Constant type Example Rules for constructing C constant 1 Integer constants 53762, -478, • Must have atleast one digit • It must not have a decimal point 2 Real or Floating point constants 10.45, 0.5e2,14E-2 • Must have atleast one digit • It must have a decimal point 5 character constants ‘A’ , ‘B’, ‘C’ Single character enclosed in single quotes 6 string constants “ABCD” , “Hai” Sequence of characters enclosed in double quotes Q) Write any two header files in C. Ans: It is not possible to write our own output functions every time we wanted to communicate with the computer. So we use header files that have standard functions which can be included in our programs. Header files names end with ‘dot h’ (.h) extension. Example of standard header files are : 1. stdio.h : Contains standard Input and output and file operation functions. Some functions defined in stdio.h are S.no Function Description 1 printf() Prints the output on the screen 2 scanf() Reads a character, string, numeric data from keyboard. 3 gets() It reads line from keyboard 4 getchar() It reads character from keyboard 5 puts() It writes line to o/p screen 6 putchar() It writes a character to screen 7 fflush() flushes a file 2. conio.h: provide console input/output functions. Some of the functions defined in conio.h are S.n o Function Description 1 clrscr() This function is used to clear the output screen. 2 getch() It reads character from keyboard 3 getche() It reads character from keyboard and echoes to o/p screen
  • 3. Long Answer Questions 1. Explain data types in C .Explain with examples. Ans: The data type of a variable determines how much space it occupies in memory. It defines the type of data and operations that can be performed on the data. Basic data types and their size in bytes in a 16 bit computer is shown in the table below. Keyword used Size in bytes Range Use Example character data type char 1 -128 to 127 To store characters char gender = ‘m’; Integer data type int 2 -32767 to 32768 To store integers int num=10; Floating point data type float 4 3.4E-38 to 3.4E+38 To store floating point numbers float discount = 12.5; Double data type double 8 1.7E-308 to 1.7E+308 To store big floating point numbers double sal = 1234567.12345; Valuless Void 0 --- --- There are 4 type modifiers that can be applied to the basic data types. They are: unsigned, signed, short and long. All the modifiers (long, short, unsigned and signed) can be applied to integer data type. Only signed and unsigned can be applied to character data type. Only long can be applied to double data type. Detailed list of data types Keyword used Size in bytes Range Example char signed char 1 -128 to 127 signed char status= ‘u’ int signed int short int signed short int 2 -32767 to 32768 short int num = -12; unsigned int unsigned short int 2 0 to 65535 unsigned short int num = 12; long int signed long int 4 -2147483648 to 2147483647 long int num = -12345678; unsigned long int 4 0 to 4294967295 unsigned long int=1234567890; long double 10 3.4E-4932 to 1.1E+4932 long double population = 123456789.1234567 Q) Explain decision making statements in C.
  • 4. Ans: Many programs require a logical condition to become true for executing a particular statement / group of statements. These statements are known as decision making statements. a) If statement: The if statement is used to control the flow of execution of statements. The syntax and flowchart of is statement is as shown below. Example: /* program to give a discount of Rs.500 if the total amount is above 5000*/ #include <stdio.h> void main() { int amount = 6000; if (amount > 5000) { amount = amount-500; } printf(“Total amount to be paid = %d”,amount); } if-else statement: In if else control statement, group of statements are executed when condition is true. If condition is false, then else part statements are executed. output: Total amount to be paid = 5500
  • 5. Example: #include <stdio.h> int main() { int m=40,n=20; if (m == n) { printf("m and n are equal"); } else { printf("m and n are not equal"); } } Switch statement: The switch makes one selection when there are several choices to be made. The break statement is used inside each case of switch . It causes immediate exit from the switch statement and continue onto the next statement outside the switch statement. When we execute this form of switch statement, first the test expression is evaluated. the value of expression is compared one –by- one, with value-1, value--2 …valuen . When a match is found, the Output: m and n are not equal
  • 6. program executes the following that case. The execution continues till a break statement is found or the switch statement is completed. If there is no match the statements in the default case gets executed. Syntax of switch is as follows Switch(test expression) { case value-1: statementblock-1; break; case value-2: statementblock-2; break; . . default: defaultblock; } Q) Write a c program to perform all arithmetic operations using switch-case. #include<stdio.h> #include<conio.h> void main() { int ch; float a,b,res; clrscr(); printf(“Enter two numbers:”); scanf(“%f%f”,&a,&b); printf(“nMenun1.Additionn2.Subtractionn3.Multiplicationn4.Division”); printf(“nEnter your choice:”); scanf(“%d”,&ch); switch(ch) { case 1: res=a+b; break; case 2: res=a-b; break; case 3: res=a*b; break; case 4: res=a/b; break; default: printf(“Wrong choice!!nPress any key…”); }
  • 7. printf(“nResult=%f”,res); getch(); } Q) Explain hardware components of a computer. Ans: A computer is made up of many parts: •Input/Output (I/O) devices – These allow you to send information to the computer or get information from the computer. •Central Processing Unit – CPU or Processor for short. The brain of a computer. Does all the computation/work for the computer. •Memory –any form of electronic storage is referred to as memory. There are two types of memories. 1. Primary memory 2. Secondary memory Primary memory a) RAM holds data and instructions as long as the program is being processed by the processor. RAM is a volatile memory as data in the RAM is lost when the power is switched off. The cpu can access any other location in memory directly in random manner and hence it is called random access memory. b) ROM: ROM is a non- volatile memory as data in the ROM is not lost when the power is switched off. ROM can also be accessed randomly. Secondary memories are used to store large amounts of data. They are inexpensive than primary memories. They are also non-volatile. A drive is used to read the contents of a hard disk, CD , DVD or a floppy. a) hard disk drive (HDD) Accessing the hard drive for information takes time. b) CD ROM drive– A device used to read CD-ROMs. CD-RW drive is used to read data/ write data from/to CD-RW disks. c) DVD ROM drive – A device that is used to read DVDs. DVD-RW drive is used to read data/ write data from/to DVD-RW disks. c) Floppy Drive – A device that is used to read/write to floppy diskettes. •Motherboard – A circuit board that allows the CPU to interact with other parts of the computer. •Power Supply – Gives your computer power by converting alternating current (AC) supplied by the wall connection to direct current (DC). •Expansion Cards – Used to add/improve functionality to the computer. a. Sound Card – Used to input and output sound under program control. Sound cards provide better sound quality than the built in sound control provided with most computers. b. Graphics Card – Used to convert the logical representation of an image to a signal that can be used as input for a monitor. c. Network Card – Used to provide a computer connection over a network. Transmit data at 10/100/1000 Mb/s. • Fan – Keeps your computer cool. If the inside of your computer becomes too hot, then the computer can overheat and damage parts. • Heatsink – Used to disperse the heat that is produced inside the computer by the CPU and other parts by increasing surface area. • Ports – Means of connecting peripheral devices to your computer.
  • 8. Q) Explain different sections of a C program. (or) Explain the structure of C Ans: Documentation section pre-processor directives global declarations main() { local variables to function main ; statements associated with function main ; } f1() { local variables to function 1 ; statements associated with function 1 ; } f2() { local variables to function f2 ; statements associated with function 2 ; } Preprocessor Directives: It is not possible to write our own output functions every time we wanted to communicate with the computer. So we use header files that have standard functions which can be included in our programs. All pre-processor directives begin with a # and the must written in the beginning of the c program #include <stdio.h> Documentaion section contains a set of comments giving the name of the program, the author and other details which the programmer would like to use later. Comments are non-executable  Single Line Comment Starts with ‘//’ . used to comment out just Single Line in the Code written after //.  Multi line comments starts with /* and ends with */. Multi line comments comment out multiple lines written between /* and */ main() All C programs will consist of at least one function. The only function that has to be present is the function called main. Execution of a C program starts with main(). User Defined Functions Any number of user defined functions can be written. All functions including main() are divided into 2 parts. 1. declaration section 2. statement section declaration section is used to describe the data that will be used in the function. The data declared within a function will be visible only within the function and will be removed from memory once the control goes out of the function. statement section contains the code that manipulates the data to perform a specified task. Global declarations : globally declared variables are accessed through out the program and will be in memory until the program runs. Q)Explain different types of operators in C. Ans:
  • 9. S.no Types of Operators Description 1 Arithmetic operators These are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus 2 Assignment operators (=) These are used to assign values to variables. 3 Relational operators These are used to compare the values of two variables 4 Logical operators These operators are used to perform logical operations on expression. 5 Bit wise operators These operators are used to perform bit operations on variables. 6 Conditional (ternary) operators Conditional operators return one value if condition is true and returns another value if condition is false. 7 Increment/decrement operators These operators are used to either increase or decrease the value of the variable by one. 8 Special operators &, *, sizeof( ) Arithmetic Operators in C: S.no Arithmetic Operators Operation Example 1 + Addition A+B 2 - Subtraction A-B 3 * multiplication A*B 4 / Division A/B 5 % Modulus A%B Assignment operators in C: Operators Example Explanation Simple assignment operator = sum = 10 10 is assigned to variable sum Compound assignment operators (+=, *=, /=, %=, etc.. += sum += 10 This is same as sum = sum + 10 Relational operators in C: S.no Operators Example Description 1 > x > y x is greater than y 2 < x < y x is less than y 3 >= x >= y x is greater than or equal to y 4 <= x <= y x is less than or equal to y 5 == x == y x is equal to y 6 != x != y x is not equal to y Logical operators in C: There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and logical NOT (!). S.no Operators Name Example Description 1 && logical AND (x>5)&&(y<5) It returns true when both conditions are true 2 || logical OR (x>=10)||(y>=10) It returns true when at-least one of the condition is true 3 ! logical NOT ! ((x>5)&&(y<5)) It reverses the state of the operand Bit wise operators in C: Decimal values are converted into binary values and bit wise operators work on these bits. Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR), << (left shift) and >> (right shift). Truth table for bit wise operation Bit wise operators x y x|y x & y x ^ y Operator_symbol Operator_name 0 0 0 0 0 & Bitwise_AND 0 1 1 0 1 | Bitwise OR 1 0 1 0 1 ~ Bitwise_NOT
  • 10. 1 1 1 1 0 ^ XOR << Left Shift >> Right Shift Conditional or ternary operators in C: Conditional operators return one value if condition is true and returns another value is condition is false. This operator is also called as ternary operator. Syntax : (Condition? true_value: false_value); Example : (A > 100 ? 0 : 1);. In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional statements. Increment/decrement Operators Syntax: Increment operator: ++var_name; (or) var_name++; Decrement operator: - - var_name; (or) var_name - -; Example: Increment operator : ++ i ; i ++ ; Decrement operator : - – i ; i – - ; Special Operators in C: Below are some of special operators that C language offers. S.no Operators Description 1 & This is used to get the address of the variable. Example : &a will give address of a. 2 * This is used as pointer to a variable. Example : * a where, * is pointer to the variable a. 3 Sizeof () This gives the size of the variable. Example : size of (char) will give us 1. Q) Write a program to find biggest among three numbers. #include <stdio.h> void main() { float a, b, c; printf("Enter three numbers: "); scanf("%f %f %f", &a, &b, &c); if(a>b && a>c) printf("Largest number = %f", a); else if(b>c) printf("Largest number = %f", b); else printf("Largest number = %f", c); } Q)Explain about the looping making statements in C. loop control statements : repeatedly executes a statement/ block of statements as long as a given condition is true. Control comes out of the loop statements once condition becomes false. Output: Enter three numbers:3 4 5 Largest number = 5
  • 11. Types of loop control statements in C: There are 3 types of loop control statements in C language. They are, 1. for 2. while 3. do while While loop: /* Program to print the natural numbers from 1 to 5 using while loop*/ #include <stdio.h> void main() { int i=1; while(i < 5) { printf(“%dn”,i); i++; } } Do while loop: /* Program to print the natural numbers from 1 to 5 using do - while loop*/ #include <stdio.h> void main() { int i=1; do { printf(“%dn”,i); i++; } while(i < 5); } For loop: /* Program to print the natural numbers from 1 to 10 using for loop*/ #include <stdio.h> void main() { Syntax of do while loop is as follows: do { statements; } while (condition); The syntax of while loop is as follows: while(condition) { statement(s); } Syntax of for loop is as follows: for (exp1; exp2; expr3) { statements; } Where, exp1 – variable initialization ( Example: i=0, j=2, k=3 ) exp2 – condition checking ( Example: i>5, j<3, k=3 ) exp3 – increment/decrement ( Example: ++i, j–, ++k )
  • 12. int i; for(i=1;i < 5;i++) { printf(“%dn”,i); } } Output: 1 2 3 4 5 Q) Whys is clrscr() used? clrscr() will clear the output of previous execution. It is defined in conio.h header file. Q) Explain about the execution of c program. Source code is the program written by user. ex: factorial.c Compiler converts the c program into machine level language Object code ex: factorial.obj LinkerObject code of header files included Ex: stdio.h Executable ex: factorial.exe
  • 13.
  • 14. main() { int x, y; y= f1(x); ……. } int f1(int z) { …… return z; } Functions Definition: Functions are self contained and independent block of statements. C allows a big program to be divided into segments known as functions. Need for functions 1. Code reuse. 2. Dividing a program into functions allows each function to be tested separately. 3. A large program may not fit in main memory. Using Functions While using functions we use the following terminology 1. If a function f() uses another function g(). f() is called calling function and g() is called called function 2. Function call When a function is called, the compiler jumps to the called function to execute the statements of called function. When the called function is executed, the program control passes back to the calling function Here main() is calling function and f1() is called function 3. Inputs given to function are called parameters / arguments. Arguments are 2 types i) Actual arguments: arguments given in function call. Here x is actual argument ii) Formal arguments : arguments given in function definition. Here z is called formal argument. 4. Return statement: return statement terminates the execution of a function and returns the control to the calling function. 5. Function declaration/ Function prototype Before using function, the compiler must know about its return type and number and type of arguments the function takes Syntax: return_type function_name (datatype variable1…..); 6. Function definition When a function is defined space is allocated for that function in memory A function definition consists of i) Function header : Syntax: return_type function_name (datatype variable1…..) ii) Function body : contains code to perform specific task Passing arguments to functions Arguments can be passed by calling function in 2 ways 1. Call by value: In this method, the called function creates new variables and copies the values of arguments passed to it. If the values of arguments are modified, the modified values can be sent to caller using return statement. Advantages: variables, literals (Ex: 6), expressions (x+1) can be passed using call by value Disadvantage: copying arguments requires more memory and takes lot of time. f1() { ….. ….. }
  • 15. 2. Call by reference : In this method, the function receives address of the arguments. Changes made to arguments in called function will also change the values in calling function Advantages: A function can return only one value. To return multiple values, call by reference is used /* swapping using call by value */ void swap(int , int); void main() { int a ,b; clrscr(); printf(“enter two numbers”); scanf(“%d%d”, &a,&b); printf(“values before swapping = %d t%d”, a, b); swap(a,b); getch(); } void swap ( int x, int y) { int temp; temp =x; x=y; y=temp; printf(“values after swapping = %dt %d”, x, y); } /* swapping using call by reference */ void swap(int *, int *); void main() { int a ,b; clrscr(); printf(“enter two numbers”); scanf(“%d%d”, &a,&b); printf(“values before swapping = %d t %d”, a, b); swap(&a,&b); getch(); } void swap ( int *x, int *y) { int temp; temp =*x; *x=*y; *y=temp; printf(“values after swapping = %d t %d”, *x, *y); } Types of functions: There are 2 types of functions 1. Built in / pre-defined functions: these are stored as library files. Ex: printf, scanf, abs(), strlen() 2. User defined functions: these functions are defined by the user with his own logic. Ex: main(), factorial() Categories of functions 1. Functions with arguments and with return type 2. Functions with arguments and without return type 3. Functions without arguments and without return type 4. Functions without arguments and with return type Recursion Recursive function is a function that calls itself. Every recursive function must have an exit condition/ terminating condition / stop condition. If not, recursive function will call itself indefinitely. When the problem can be defined in recursive manner, then recursion can be used. Advantages: 1. Recursive solutions are shorter and simpler than non- recursive solutions. 2. Code is clearer and easier to use. 3. Follows divide and conquer to solve problems Disadvantages:
  • 16. 1. Recursion is difficult concept to some programmers 2. Recursion uses system stack. If the system stack is limited, it is difficult to implement recursion 3. uses more memory and time to execute 4. it is difficult to find errors. Example: 1 if a=1 factorial(a) = a*factorial(a-1) if a > 1 Types of Recursion 1. Direct recursion: a function is said to be directly recursive if it is explicitly calls itself. 2. Indirect Recursion: a function is said to be indirectly recursive if it calls another function which ultimately calls it. 3. Tail Recursion: if no operations are pending to be performed when the recursive function returns to its caller. 4. Linear Recursion: when the pending operation (if any) does not make another recursive call to the function 5. Non linear / Tree recursion: when the pending operation makes another recursive call to the function Scope of a variable Scope is accessibility and visibility of the variables. Variables in C has 4 types of scope 1. block scope: a statement block is a group of statements enclosing within { and }. If a variable is declared within a statement block , as soon as control exits the block, the variable will be removed from memory. Such a variable is said to have block scope. 2. function scope: variable is accessible and visible from the beginning to end of a function 3. program scope: variable is accessible and visible from the beginning to end of a program 4. file scope: variable is accessible and visible from the beginning to end of a file Storage Classes The storage class defines scope (visibility) and lifetime of variable and functions declared within a C program. The storage class will determine 1. where the variable will be allocated memory ( in register or main memory etc...) 2. how long the variable stays in memory (life time ) 3. scope of the variable i.e, the part of C program in which the variable is accessible or visible. 4. whether the variable will be automatically initialized or not. C supports 4 storage classes.
  • 17. 1. automatic 2. register 3. external 4. static Comparison of storage classes Feature Storage class auto extern register static Accessibility Within function or block in which it is declared Within all program files that are part of a program Within function or block in which it is declared Local: Within function or block in which it is declared Global: Within the program in which it is declared Storage Main memory Main memory CPU register Main memory Existence Exists in memory as long as the control is within the block or function in which it is declared. Once the control returns from function or block, it is removed from memory Exists through out the execution of the program Exists in memory as long as the control is within the block or function in which it is declared. Once the control returns from function or block, it is removed from memory Local: Exists through out the execution of the program Global: Exists through out the execution of the program files Default Value Garbage Garbage Garbage zero Array: It is collection of similar data type elements. All Elements of array are stored in contiguous memory locations. Declaration of Arrays: An array can be declared by specifying 3 things 1. Data type: what kind of values it can store Ex: int , char , float etc.. 2. Name: to identify the array 3. Size: the maximum number of values the array can hold Syntax: type name[size] Example: int marks[3]; marks is an array of integer type and it can hold maximum 3 elements. marks is pointer that holds the address of first element (&marks[0]) Initialization of array (or) storing values in arrays All Elements of array are stored in contiguous memory locations. Memory location addresses 1000 1002 1004 95 96 97 marks[0] marks[1] marks[2]
  • 18. 1. Initialization at the time of declaration int marks[3] = { 95,96,97} Here since marks stores integer values. Each element in array requires 2 bytes. If marks[0] is stored at memory location 1000 then second element (marks[1]) is stored at memory location 1002 and so on. 2. Taking values of all the array elements (marks[0], marks [1], marks[2]) from user Ex: for(i=0;i<3;i++) { printf (“enter marks of student no. %d”,i); scanf(“%d”,&marks[i]; } 3. Giving values to individual elements marks[0] = 95; marks[1] = 96; marks[2] = 97; We can change the marks of individual elements using the above method. In marks[2] data element, 2 is the index or subscript. It is the (index+1) i.e, 5th element in the array marks as index starts with zero in arrays. Displaying the elements of an array for(i=0;i<5;i++) { printf (“%d”, marks[i]); } Operations that can be performed on arrays 1. Traversal: acessing every element of array 2. Insertion : inserting a new element 3. Deletion: deleting existing element 4. Merging: merge 2 arrays 5. Search : search for a value in an array 6. Sorting : arrange the values in array in either ascending or descending order. Types of arrays: 1. One dimensional arrays (1D) 2. Two dimensional arrays (2D) 3. Multi dimensional arrays (3D) 1. 1D array is represented using one index ‘[ ]’ .It is mostly used for searching and sorting 2. 2D array is represented using two indexes ‘[][]’. One subscript denotes rows and other denotes columns. It is mostly used for matrix representation. Example: int marks[3][3]; (3 rows and 3 columns) 3. Multi dimensional arrays have more than 2 indices. Example: int m[3][2][2] m is an array of three 2D arrays. Program to read and print the values of 1D array Find the sum of the elements of an array void main()
  • 19. void main() { int marks[5], i; clrscr(); printf(“Enter marks of 5 students”); for (i=0;i<5;i++) { scanf(“%d”,&marks[i]); printf(“n marks = %d”, marks[i]); } getch(); } { int marks[5], i, sum; clrscr(); sum=0; printf(“Enter marks of 5 students”); for (i=0;i<5;i++) { scanf(“%d”,&marks[i]); sum = sum+ marks[i]; } printf(“sum = %d”, sum); getch(); } Search an element in an array using linear search void main() { int a [10], i, n, s, flag = 0; printf(“Enter the number of elements”); scanf(“%d”, &n); printf (“enter %d elements”,n); for (i=0;i<n;i++) { scanf(“%d”,&a[i]); } printf(“enter the search element”); scanf(“%d”, &s); for (i=0;i<n;i++) { if ( s == a[i]) { flag = 1; break; } } if( flag = = 1) printf(“Element found”); else printf(“Element not found”); getch(); } Search an element in an array using binary search void main() { int a [10], i, n, s, left, right, mid, flag=0; printf(“Enter the number of elements”); scanf(“%d”, &n); printf (“enter %d elements”,n); for (i=0;i<n;i++) { scanf(“%d”,&a[i]); } printf(“enter the search element”); scanf(“%d”, &s); left=0; right=n-1; mid = (left+right)/2; while (left < = right) { if ( s = = a[mid]) flag =1; else if ( s< a[mid]) right = mid-1; else left = mid+1; mid = (left+right)/2; } if( flag = = 1) printf(“Element found”); else printf(“Element not found”); getch(); } Program to sort the given elements using bubble sort. #include <stdio.h> #include <conio.h> Program to read and print values of 2D array #include <stdio.h> #include <conio.h>
  • 20. void main() { int a [10], i, n, j, t; printf(“Enter the number of elements”); scanf(“%d”, &n); for (i=0;i<n;i++) scanf(“%d”,&a[i]); for ( i=0; i< n; i++) { for ( j = i+1; j < = n; j++) { if( a[i] > a[j]) { t= a[i]; a[i]=a[j]; a[j]=t; } } } printf(“n sorted array”); for (i =0; i< n; i++) printf(“%5d”, a[i]; getch(); } void main() { int a[5][5],i,j,r,c; clrscr(); printf(“enter the order of matrix”); scanf(“%d %d”, &r,&c); printf(“Enter %d elements”, r*c); for(i=0; i<0r;i++) for(j=0; j<c;j++) scanf(“%d”, &a[i][j]); for(i=0; i<r;i++) { for(j=0; j<c;j++) printf(“%3d”, a[i][j]); printf(“n”); } getch(); } Two dimensional Arrays Declaration: Syntax: data_type name [row_size][column_size]; Example: int marks[3][2]; marks is a 2D array that can store 3*2 = 6 elements. (row_size * column_size) Initialization of 2D array 1. Initialization at the time of declaration int marks[3][2] ={ 80,81,82,83,84,85}; (or) int marks[3][2] = {{80,81},{82,83},{84,85}}; 2. Giving values to individual elements marks[0][0]=80; marks[0][1]=81; marks[1][0]=82; marks[1][1]=83; marks[2][0]=84; marks[2][1]=85; 3. Taking values of all array elements from user for(i=0; i<3;i++) for(j=0; j<2;j++) scanf(“%d”, &marks[i][j]); memory addresses 1004 1008 1010 1012 1014 1016 80 81 82 83 84 85
  • 21. One dimensional arrays One dimensional arrays Passing entire array Passing data values Passing addresses marks[0][0] marks[0][1] marks[1][0] marks[1][1] marks[2][0] marks[2][1] marks[0] marks[1] marks[2] The two dimensional matrix marks is an array of three 1D arrays (marks[0], marks[1] marks[2]) Arrays and Functions 1. 1D arrays and passing them as arguments to functions can be as shown in the diagram below Passing entire array to function When entire array is passed to function, they are always passed by address. In arrays there is no call by value and there is only call by reference. When the address of array is passed there is no way the function will come to know about the size of the array. so size of the array must also be passed. Example: int soe(int *, int ); void main() { int marks[3] = {65,67,69}; int sum; sum = soe(&marks[0], 3); printf(“sum of elements in array =%d”,sum); } int soe(int *b, int size) { int i, s=0; for ( i=0; i< size, i++) s=s+(*(b+i)); return s; } Note: marks (or) &marks[0] (or) (marks + 0) are the same &marks[1] (or) (marks+1) are same marks[0] (or) *(marks+0) are the same. /* program to perform matrix multiplication */ #include <stdlib.h> void main() { int a[10][10], b[10][10], c[10][10], r1,c1,r2,c2, i,j,k; clrscr(); printf(“enter the order of matrix A”); scanf(“%d%d”,&r1,&c1); printf(“enter the order of matrix B”); scanf(“%d%d”,&r2,&c2);
  • 22. printf(“enter the elements of matrix A”); for (i = 0; i< r1; i++) for (j=0; j<c1; j++) scanf(“%d”, &a[i][j]); printf(“enter the elements of matrix B”); for (i = 0; i< r2; i++) for (j=0; j<c2; j++) scanf(“%d”, &b[i][j]); if(r1 != c2) { printf(“n multiplication is not possible”); exit(0); } else { for(i=0; i<r1; i++) { for (j=0; j<c2; j++) { c[i][j]=0; for(k=0; k<c1; k++) c[i][j] = c[i][j]+ a[i][k]* b[k][j]; } } } printf(“the resultant matrix isn”); for(i=0; i<r1;i++) { for(j=0; j<c2;j++) printf(“%dt”, c[i][j]); printf(“n”); } } STRINGS A String in C is defined to be a sequence of characters terminated by null character ‘0’. The null character indicates the end of a string. Declaration of Array of char type: Syntax: char string_name[size]; Example: char str[20]; str is string name 20 is the size of string.
  • 23. Example 2: char str[10]=”COMPUTER”; C O M P U T E R 0 str [0] str [1] str [2] str [3] str [4] str [5] str [6] str [7] str [8] Initialization of arrays of char type: Type 1: char str[6]={‘H’,’E’,’L’,’L’,’O’,’0’}; Type 2: char str[6]=”HELLO”; Write a program to read and write strings using scanf and printf #include <stdio.h> void main() { char str[10]; printf(“Enter a string”); scanf(“%s”, &str); printf(“You entered %s”,str); } String Input/ Output Functions 1. Reading Strings Strings can be read from user by using 3 ways 1. using scanf function 2. using gets() function 3. using getchar(), getch() and getche() functions The main drawback of scanf() function is that it teminates as soon as it finds a blank space. So, we can use gets() function which takes blank spaces . getchar(), getch() and getche() functions read only single characters and has to call them repeatedly to read a string. 2. Writing Strings Strings can be displayed using three ways 1. using printf() function 2. using puts() function 3. using putchar() function repeatedly Summary of functions to read and write a single character Function Operation Usage getchar() Used to read a character from keyboard and waits for ENTER or TAB or ESC key to be pressed char s = getchar(); getch() Reads a character from keyboard and returns immediately and does not wait for ENTER key to be pressed. It does not display the character entered by user char s = getch(); getche() Reads a character from keyboard and returns immediately and does not wait for ENTER key to be pressed. It displays the character entered by user char s = getche(); putchar() Writes a character to screen putchar(s) Write a program to read and write strings using puts() and gets() Output: Enter a string mpcs student. You entered mpcs
  • 24. void main() { char str[20]; puts("Enter a string"); gets(str); puts(str); } String manipulation functions The string library functions which are in the header file “string.h” The most commonly performed operations are 1. Finding the length of the string – strlen() 2. Copying one string to another string – strcpy() 3. Comparing two string --- strcmp() 4. Concatenation of two strings --- strcat() 5. Reverse the given string-- strrev() 6. Convert the input string to lower case strlwr() 7. Convert the input string to upper case strupr() 1. Finding the length strlen() is used to find the number of characters in a string excluding the null character Usage: int length = strlen(string) Write a program to find the length of a string #include <string.h> void main() { char str[10]; int len; printf(“enter a string”); scanf(“%s”, &str); len = strlen(str); printf(“You entered %s”,str); printf(“length of the string is %d”,len); } 2. copying one string to another string Usage: strcpy(string1, string2); This function copies the string2 to string 1 including the null character. The contents if any in string1 will be lost. #include <string.h> void main() { char str1[50],str2[50]; clrscr(); printf("enter a string"); gets(str2); strcpy(str1,str2); printf(“copied string in str1 is %s”,str1); } 3. strcmp() is used to compare two strings Output: Enter a string computers You entered computers Length of the string is 9 Output: Enter a string mpcs copied string in str1 is mpcs
  • 25. Usage: int ret = strcmp( string1, string2) This function return values as follows: • returns < 0 if str1 is less than str2. • returns > 0 if str2 is less than str1. • returns = 0 if str1 is equal to str2. Write a program to compare two strings #include <string.h> void main() { char str1[50],str2[50]; int ret; clrscr(); printf("enter first string"); gets(str1); printf("enter second string"); gets(str2); ret = strcmp(str1,str2); if (ret == 0) printf(“the two strings are equal”); else printf(“the two strings are not equal”); } 4. Concatenation of two strings The strcat() function appends the string2 to the end of the string1. The null character in string1 is overwritten. The process stops when null character of string2 is copied. String1 must be big enough to store the contents of string1 and string2. Usage: strcat(string1, string2) Write a program to concatenate two strings #include <string.h> void main() { char str1[50],str2[50]; clrscr(); printf("enter first string"); gets(str1); printf("enter second string"); gets(str2); strcat(str1,str2); printf(“string1 =%s”,str1); } 5. Reverse the input string #include <string.h> void main() { char str1[50],str2[50]; clrscr(); printf("enter a string "); gets(str1); printf(“reverse =%s”, strrev(str1)); Output: Enter first string mpcs Enter second string mecs the two strings are not equal Output: Enter first string mpcs Enter second string First year String1 = mpcs First year Output: enter a string mpcs reverse = scpm
  • 26. } 6. Convert the input string into lower case #include <string.h> void main() { char str1[50],str2[50]; clrscr(); printf("enter a string in capital letter "); gets(str1); printf(“lowercase =%s”, strlwr(str1)); } 7. Convert the input string into uppercase #include <string.h> void main() { char str1[50],str2[50]; clrscr(); printf("enter a string in lower case "); gets(str1); printf(“upper case =%s”, strupr(str1)); } ARRAYS OF STRINGS An array of string is declared as char names[5][30]; First index indicates how many strings are needed and Second index indicates the length of every individual string. char names[3][30] = {“RAM”,”SHYAM”,”SAI”}; 3 names and each name can consist of maximum of 30 characters . Memory representation of 2D array names[0] R A M 0 names[1] S H Y A M 0 names[2] S A I 0 Write a program to print names of n students of a class void main() { char names[10][30]; int i, n; clrscr(); puts(“Enter the number of studentsn”); scanf(“%d”, &n); printf(“enter names of %d students”, n); for ( i = 0; i<n;i++) { scanf(“%s”,names[i]); } for ( i = 0; i<n;i++) { puts(names[i]); } Output: Enter the number of students 2 Enter names of 2 students sita gita sita gita Output: enter a string MPCS lowercase = mpcs Output: enter a string in lower case mpcs uppercase = MPCS
  • 27. } UNIT – VI Pointers Pointer Variables When a variable is declared some amount of memory is allocated to hold the value of that variable. The size of memory allocated depends on the datatype of the variable. Each memory location has an address. pointer is a variable that stores the address of another variable. Applications of pointers 1. pointers are used to pass arrays and strings as function arguments. 2. using pointers one can pass functions as arguments to another function 3. pointers are used to create complex data structures like trees, stack, queues etc.. 4. pointers are used for dynamic memory allocation Declaring and initializing Pointers Example 1: int x = 6000; int *ptr1; ptr1=&x; ptr1 will store the starting address (here 100) and will read 2 bytes as it points to a integer variable when dereferenced using *ptr1. Example2: float sal = 100000.0; float *ptr2; ptr2=&sal; ptr1 and ptr2 occupy same amount of memory. Memory enough to store the address of a memory location. The datatype of pointer indicate that they contain the address of a variable of that datatype. Indirection operator (or) Value at Address operator (*) When * is used as unary operator after the pointer variable other than at the declaration of pointer variable, then * is called indirection operator. void main() { int x= 6000, *ptr; ptr = &x; printf(“%d”, *ptr); } The above program will print 6000 on the screen. * operator deferences a pointer and will display the value present at the address stored in pointer. printf (“%d”, *(&x) ; will also prints 6000 on the screen. Hence *ptr (or) x (or) *(&x) are same. Addresses 10 0 10 1 10 2 10 3 104 105 6000 100 x ptr1 Addresses 10 6 10 7 10 8 10 9 11 0 111 100000.0 106 sal ptr2
  • 28. ptr (or) &x are same. Write a program to declare and access pointer variable void main() { int x = 6000, *ptr; ptr = &x; printf(“ value of x = %d”,x); printf(“ value of x = %d”,*ptr); printf(“ value of x = %d”,*(&x)); printf (“address of x = %u”, ptr); printf (“address of x = %u”, &x); } Generic pointers It is a pointer variable that has void as its data type. Generic pointer can be used to point to variables of any data type. Ex: void *ptr; Pointers and arrays Example: int marks[10], *ptr ; ptr = marks; The array name marks holds the starting address of the array i.e, &marks[0] Write a program to print the elements of array using pointers void main() { int marks[3] = { 1,2, 3}, *ptr,i=0 ; ptr=&marks[0]; printf(“elements in an array are”); while( i<3) { printf(“%dt”, *ptr); ptr++; } Write a program to pass string as arguments to functions using pointers void print(char *); void main() { char str[20]=”HELLO”; print(str); } void print( char *c) { while(*c != 0) { printf(“%c”, *c); c++; } } Understanding Computer memory Memory allocated to a Program or application is divided into 4 segments. 1. Code -- contains instructions Output: HELLO
  • 29. 2. Static/ Global memory --stores static and global variable that have program lifetime 3. Stack memory 4. Heap memory. A fixed size Stack is allocated by the system and the stack is filled from bottom to top. Also the last element added to stack is removed first (hence it is called LIFO data structure). All the variables declared within main() are allocated space on stack. All the parameters passed to called function are also stored on stack. Stack is faster, smaller and expensive than HEAP memory. A fixed size HEAP is allocated by the system and is used when need arises in random fashion. what is static memory and dynamic memory allocation? 1. Static memory allocation: The process of allocating memory to program at compile time is known as static memory allocation. This memory cannot be changed during the execution of program. Example : stack and global memory when a program is executed, certain amout of memory from stack is taken and allocated for main() method. This is called stack frame. Similarly stack frame is created for each function called above the main()'s stack frame. when a function is called, it is pushed onto the stack. when control returns from function, it is popped from stack. Whatever is on the top of the stack is executing. At the time of program compilation itself, the amout of memory to be allocated for each function's stack frame is decided by the compiler and do not change. Hence it is called Static allocation. 2. Dynamic memory allocation: The process of allocating memory to the variables during program execution or at run time is known as dynamic memory allocation. Example : heap memory. If you want memory to be kept as long as you want, instead of getting cleared automatically when popped from stack, we use dynamic memory. In C, dynamic memory allocation is done using 1. malloc 2.calloc 3. realloc Dynamic memory deallocation is done using free 1. malloc returns a void pointer that has address of first byte of block of memory allocated on heap , so we typecast as shown below ex: The below code allocates memory for 20 integers on heap int *p; p= (int *) malloc(20*sizeof(int)); 2. free(p); is used to deallocate the memory. 3. calloc is same as malloc except i. it takes 2 arguments. For ex: p=(int *)calloc(20, sizeof(int)); ii. it initializes all the memory allocated on heap to 'zero' 4. realloc is used to change the amout of memory previously allocated on heap syntax: void * realloc(void * ptr, size_t size) ptr is pointer to existing block size is the size of new block size_t is data type that has only positive values For ex: unsigned integer. Structures
  • 30. A structure is a user defined data type. A structure stores related information. Structure is collection of variables of DIFFERENT data types. Declaring structures A structure is declared using struct keyword followed by structure name. All variables of structure are declared within structure and each variable is called member of the structure. Memory is not allocated when the structure is declared. Example: struct student { int roll_no; char name[10]; int marks; }s1; Structure initializations Structures can be initialized in 3ways 1) 2) 3) 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  • 31. struct book { char title[20]; char author[40]; int price; }b1 ={“ANSI C”,”swamy”,350}; struct book { char title[20]; char author[40]; int price; }; struct book b1 ={“ANSI C”,”swamy”,350}; struct book b1,b2,b3; b1.title=”ANSI C”; b1.author=”guru swamy”; b1.price=350; b2.title=” C”; b2.author=”reema”; b2.price=450; Accessing the members of structure A structure variable is accessed using a ‘.’ operator. Write a program to print the details of 2 students such as rollno, name, course and fees. #include <string.h> void main() { struct student { int roll; char name[40], course[10]; }; struct student s1={151301, “adi”,”IMPCS”}; struct student s2; s2.roll=151302; strcpy(s2.name,”naik”); strcpy(s2.course,”IMPCS”); printf(“rollno = %d t name=%s t course=%s n”, s1.roll, s1.name, s1.course); printf(“rollno = %d t name=%s t course=%s n”, s2.roll, s2.name, s2.course); } typedef By using typedef keyword an alternate name is given to existing data type. When we precede a struct name with typedef keyword then the struct becomes a new data type. write a program to create a user defined data type date
  • 32. #include <string.h> typedef struct date { int dd; int mm; int yy; }; void main() { date d1 = {1,9,2015}; printf(“today’s date = %d - %d - %d”, d1.dd, d1.mm, d1.yy); } Now that we have added typedef keyword before structure name date, date becomes new data type. Therefore, we can define variable of type date by writing just date d1,d2,d3; Copying and comparing structures We can assign a structure variable to another structure variable of same type. Example: struct student s1={151301, “adi”,”IMPCS”,18000}; struct student s2; s2=s1; C does not allow comparing of two structure variable however; individual elements of one structure can be compared with individual elements of another structure. Nested Structures A structure can be placed within another structure. That is, a structure may contain another structure as its member. Such a structure is called a nested structure. #include <stdio.h> typedef struct date { int dd; int mm; int yy; }; typedef struct student { char name[40]; date dob; }; main() { student s1; printf("enter name and date, month and year of birth of studentn"); scanf("%s %d %d %d", &s1.name, &s1.dob.dd, &s1.dob.mm, &s1.dob.yy); printf("name =%s t date of birth =%d - %d - %d", s1.name, s1.dob.dd, s1.dob.mm, s1.dob.yy);
  • 33. } Arrays of structures Example: student st[30]; To assign values to ith student, you should write st[i].name = “ xyz”; st[i].dob.dd = 21; st[i].dob.mm=12; st[i].dob.yy=1991; Self referential Structures contains a pointer to data that is of same type as that of the structure. example: struct node { int val; struct node *next; } Here the structure node will contain 2 types of data- an integer val and next, which is pointer to a node. Structures and Functions A structure can be passed to a function in 3 ways 1. Passing individual members 2. Passing the entire structure 3. Passing the address of the structure. Difference between structure and unions Structure Union It is collection of variables of different data type Structure is declared using struct keyword struct structure_name { datatype var1; datatype var2; }object; It is collection of variables of different data type Union is declared using union keyword union name { datatype var1; datatype var2; }object; Each member within a structure is allocated unique memory. A common memory of size equal to largest member size is allocated. Each member
  • 34. struct book { char title[20]; char author[40]; int price; }b1 ; Memory allocated for b1 = 64 bytes 20 bytes for title variable + 40 bytes for author variable+ 2 bytes for price variable+ 2 bytes padding within union share the common memory. union book { char title[20]; char author[40]; int price; }b1 ; Memory allocated for b1 = 40 bytes Size of structure is >= sum of sizes of its members Size of union is equal to its largest member size All the members can be assigned values at a time. Only one member can be assigned value at a time All the members can be accessed at same time Only one member can be accessed at a time Values assigned to one member will not cause the change in other members. Values assigned to one member may cause change in values of other members. Enumerated Data types Enumerated data types is a user defined type. Keyword enum is used to defined enumerated data type. Enumerated data type consists of integral constants and each integral constant is given a name. Example: enum month {JAN =1 ,FEB=2,MAR=3,APR=4,MAY=5,JUN=6,JUL=7,AUG=8,SEP=9,OCT=10, NOV=11,DEC=12}; A user defined data type month is created. It has 12 values as given in pair of braces. enum month rmonth; “rmonth” variable is declared of type “month” which can be initialized with any data value amongst 12 values”. Files File is a collection of records stored in secondary memory such as hard disk. Record is collection of fields and each field can carry a value. Stream is a logical interface. Stream can be attached to any device to communicate with that device. The device can be logical file or physical keyboard.
  • 35. There are 3 standard streams in C language 1. standard input (stdin)----------- stream from which the program receives data. 2. standard output (stdout) ------- stream to which the program writes the data. 3. standard error (std err) ---------- stream to which the program writes the error messages. stdin, stdout and stderr are the logical names given to these streams. By default Standard input is connected to keyboard. Standard output and Standard error are connected to monitor. Buffer: When a stream is linked to a disk file, a buffer is automatically created. Buffer is block of memory used for temporary storage of data. Buffers are needed as the disk drives are block oriented. Types of Files There are 2 types of files. 1. ASCII text files 2. Binary files. 1. ASCII text file is a stream of characters that can be sequentially processed by a computer. In a text file, each line of data ends with a new line character (n). Each file ends with a special character (EOF) marker Example: Integer vaue 123 will be stored as a sequence of 3 characters. And so requires 3 bytes to store int value will be represented as 2 bytes of memory internally, but externally the int value will be represented as a string of characters. To convert internal representation into external, we use printf and fprintf functions. To convert external representation to internal representation, scanf and fscanf functions are used. 2. Binary files may contains any type of data encoded in binary form. A binary file does not require any special processing. Binary files can be processed sequentially or randomly. Integer vaue 123 will be stored in 2 bytes . Using files in C To use files in C, we must follow the below steps 1. Declare a FILE pointer variable 2. Open the file (fopen) 3. Process the file 4. Close the file. Declaring a file pointer variable. A file pointer variable that points to a structure FILE has to be declared as fopen functions return a FILE pointer. Syntax: FILE filepointer_variable; Ex: FILE *fp; Opening a file a file must be opened before data can be read and write. fopen() function is used to open the file. Syntax: filepointer_variable = fopen(“filepath”,”mode”); ex: fp = fopen(“myfile.txt”, “r”);
  • 36. File modes: mode Description "r" Opens a file for reading. The file must exist. "w" Creates an empty file for writing. If a file with the same name already exists, its contents are erased "a" Appends data at the end of the file. The file is created if it does not exist. "r+" Opens a file for reading and writing. The file must exist. "w+" Creates an empty file for both reading and writing. "a+" Opens a file for reading and appending. note: the modes that can be used with binary files are rb,wb,ab, rb+,wb+,ab+ closing a file: The C library function fclose closes the stream. All buffers are flushed. syntax: fclose(filepointer_variable); Example: fclose(fp); Write a program to read student details from a file and display the details #include <stdlib.h> void main() { FILE *fp; char name[40]; int roll; fp = fopen("student.txt","r"); if( fp == NULL) { printf("file cannot be opened"); exit(0); } printf("enter rollno and name"); fscanf(fp,"%d%s", &roll,&name); printf("n Roll no = %d t name = %s",roll, name); fclose(fp); } Reading data from files C provides the following set of functions to read data from a file. Function name Description Example fscanf() fscanf reads formatted input from a stream. fgets() fgets reads a line from the stream and stores it into the string pointed to by str. char str[60]; if( fgets (str, 60, fp)!
  • 37. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first. =NULL ) { /* writing content to stdout */ puts(str); } fgetc() gets the next character from the stream and advances the position indicator for the stream do { c = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", c); }while(1); fread() fread function reads data from the given stream into the array pointed to, by ptr. char c[] = "this is c program"; char buffer[100]; fp = fopen("file.txt", "w+"); /* Write data to the file */ fwrite(c, strlen(c) + 1, 1, fp); /* Seek to the beginning of the file */
  • 38. fseek(fp, SEEK_SET, 0); /* Read and from file */ fread(buffer, strlen(c)+1, 1, fp); writing data to files 1. fprintf() 2. fputs() 3.fputc() 4. fwrite()