computer c language
computer c language
Page: 1
3. Write an algorithm and flow chart for exchange (interchange) of values in Two Variables
Flow chart
Algorithm
Start
XNumber
Num[1…X]Val 1,Val 2,….Val X
Algorithm
Sum0
1. Initialize variable X with how many numbers you want to add
No
End
Page: 2
5. Write an algorithm and flow chart for find the factorial of a numbers
Start
Algorithm
NNumber
1. Initialize variable N with a number. F0
No
End
Start
Algorithm NNumber
F10, F21
1. Read the N value
Display F1,F2 values
2. Initialize the first two Fibonacci numbers to F1, F2.
No
End
Page: 3
7. Write an algorithm and flow chart for reverse the digits in a number
Start
NNumber
Algorithm X0
1. Read a number to N
RN % 10
2. Initialize variable X with 0. NN / 10
5. Repeat the steps 3rd and 4th until the N value is reached to 0 Yes
N is not 0
6. Display the X value (Reversed digits)
No
Display the X value
End
Algorithm Flowchart
o A method of representing the step-by-step o Flowchart is a diagrammatic representation of
logical procedure for solving a problem. an algorithm. It is constructed using different
o It contains step-by-step English types of boxes and symbols.
descriptions, each step representing a o The flowchart employs a series of blocks and
particular operation leading to a solution of arrows, each of which represents a particular
a problem. step in an algorithm.
o These are particularly useful for small o These are useful for detailed representations of
problems. complicated programs.
o For complex programs, nobody prefers o For complex programs, everybody prefers
algorithms. Flowcharts.
Pseudo code: It is a simple way of writing programming code in English. Pseudo code is not actual
programming language. It uses short phrases to write code for programs before you actually create it in
a specific language.
Examples of Pseudo code: Let's review an example of pseudo code to create a program to add 2
numbers together and then display the result.
Start Program
Enter two numbers, A, B
Add the numbers together
Print Sum
End Program
Page: 4
10. Briefly discuss about Programming Languages.
Programming language: A programming language is a set of commands, instructions, and syntax use
to create a software program. Languages that programmers use to write code are called "high-level
languages." This code can be compiled into a "low-level language," which is recognized directly by the
computer hardware.
Generations of programming language: Programming languages have been developed over the years
in a phased manner. Each phase of developed has made the programming language more user-friendly,
easier to use and more powerful. Each phase of improved made in the development of the programming
languages can be referred to as a generation. There are five generation of Programming languages.
They are:
1. First generation languages (1GL)
2. Second generation languages (2GL)
3. Third generation languages (3GL)
4. Fourth generation languages (4GL)
5. Fifth generation languages (5GL)
1. First Generation Language (Machine language): The first generation programming language is
also called low-level programming language. In the machine language, a programmer only deals with a
binary number.
2. Second Generation language (Assembly Language): The second generation programming language
also belongs to the category of low-level- programming language. The second generation language
consists of assembly languages that use the mnemonics for the writing program.
3. Third Generation languages (High-Level Languages): The languages of the third and later
generation are considered as a high-level language because they enable the programmer to concentrate
only on the logic of the programs without considering the internal architecture of the computer system.
Examples: C, C++, Java, JavaScript, and Visual Basic…
4. Fourth generation language (Very High-level Languages): The languages of this generation were
considered as very high-level programming languages required a lot of time and effort that affected the
productivity of a programmer. The fourth generation programming languages were designed and
developed to reduce the time, cost and effort needed to develop different types of software applications.
Examples: SQL, CSS, ColdFusion, Perl, PHP, Python, Ruby….
5. Fifth generation language (Artificial Intelligence Language): Programming languages of this
generation are containing visual tools to help develop a program.
Examples: Mercury, OPS5, Prolog…
Page: 5
11. Write about structured programming languages.
The structured programming language allows a programmer to code a program by dividing
the whole program into smaller units or modules. Structured programming is not suitable for the
development of large programs. It is aimed to improving the quality, clarity, and use of subroutines,
block structures, for and while loops.
This model follows the top-down approach. Some of the programming languages initially used
for structured programming such as C, C++, C#, PHP, Ruby, PERL, ALGOL, Pascal, PL/I and Ada.
C++ language code can be either structured, or object-oriented.
Advantages of Structured Programming Language
o Structured programming is user-friendly and easy to understand.
o In this programming, programs are easier to read and learn.
o The main advantage of structured programming is reduced complexity.
o Increase the productivity of application program development.
Page: 6
UNIT-1
Chapter2: INTRODUCTION TO C
1. A brief history of C
C evolved from a language called B, written by Ken Thompson at Bell Labs in 1970. B in turn
was a successor of the language BCPL (Basic Combined Programming Language). The original C was
still too limiting, and not standardized, and so in 1983 an ANSI(American National Standard Institute)
committee was established to formalize the language definition. It has taken until now standard to
become well accepted and almost universally supported by compilers.
C is a high level language and also has a low level programming features. It is well suited for
writing both system software and application soft ware. It is highly portable. It is well suited for
structured programming. A C program is basically collection of functions that are supported by C
library.
Page: 7
main () function section: Every C program must have one main function section. A function is a block
of code that performs a specific task.
C program to explain the structure of C program
#include <stdio.h>
main( )
{
printf("Hello, World!");
return 0;
}
The character set of C Language
To write a program in any computer language you need a set of characters and symbols. The
characters and symbols can understand and accept by the language. C is used the upper cases
A,B,…….,Z, the lower cases a ,b,…..,z and certain special characters like + - * / = % & # ! ? ^
“ ‘ ~ \ < > ( ) = [ ] { } ; : . , _ blank space @ $ and certain combinations of these
characters like \b, \n, \t, etc…
Page: 8
Standard keywords are auto, break, case, char, const, continue, default, do, double, else
enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct,
switch, typedef, union, unsigned, void, volatile, while.
(Note that these words should not be used as identities.)
Page: 9
DATA TYPE MEMORY (BYTES) RANGE FORMAT SPECIFIER
float 4 %f
double 8 %lf
Page: 10
6. What are the different Operators used in C language?
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is supported the following types of operators
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Unary operators
6. Conditional operators
7. Bitwise operators
1. Arithmetic Operators: Different types of arithmetic operations are supported by C language. The
fallowing basic operators are used to performing arithmetic operations.
+ for addition,
- for subtraction,
* for multiplication,
/ for division
% for modulus (remainder)
2. Relational Operators: These relational operators are used to compare two values on their relation.
The relational operators are
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
3. Logical Operators: A logical expression is expression connected with a relational operator. Its value
is either true or false. In the logical expression use the fallowing three logical operators are used.
&& means logical AND
|| means logical OR
! means logical NOT
4. Assignment Operators: These operators are used for assigning a value of expression to a variable.
=, + =, - = , * =, /= , %= are assignment operators. These operators are used in the fallowing way.
a = b+c results in storing the value of b+c in ‘a’.
a += 5 results in increasing the value of a by 5
a /= 3 results in storing the value a/3 in a and it is equivalent a=a/3
Page: 11
5. Unary Operators: A operator acts upon a single operand to produce a new value is called a unary
operator.
(1) The increment and decrement operators ++ and -- are unary operators. They are used to increase and
decrease the value by 1.
For Ex: ++A in this A value is incremented by 1
--B in this B value is decremented by 1
(2) sizeof is another unary operator For Ex: int x, y; y=sizeof(x); The value of y is 2 . the sizeof an
integer type data is 2 that of float is 4, that of double is 8, that of char is1.
6. Conditional Operator
The operator ?: is the conditional operator. It is used as
variable 1 = expression 1 ? expression 2 : expression 3.
Here expression1 is a logical expression and expression2, expression3 are having numerical values. If
expression1 is true, value of expression2 is assigned to variable1 otherwise expression3 is assigned.
For Ex: int a=10, b=15, x;
x = (a > b) ? a : b ;
7. Bitwise Operators
C has supporting special operators known as bit wise bitwise operators. They are listed bellow.
& Bit wise AND
| Bit wise OR
^ Bit wise exclusive OR
<< Bit wise shift left
>> Bit wise shift right
7. What are the different Input and Output statements(functions) used in C program?
There are some library functions which are available for transferring the information between
the computer and the input and output devices. To use these functions in a C-program there should be a
preprocessor statement #include<stdioh>.
Some of the input and output functions are as follows:
1. printf( ): In C programming, printf() is one of the main output function. The function sends
formatted output to the screen. For example: printf(“Hello Every Body..”);
printf("Number = %d", testInteger);
2. scanf(): In C programming, scanf() is one of the commonly used function to take input from the
user. The scanf() function reads formatted input from the standard input such as keyboards.
For example: scanf("%d", &testInteger);
3. getch: This function is used to input a single character. The character is read instantly and it does not
require an enter key to be pressed.
For example: VariableName = getch();
Page: 12
4. putch: This function is a complement of getch. Which means that it will display a single character
on the screen. For example: putch(VariableName);
5. getche: This function is used to input a single character. The main difference between getch and
getche is that getche displays the (echoes) the character that we type on the screen.
For example: VariableName = getche();
6. getchar: This function is used to input a single character. The enter key is pressed which is followed
by the character that is typed. The character that is entered is echoed.
For example: VariableName = getchar;
7. Putchar: This function is the other side of getchar. A single character is displayed on the screen.
For example: putchar(ch);
8. gets and puts: They help in transferring the strings between the computer and the standard input-
output devices. Only single arguments are accepted. The arguments must be such that it represents a
string. For Example: gets (line);
puts (line);
8. What is Type Casting or Conversion in C?
Typecasting is converting one data type into another one. It is also called as data conversion or
type conversion. It is one of the important concepts introduced in 'C' programming. 'C' programming
provides two types of type casting operations:
1. Implicit type casting
2. Explicit type casting
1. Implicit type casting: Implicit type casting means conversion of data types without losing its original
meaning. Implicit type conversion happens automatically when a value is copied to its compatible data
type.
short a=10; //initializing variable of short data type
int b; //declaring int variable
b=a; //implicit type casting
2. Explicit type casting: In implicit type conversion, the data type is converted automatically. There are
some scenarios in which we may have to force type conversion. Suppose we have a variable div that
stores the division of two operands which are declared as an int data type.
int result, var1=10, var2=3;
result=var1/var2;
Page: 13
UNIT-2
Chapter3: DECISION CONTROL AND LOOPING STATEMENTS
Page: 14
2. if else statement: It is used to execute one of the two
possible group of statements depending on the outcome of a
logical condition in the if statement.
Syntax : Example:
if (Condition) if(x<0)
Statement 1 ; printf(“\n x is negative”);
else else
Statement 2; printf(“\n x is positive”);
3. Nested if statement: Within an if block or else block another if – else statement can come. Such
statements are called nested if statements.
Syntax : Example:
if (Condition) If (x= =0)
Statement1; printf(“\n x value is zero ”);
else if (Condition2) else if(x<0)
Statement2; printf(“\n x is negative”);
else else
printf(“\n x is positive”);
Statement3;
Page: 15
Syntax : Example:
int temp = 3;
switch(temp)
{
switch(expression) case 1 :
{ printf("One");
case value1: break;
Statement1; case 2 :
break; printf("Two");
case value 2: break;
Statement2; case 3 :
break; printf("Three");
……. break;
…….. case 4 :
default: printf("Four");
Statement n; break;
} case 5 :
printf("Five");
break;
default :
printf("default");
}
2.2 What are the different Looping control statements used in C-Programs?
1. The while statement: It is used to execute a set of statements to be executed repeatedly until some
condition is satisfied.
Syntax : Example:
int i=1;
while (Condition)
{ while(i<=10)
// Statements inside {
the body of the loop printf(“%d”,i);
} ++i;
}
Working:
o The while loop evaluates the test condition inside the parenthesis ().
o If the test condition is true, statements inside the body of while loop are executed. Then, the test
condition is evaluated again.
o The process goes on until the test condition is evaluated to false.
Page: 16
2. do while statement: This is also used to execute a set of statements to be executed repeatedly so as
long as a condition is true.
Syntax : Example:
int i=1;
do do
{ {
// statements inside the body printf(“%d”,i);
of the loop
} ++i;
while (Condition); }while(i<=10);
Working:
o The body of do...while loop is executed once. Only then, the condition is evaluated.
o If the test condition is true, the body of the loop is executed again
o This process goes on until the test condition becomes false.
o If the test condition is false, the loop ends.
3. for loop It is the most commonly used looping statement in C. The loop header contains three parts:
an initialization, a continuation condition, and step.
Page: 17
Syntax :
for (InitializationStatement; TestExpression; UpdateStatement)
{
// statements inside the body of loop
}
Example:
main()
{
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
}
Working:
o The initialization statement is executed only once.
o Then, the test expression is evaluated. If the test expression is evaluated to false, the for loop is
terminated.
o However, if the test expression is evaluated to true, statements inside the body of for loop are
executed, and the update expression is updated.
o Again the test expression is evaluated.
2. The continue statement: The continue statement skips the current iteration of the loop and
continues with the next iteration. The continue statement can be used only inside for loop, while loop
and do-while loop. The loop does not terminate when continue statement is encountered, but statements
after continue are skipped and proceeds to the next pass through the loop.
Page: 18
Example:
int i;
for(i=1;i<=5;++i)
{
if(i==3)
continue;
printf(“%d\n”,i);
}
The above example print the 1, 2, 4, 5 values only.
3.goto statement: It is used to alter the normal sequence of program execution by transferring control
to some other part of the program .
The syntax is goto label ;
Example:
int n=1,x,sum=0;
while(n<=10)
{
scanf(“%d” ,&x);
if(x<0) goto error;
sum+=x; ++n;
}
error:
printf(“\n the number must be non
negative”);
Page: 19
UNIT-2
Chapter4: FUNCTIONS
Page: 20
15. }
16.
17. int addNumbers(int a, int b) // function definition
18. {
19. int result;
20. result = a+b;
21. return result; // return statement
22. }
0. Function prototype: A function prototype is simply the declaration of a function that specifies
function's name, parameters and return type. It doesn't contain function body. A function prototype
gives information to the compiler that the function may later be used in the program.
Syntax of function prototype: returnType functionName(type1 argument1, type2 argument2, ...);
In the above example, int addNumbers(int a, int b); is the function prototype which provides the
following information to the compiler:
1. name of the function is addNumbers()
2. return type of the function is int
3. two arguments of type int are passed to the function
4. The function prototype is not needed if the user-defined function is defined before
the main() function.
1. Calling a function: When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task. Once the function completes its task, the program
control is returned back to the calling function. To call a function, you simply need to pass the required
parameters along with the function name.
Syntax of function call: functionName(argument1, argument2, ...);
In the above example, the function call is addNumbers(n1, n2); statement inside the main() function.
2. Function definition: Function definition contains the block of code to perform a specific task. A
function declaration tells the compiler about a function's name, return type, and parameters.
A function definition in C programming consists of a function header and a function body. Here are all
the parts of a function.
Return Type: The return_type is the data type of the value the function returns.
Function Name: This is the actual name of the function.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument.
Function Body: The function body contains a collection of statements that define what the function
does.
Syntax of function definition:
returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}
Page: 21
In the above Example function definition is
int addNumbers(int a, int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
3. Passing arguments to a function: In programming, argument refers to the variable passed to the
function. In the above example, two variables n1 and n2 are passed during the function call. The
parameters a and b accepts the passed arguments in the function definition.
4. Return Statement: The return statement terminates the execution of a function and returns a value
to the calling function. The program control is transferred to the calling function after the return
statement.
Syntax of return statement: return (expression);
In the above Example return statement is return result;
3. What are the different types of User-defined Functions used in C Programming language?
There can be 4 different types of user-defined functions, they are:
1. Function with no argument and no Return value. (No arguments passed and no return value)
2. Function with no argument and with Return value. (No arguments passed but a return value)
3. Function with argument and No Return value. (Argument passed but no return value)
4. Function with argument and Return value. (Argument passed and a return value)
1. Function with No argument and No Return value: In this method, We won’t pass any arguments
to the function while defining, declaring or calling the function. This type of functions will not return
any value when we call the function from main( ).
Example:
#include<stdio.h>
void addition();
void main()
{
addition();
}
void addition()
{
int sum, a = 10, b = 20;
sum = a + b;
printf("\n Sum of a and b is %d",sum);
}
Expected output: Sum of a and b is 30
2. Function with no argument and with Return value: In this method, We won’t pass any arguments to
the function while defining, declaring or calling the function. This type of functions will return some value when
we call the function from main( ) function.
Page: 22
Example:
iinclude<stdio.h>
int multiplication();
main()
{
int multi;
multi = multiplication();
printf("\n Multiplication of a and b is = %d \n", multi );
}
int multiplication()
{
int multi, a = 20, b = 40;
multi = a * b;
return multi;
}
Expected output: Multiplication of a and b is =800
3. Function with argument and No Return value: This method allows us to pass the arguments to the
function while calling the function. But, this type of functions will not return any value when we call
the function from main( ) function.
Example:
#include<stdio.h>
void addition(int, int);
void main()
{
int a=20, b=30;
addition(a, b);
}
void addition(int a, int b)
{
int sum;
sum = a + b;
printf("\n Additiontion of a and b is %d ",sum);
}
Expected output: Additiontion of a and b is 50
4. Function with argument and Return value: This method allows us to pass the arguments to the
function while calling the function. This type of functions will return some value when we call the
function from main( )function.
Example:
#include<stdio.h>
int multiplication(int, int);
main()
{
int a=10, b=20, multi;
multi = multiplication(a, b);
printf("\n Multiplication of a and b is = %d",multi);
}
int multiplication(int a, int b)
{
int multi;
multi = a * b;
Page: 23
return multi;
}
Expected output: Multiplication of a and b is =200
Scope of Variables: A scope is a region of the program, and the scope of variables refers to the area of
the program where the variables can be accessed after its declaration. In C every variable defined in
scope. You can define scope as the section or region of a program where a variable has its existence,
that variable cannot be used or accessed outside that region.
In C programming the variable can be declared in three places. These are:
Position Type
1. Local Variables: Variables that are declared inside a function or a block are called local
variables and are said to have local scope. These local variables can only be used within the function
or block in which these are declared. It is invalid outside it.
#include <stdio.h>
main()
{
int x= 3; /* variable declaration in outerblock */
printf(“\n in outer block x = %d before executing inner block”, x);
if(x>0)
{
int x= 45; /* variable declaration in innerblock */
printf(“\n in inner block x = %d”, x);
}
printf(“\n in outer block x = %d after executing inner block”, x);
return 0;
}
Output:
in outer block x = 3 before executing inner block
in inner block x = 45
in outer block x = 3 after executing innerblock
2. Global Variables: Variables that are defined outside of all the functions and are accessible
throughout the program are global variables and are said to have global scope. Once declared,
these can be accessed and modified by any function in the program. We can have the same name for
a local and a global variable but the local variable gets priority inside a function.
Page: 24
#include <stdio.h>
int x = 10; /*Global variable*/
main()
{
printf("%d\n",x);
fun1();
}
void fun1()
{
int x = 5; /*Local variable of same name*/
printf("%d\n",x);
}
Output:
10
5
3. Formal Parameters: Formal Parameters are the parameters which are used inside the body of a
function. Formal parameters are treated as local variables in that function and get a priority over the
global variables.
#include <stdio.h>
int x = 10; /*Global variable*/
int main()
{
fun1(5);
}
Output:
5
Page: 25
auto Storage Class: This is the default storage class for all the variables declared inside a function.
Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be
only accessed within the function they have been declared and not outside them. They are assigned a
garbage value by default whenever they are declared.
Example: auto int age;
register Storage class: You can use the register storage class when you want to store local variables
within functions or blocks in CPU registers instead of RAM to have quick access to these variables.
Example: register int age;
The keyword register is used to declare a register storage class. The variables declared using
register storage class has lifespan throughout the program. The variables declared using register storage
class has no default value. These variables are often declared at the beginning of a program.
static Storage Class: The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it comes into and
goes out of scope. The static modifier may also be applied to global variables. Keep in mind that static
variable has a default initial value zero and is initialized only once in its lifetime.
Example: static int x=10.
extern Storage Class: Extern stands for external storage class. Extern storage class is used when we
have global functions or variables which are shared between two or more files. Keyword extern is used
to declaring a global variable or function in another file to provide the reference of variable or function
which have been already defined in the original file.
The variables defined using an extern keyword are called as global variables. These variables
are accessible throughout the program.
Example: extern int x;
Example: extern void display();
Page: 26
6. Briefly discuss about recursive functions.
Recursion: Recursion is the process of repeating items in a self-similar way.
Recursive functions: Function call by itself is known as recursion. The C programming language
supports recursion. Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
The following example calculates the factorial of a given number using a recursive function:
#include <stdio.h>
unsigned long long int factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
It produces the following result : Factorial of 12 is 479001600
Page: 27
Towers of Hanoi We can develop a simple solution for Towers of Hanoi Program in C by using
Recursion.
o Move n disks from peg A to peg C, using peg B as needed.
o The following conditions apply.
o Only one disk may be moved at a time.
o This disk must be the top disk on a peg.
o A larger disk can never be placed on top of a smaller disk.
The General and Base rule of solving Towers of Hanoi problem has been listed below.
Move (n-1) disk from source to auxiliary (general rule)
Move nth disk from source to destination (base rule)
Move (n-1) disks from auxiliary to destination (general rule)
Expected o/p:
Enter No. of Disks: 3
Enter Source, Destination and Auxillary Disk Names:S D A
1 is moved from S to D
2 is moved from S to A
1 is moved from D to A
3 is moved from S to D
1 is moved from A to S
2 is moved from A to D
1 is moved from S to D
Page: 28
8. What is the difference between Recursion and Iteration?
Recursion vs. Iteration
BASIS FOR
RECURSION ITERATION
COMPARISON
Recursion refers to a situation where a Iteration refers to a situation where some
Definition function calls itself again and again until statements are executed again and again
some base condition is not reached. using loops until some condition is true.
It is comparatively slower because before
Its execution is faster because it doesn’t
Performance each function call and after the return
use stack.
statement organize the stack.
Memory usage is more as stack is used to Memory usage is less as it doesn’t use
Memory
store the current function state. stack.
Size of code is comparatively smaller in
Code Size Iteration makes the code size bigger.
recursion.
Page: 29
UNIT-3
Chapter5: ARRAYS
1. What is an array?
Array: An array can be defined as the collection of similar type of data elements. The elements are
stored in consecutive memory locations and are referenced by index. Arrays are the derived data type in
C programming language which can store the primitive type of data such as int, char, double, float, etc.
Array Characteristics:
o All the elements of array are homogeneous (similar)
o A specific element in an array is accessed by an index
o Array index starts from 0 and ends with [Array size-1]
o An element of an array is referred to by specifying the array name followed by index value
enclosed in square brackets.
marks
Page: 30
i. Initialize the array elements.
ii. Inputting the values from the keyboard.
i. Initialize the array elements:
After an array is declared it must be initialized. Otherwise, it will contain garbage value.
Syntax: DataType ArrayName[Size]={list of values};
Ex: int Marks[5]={45,36,58,71,82};
char Name[ ] = “John”;
Page: 31
Example: int a[5];
Here a[0], a[1], a[2], a[3], a[4] are elements of the array.
Page: 32
1. One Dimensional Array: A one-dimensional array (or single dimension array) is a linear array.
Practically you can think of a one-dimensional array as a row. Accessing its elements involves with a
single index value. As an example consider the C declaration int Marks[8]; which declares a one-
dimensional array of eight integers.
iii. Insert elements into the array: To insert the values into an array from standard input device by
using the following syntax
Example: int a[5];
for(i=0; i<4; i++)
{
scanf(“%d”,&a[i]);
}
iv. Display an array elements: To display the array elements on a standard output devices using the
following syntax.
Example: int a[5];
for(i=0;i<4;i++)
{
printf(“%d”,a[i]);
}
2. Two Dimensional Arrays: The two-dimensional array can be defined as an array of arrays. The two
dimensional arrays contains multiple rows and multiple columns. It contains two indexes one is row
index another one is column index. The 2D array is organized as matrices which can be represented as
the collection of rows and columns.
Page: 33
Operations on Two Dimensional Array:
i. Declaration: To declare two dimensional array using the following syntax.
Syntax: DataType ArrayName[Row Index] [Column Index];
Example: int Matrix [4][3];
ii. Initialization: To initialize two dimensional arrays use the following syntax.
Syntax: DataType ArrayName[Row Index] [Column Index]={(value1,value2),..,(value n-1,value n)}
Example: int Matrix[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
iii. Insert elements into the Two dimensional array: To insert the values into a two dimentional array
from standard input device by using the following syntax
Example: for(i=0; i<4; i++)
{
for(j=0; j<3;j ++)
{
scanf(“%d%”,&Matrix[i][j]);
}
}
iv. Display two dimensional array elements: To display the two dimensional array elements on a
standard output devices using the following syntax.
Example: for(i=0; i<4; i++)
{
for(j=0; j<3; j++)
{
printf(“%d%”,a[i][j]);
}
}
3. Multi Dimensional Arrays: C programming language allows multidimensional arrays. Here is the
general form of a multidimensional array declaration
Syntax: DataType ArrayName[size1][size2]...[sizeN];
Example: Following declaration creates a three dimensional integer array int threedim[4][4][3];
Page: 34
5. One-Dimensional Arrays for Inter Function Communication (OR)
How to Passing One-Dimensional Array to function?
Just like variables, array can also be passed to a function as an argument.
i. Pass the individual elements of the array to a function
ii. Pass the entire array to a function
i. Pass the individual elements of the array to a function: The individual elements can be passed in the
same manner as we pass variables of any other data type. The condition is just that the data type of the
array element must match the type of the function parameter.
Example:
main( )
{
int arr[5]= {1,2,3,4,5};
function1(arr[3]);
}
void function1(num)
{
printf(“%d”,num);
}
ii. Passing the Entire Array: Like the values of simple variables, it is also possible to pass the values of
an array to a function.
Example:
main( )
{
int arr[5]= {1,2,3,4,5};
myfunc(arr);
}
void myfunc(int arr[5])
{
int i;
for(i=0; i<5;i++)
printf(“%d”, arr[i]);
}
Page: 35
6. What is Sparse Matrix and how it can be represented?
A matrix is a two-dimensional data object made of m rows and n columns, therefore having
total m x n values. If most of the elements of the matrix have 0 value, then it is called a sparse matrix.
Reasons use Sparse Matrix instead of simple matrix:
o Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to
store only those elements.
o Computing time: Computing time can be saved by logically designing a data structure
traversing only non-zero elements.
Representing a sparse matrix: To avoid the wastage of memory for representing zeros in a simple
matrix use a sparse matrix. In sparse matrix non zero elements are represented with their row and
column values. This means storing non-zero elements with triples- (Row, Column, value).
2D array is used to represent a sparse matrix in which there are three rows named as
Row: Index of row, where non-zero element is located
Column: Index of column, where non-zero element is located
Value: Value of the non zero element located at index – (row,column)
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int i,j,m,n,a[10][10],b[10][10],c[10][10];
clrscr();
printf("\nEnter the Row size of Matrix : ");
scanf("%d", &m);
printf("\nEnter the Column size of Matrix: ");
scanf("%d", &n);
Page: 36
printf("enter A matrix elements \n");
for(i=0; i<m; i++)
{
for(j=0;j<n;j++)
{
scanf("%d\t",&a[i][j]);
}
printf("\n");
}
printf("enter B matrix elements \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d\t",&b[i][j]);
}
printf("\n");
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(" the addition of two matrices is \n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%4d ",c[i][j]);
}
printf("\n");
}
getch();
}
OUTPUT: Enter the Row size of Matrix
2
Enter the Column size of Matrix
2
enter A matrix elements
3 4
5 6
enter B matrix elements
5 6
7 8
the addition of two matrices is
8 10
12 14
Page: 37
Write a C-Program to perform Multiplication of two Matrices.
#include<stdio.h>
#include<conio.h>
#include<math.h>
main( )
{
int i,j,k,p,q,m,n,a[10][10],b[10][10],c[10][10];
clrscr();
printf(" enter the order of matrix A \n");
scanf("%d%d",&m,&n);
printf("enter the order of matrix B \n");
scanf("%d%d",&p,&q);
if(n!=p)
{
printf(" matrix multiplication is not possible \n");
}
else
{
printf("enter A matrix elements \n");
for(i=0; i<m; i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter B matrix elements \n");
for(i=0; i<p; i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0; i<m; i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0; k<n; k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
Page: 38
printf(" The multiplication matrix of two matrices is \n");
for(i=0; i<m; i++)
{
for(j=0; j<q; j++)
{
printf("%d \t",c[i][j]);
}
printf("\n");
}
}
getch();
}
Page: 39
UNIT-3
Chapter6: STRINGS
1. What is a string?
Definition: In C programming, a string is a sequence of characters terminated with a null character \0.
It is also called as character array.
Now we learn how to declare, initialize and use the strings for various I/O operations.
How to declare a string
It is declared by using the following syntax.
Syntax: char StringName[Size];
Example: char name[20]; Here, we have declared a string of 20 characters.
How to initialize strings
You can initialize strings in a number of ways.
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'}
Page: 40
1. strlen(s1): The strlen() function calculates the length of a given string. This function takes a string as
an argument and returns its length.
Exmple: s1=’college’;
a=strlen(s1);
a=7
2. strcmp(s1,s2): The strcmp() function compares two strings and returns 0 if both strings are identical.
This function takes two strings and returns an integer. It compares two strings character by character. If
the first character of two strings is equal, the next character of two strings is compared. This continues
until the corresponding characters of two strings are different or reached to end of the string.
Return Value Remarks
0 if both strings are identical (equal)
Negative if the ASCII value of the first unmatched character is less than second.
Positive Integer if the ASCII value of the first unmatched character is greater than second.
3. strcpy(s1,s2): This function is used to coping the strings from source to destination.
Example: s1=abc and s2=xyz
strcpy(s1,s2)
Result: s1=abc
s2=abc
4. strcat(s1,s2) : This function is used to merging the two strings. This function append the string 2
fallowed by string 1.
Example: str1[20]=”programming”
str2[10]=”in c”
pritf(“%s”,strcat(str1,str2) );
Output: programming in c
5. strlwr(s1): The strlwr() function returns string characters in lowercase letters.
Sytax: strlowr(strig);
Example: char s1[10] = "GOOD";
printf("%s", strlwr(s1) );
Output: good
6. strupr( ): The strlwr() function returns string characters in Uppercase letters.
Syntax: strupr(string)
Example: char s1[10] = "Good";
printf("%s", strupr(s1) );
Output: GOOD
7. strstr( ): strstr() function is used to search a sub string in a string.
Syntax: strstr(string1, search_string)
Page: 41
8. strrev(s1): This function is used to display the string in reverse order.
Example: s1=’college’;
s2=strrev(s1);
Result: s2=egelloc
isgraph( ch ); This function checks if ch is a printing character other than a space or not.
ispunct( ch ); This function checks if ch is a printing character other than a digit, a space, a
letter or not.
Page: 42
UNIT-4
Chapter7: POINTERS
1. What is a Pointer explains in detail?
A pointer is a variable that stores the address of another variable. Unlike other variables that
hold values of a certain type, pointer holds the address of a variable. For example, an integer variable
holds an integer value; however an integer pointer holds the address of a integer variable.
Syntax: DataType *var-name;
Here, DataType is the pointer's base type; it must be a valid C data type and var-name is the
name of the pointer variable. The asterisk * used to declare a pointer
Declarations of pointers
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
How to Use Pointers?
There are a few important operations, which we will do with the help of pointers very frequently.
o We define a pointer variable
o Assign the address of a variable to a pointer
o Access the value at the address available in the pointer variable.
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result:
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
Page: 43
2. What is a NULL Pointer explains in detail?
A pointer that is assigned NULL is called a null pointer. It is always a good practice to assign a
NULL value to a pointer variable in case you do not have an exact address to be assigned. This is done
at the time of variable declaration. The NULL pointer is a constant with a value of zero defined in
several standard libraries. Consider the following program:
Live Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result:
The value of ptr is 0
Page: 44
3. Pointer Comparisons: Pointers may be compared by using relational operators, such as ==, <, and
>. If p1 and p2 point to variables that are related to each other, such as elements of the same array, then
p1 and p2 can be meaningfully compared.
4. C Pointer Addition: We can add a value to the pointer variable. The formula of adding value to
pointer is given below: new_address= current_address + (number * size_of(data type));
5. C Pointer Subtraction: Like pointer addition, we can subtract a value from the pointer variable.
Subtracting any number from a pointer will give an address. The formula of subtracting value from the
pointer variable is given below: new_address= current_address - (number * size_of(data type));
Size of datatypes on 16-bit Machine(Turbo C):
char 1
long 4
float 4
double 8
long double 10
Function Purpose
Malloc() Allocates the memory of requested size and returns the pointer to the first
byte of allocated space.
Calloc() Allocates the space for elements of an array. Initializes the elements to zero
and returns a pointer to the memory.
Page: 45
1. The malloc Function: The malloc() function stands for memory allocation. It is a function which is
used to allocate a block of memory dynamically. It reserves memory space of specified size and returns
the null pointer pointing to the memory location. The pointer returned is usually of type void. It means
that we can assign malloc function to any pointer.
Syntax: ptr = (cast_type *) malloc (byte_size);
Example: ptr = (int *) malloc (50)
When this statement is successfully executed, a memory space of 50 bytes is reserved. The
address of the first byte of reserved space is assigned to the pointer ptr of type int.
2. The calloc Function: The calloc() function stands for contiguous allocation. This function is used to
allocate multiple blocks of memory. It is a dynamic memory allocation function which is used to
allocate the memory to complex data structures such as arrays and structures.
malloc function is used to allocate a single block of memory space while the calloc function is
used to allocate multiple blocks of memory space. Each block allocated by the calloc function is of the
same size.
Syntax: ptr = (cast_type *) calloc (n, size);
o The above statement is used to allocate n memory blocks of the same size.
o After the memory space is allocated, then all the bytes are initialized to zero.
o The pointer which is currently at the first byte of the allocated memory space is returned.
3. The free Function: The memory for variables is automatically de-allocated at compile time. In
dynamic memory allocation, you have to de-allocate memory explicitly. If not done, you may
encounter out of memory error. The free() function is called to release/de-allocate memory. By freeing
memory in your program, you make more available for use later.
4. The realloc Function: Using the realloc() function, you can add more memory size to already
allocated memory. It expands the current block while leaving the original content as it is. realloc stands
for reallocation of memory. realloc can also be used to reduce the size of the previously allocated
memory.
Syntax: ptr = realloc (ptr,newsize);
Page: 47
UNIT-4
Chapter8: STRUCTURE, UNION and ENUMERATED DATA TYPE
1. What is a Structure?
Structure: A structure can be defined as a collection of different data elements that are all represented
by common name. In other words the structure is a user-defined data type in C, which is used to store a
collection of different kinds of data.
Defining a structure / Structure Declaration: A structure can be declared using the keyword
“struct”, followed by structure name. All the variables of the structure are declared within the
structure.
After defining a structure, we can declare variables.
Declaration of variables includes:
o The Keyword struct
o The structure Tag name
o List of variable names separated by commas.
o Terminating with semicolon.
Syntax:
<struct> <tag name or structure name>
{
data type variable1/element1;
data type variable2/element2;
--------------------------------
data type variable n/element n;
};
Page: 48
stu1.sname
Page: 49
printf("\n Student fees=%f",stud1.fees);
printf("\n DOB is=%s",stud1.DOB);
}
5. What is a Union?
Union is a collection of different data members like a structure. Union can be created by using union
keyword. It is a one of the users defined data type. A union is a memory location that is shared by two
(or) more variables, generally of different types, at different times.
1. Union occupies only one memory location at a time.
2. When a new value is assigned to a field, the existing data is replaced with the new data.
3. Unions are used to save the memory.
Declaration of Unions: The declaration of union is same as structure only difference is that instead of
using the keyword “struct”, the keyword “union” would be used.
Syntax: union union name Example: union employee
{ union emp
{
data tyepo var-name1;
char empname [20];
data type var-name2; char empjob[10];
---------------------- int empno;
float empsal;
Page: 50
}; };
In the above example the union works same, as structure but different in memory occupation.
Note: Union variable can be created by using following syntax
Syntax: Union <union name><union variable/union member>;
Example: union employee emp1;
Structure Union
The keyword struct is used to The keyword union is used to define a
Keyword
define a structure structure
When a variable is associated When a variable is associated with a
with a structure, the compiler union, the compiler allocates the memory
allocates the memory for each by considering the size of the largest
Size
member. The size of structure is memory. So, size of union is equal to the
equal to sum of sizes of its size of largest member.
members
Each member within a structure Memory allocated is shared by individual
Memory is assigned unique storage area members of union
of location
Altering the value of a member Altering the value of any of the member
Value altering will not affect other members of will alter other member values.
the structure
Accessing Individual member can be Only one member can be accessed at a
members accessed at a time time.
Initialization Several members of a structure Only the first member can be initialized.
of members can initialize at once
The member of structure can be The members of a union can be referred by
referenced using dot operator. using the dot operator as in the case of a
Referencing structure.
Page: 52
UNIT-5
Chapter6: FILES
1. What is a File? And what are the operations performed on a File?
A file is a collection of data stored in one unit, identified by a filename. Different operations that can
be performed on a file are:
1. Creation of a new file
2. Opening an existing file
3. Reading from file
4. Writing to a file
5. Moving to a specific location in a file
6. Closing a file
1. Opening or creating file: For opening a file, fopen function is used with the required access modes.
Some of the commonly used file access modes are mentioned below.
File opening modes in C:
o “r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the first character in it. If the file cannot be opened fopen( ) returns
NULL.
o “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new
file is created. Returns NULL, if unable to open file.
o “a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a
pointer that points to the last character in it. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open file.
o “r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the first character in it. Returns NULL, if unable to open the file.
o “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a
new file is created. Returns NULL, if unable to open file.
o “a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
a pointer which points to the last character in it. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open file.
Example: FILE *filePointer;
So, the file can be opened as
filePointer = fopen(“fileName.txt”, “w”)
2. Reading from a file: The file read operations can be performed using functions fscanf or fgets. Both
the functions performed the same operations as that of scanf and gets but with an additional parameter,
the file pointer. So, it depends on you if you want to read the file line by line or character by character.
And the code snippet for reading a file is as:
Example: FILE * filePointer;
filePointer = fopen(“fileName.txt”, “r”);
Page: 53
fscanf(filePointer, "%s %s %s %d", str1, str2, str3, &year);
3. Writing a file: The file write operations can be performed by the functions fprintf and fputs with
similarities to read operations. The code for writing to a file is as:
Example: FILE *filePointer ;
filePointer = fopen(“fileName.txt”, “w”);
fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2012);
4. Closing a file: After every successful fie operations, you must always close a file. For closing a file,
you have to use fclose function. The code for closing a file is given as:
Example: FILE *filePointer ;
filePointer= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(filePointer);
2. How to handle the errors during the file operations?
While dealing with files, it is possible that an error may occur. This error may occur due to
following reasons:
o Reading beyond the end of file mark.
o Performing operations on the file that has not still been opened.
o Writing to a file that is opened in the read mode.
o Opening a file with invalid filename.
o Device overflow.
C provides two status-enquiry library functions
1. feof() - The feof() function can be used to test for an end of file condition
Syntax: feof(FILE *file_pointer);
Example: if(feof(fp)) printf(“End of file”);
2. ferror() - The ferror() function reports on the error state of the stream and returns true if an
error has occurred.
Syntax: ferror(FILE *file_pointer);
Example: if(ferror(fp)!=0) printf(“An error has occurred”);
Page: 54