0% found this document useful (0 votes)
5 views

computer c language

The document provides an introduction to algorithms and programming languages, defining algorithms as step-by-step procedures to solve problems, and flowcharts as graphical representations of these algorithms. It covers key features of algorithms, differences between algorithms and flowcharts, pseudo code, and programming languages, including their generations and structured programming. Additionally, it introduces the C programming language, its structure, identifiers, keywords, constants, variables, and basic data types.

Uploaded by

Ram Sai Meghnadh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

computer c language

The document provides an introduction to algorithms and programming languages, defining algorithms as step-by-step procedures to solve problems, and flowcharts as graphical representations of these algorithms. It covers key features of algorithms, differences between algorithms and flowcharts, pseudo code, and programming languages, including their generations and structured programming. Additionally, it introduces the C programming language, its structure, identifiers, keywords, constants, variables, and basic data types.

Uploaded by

Ram Sai Meghnadh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

UNIT-1

Chapter1: INTRODUCTION TO ALGORITHMS AND PROGRAMMING LANGUAGES

1. What is a algorithm? And what are the key features of algorithm?


Algorithm: Algorithm is a step-by-step procedure written in Ordinary Language to solve a given
problem. Algorithms are generally created independent of programming languages.
Key features of algorithms (or) characteristics of algorithm
 Unambiguous: Algorithm should be clear and unambiguous. Each of its steps, and their inputs /
outputs should be clear and must lead to only one meaning.
 Easy to grasp: Algorithms are there to help humans to understand the solution.
 Input: An algorithm should have 0 or more well-defined inputs.
 Output: An algorithm should have 1 or more well-defined outputs, and should match the desired
output.
 Finiteness: Algorithms must terminate after a finite number of steps.
 Feasibility: Should be feasible with the available resources.
 Independent: An algorithm should have step-by-step directions, which should be independent of
any programming code.
2. What is a Flowchart? And what are the symbols used in flow chart?
Flowchart: A flowchart is a graphical representation of an algorithm. It shows steps in sequential order
and is widely used in presenting the flow of algorithms. Typically, a flowchart shows the steps as boxes
of various kinds, and their order by connecting them with arrows.
Common Flowchart Symbols
o Rectangle: Represents a process
o Oval / Elliptical: Represents the start or end
o Diamond: Represents a decision
o Parallelogram: Represents input/output

Page: 1
3. Write an algorithm and flow chart for exchange (interchange) of values in Two Variables
Flow chart

Algorithm

1. Initialize two variables N1, N2 with zeros

2. Read two different values to N1, N2.

3. Move the N1 value to Temporary variable

4. Move the N2 value to N1

5. Move the Temporary variable value to N1

6. Print the N1 and N2 values

4. Write an algorithm and flow chart for sum of set of numbers

Start

XNumber
Num[1…X]Val 1,Val 2,….Val X
Algorithm
Sum0
1. Initialize variable X with how many numbers you want to add

2. Read X different values to SumSum+Num[X]


Num[1],Num[2],….Num[X]
3. Initialize the variable ‘Sum’ with 0(zero).
XX-1
4. Add the values Num[1], Num[2]….Num[X] to Sum

5. Display the Sum value


Yes
X is not 0

No

Display Sum value

End

Page: 2
5. Write an algorithm and flow chart for find the factorial of a numbers

Start

Algorithm
NNumber
1. Initialize variable N with a number. F0

2. Initialize variable F with 1 (One).

3. Multiply the F with N value FF x N

4. Decrement the N value by1


NN-1
5. Repeat the steps 3rd and 4th until the
N value is reached to 0

6. Display the Factorial value(F)


Yes
N is not 0

No

Display Factorial(F) value

End

6. Write an algorithm and flow chart for first N Fibonacci numbers.

Start

Algorithm NNumber
F10, F21
1. Read the N value
Display F1,F2 values
2. Initialize the first two Fibonacci numbers to F1, F2.

3. Display the F1, F2 values


NN-2
4. Decrement the N value by 2
F3F1 + F2
5. Compute the F3=F1+F2.

6. Display the F3 value Display F3 value

7. Decrement the N value by 1


F1 F2 NN-1
8. If N is not equal to zero F2F3
o Transfer the F2 to F1 and F3 to F2 Yes
o Then repeat the steps 5, 6,7 until N is reached to 0 N is not 0

No
End

Page: 3
7. Write an algorithm and flow chart for reverse the digits in a number

Start

NNumber
Algorithm X0

1. Read a number to N
RN % 10
2. Initialize variable X with 0. NN / 10

3. Divide N value with 10 and transfer reminder to R, quotient to N


XX*10 + R
4. Compute X= X x 10 + R

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

8. What is the difference between Algorithm and Flowchart?

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.

9. Briefly discuss about Pseudo code.

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.

2. Explain the Structure of C a program.

C is a structured programming language. Structured programming means it has a different


modules and blocks. Every C program consists of one or more modules called functions. One of these
functions is called main. The program begins by executing main function and accesses other functions,
if any. Functions are written after or before main function separately.
Structure of a C program
1. Document Section
2. Link section
3. Definition section
4. Global Declaration section
5. Main C program function called main ( )
6. Beginning of the program by using {
a. Local variable declaration.
b. Executable statements
End of the program by using }
7. User defined functions.
Documentation section: The documentation section consists of a set of comment lines giving the
name of the program, the author and other details, which the programmer would like to use later.
Link section: The link section provides instructions to the compiler to link functions from the system
library.
Definition section: The definition section defines all symbolic constants.
Global declaration section: There are some variables that are used in more than one function. ...
This section also declares all the user-defined functions.

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

/* This is my first Program developed by 1-B.Sc. students


Date: 12-12-2019*/
# include<stdio.h>
#define PI 3.142
int a,b,c;
main()
{
int x,y;
printf(“Enter any two integer values\n”);
scanf(“%d %d”,&x,&y);
a=x+y;
b=x-y;
c=x*y;
printf(“\n Additional value is %d”, a);
printf(“\n Subtracted value is %d”, b);
printf(“\n Multiplied value is %d”, c);
}
Simple 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…

3. Write about identifiers and key words used in a C Program?


Every word in a C program is classified as either Keyword or Identifier.
Identifiers: Identifiers are names given to various program elements like variables, arrays and
functions. The name should begin with a letter and other characters can be letters and digits and also
can contain underscore character ( _ ) Example: area, average, x12 , name_of_place etc………
Key Words: Key words are reserved words in C language. They have predicted meanings and are used
for the intended purpose.

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.)

4. Briefly discuss about Constants and Variables used in C language


Constant: Constants in the Clanguage refer to fixed value that does not change during the execution of
a program. There are 4 basic types of constants. They are
1. Integer constants Ex: 124, -346, 0, 26 etc…
2. Floating-point constants Ex: 25.374, -5.46, 0.3426 etc…
3. Character constants Ex: ‘a’, ‘M’, ’5’ etc…
4. String constants Ex: ” Raja”, “Hellow”, ”1999” etc..
Variables: Variables are basically memory locations which are given names. A variable is an identifier
that is used to represent some specified type of information. Only a single data can be stored in a
variable. The data stored in the variable is accessed by its name. A variable may take different values at
different times during execution.
Example: Marks, height, Average, Total, Class_Strength….

5. What are the basic Data types used in C language?


In C programming, data types are declarations for variables. This determines the type and size
of data associated with variables.( For Example int myVar;) The variety of data types available to the
needs of the programs. There are three different data types supported by C language.
1. Primary(Built-in or Basic or Fundamental) Data Types
2. Derived Data Types
3. User Defined Data Types
1. Primary Data Types: Primary data types are those which are already defined in programming
languages also known in-built data types. Many composite data types are constructed from this basic
type. The primary data types in C language are int, char, float, double and void.
2. User-Defined Data Types: Data type that derived from an existing primary data type are called
user-defined data type . typedef and enum key words areused to creates user defined data types.
Enumeration data type consists a list of values.
For Ex: enum day { SUN,MON,TUE,WED,THU,FRI,SAT}
3. Derived Data Type: Data types derived from primitive data types are called derived data types.
Derived Data types are formed by a grouping of two or more primary types.
Array, pointer, structure and union are called derived data type in C language.

Page: 9
DATA TYPE MEMORY (BYTES) RANGE FORMAT SPECIFIER

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

int 4 -2,147,483,648 to 2,147,483,647 %d

long int 4 -2,147,483,648 to 2,147,483,647 %ld

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

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 %f

double 8 %lf

long double 12 %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

1. Briefly discuss about Control statements used in C-program.


Control statements: Control statements are used to control the execution sequence of statement in a
program. These control statements basically divided into two groups. First group of statements are
called conditional control statements. These statements control the execution sequence based on the
condition is true or false. Further these can be divided in to branching and looping. Second group of
statements are called unconditional control statements. These statements control the execution sequence
without verifying the condition.
Control statements
1. Conditional control statements
a). Branching
o Simple if
o If else
o Nested if
o Switch
b). Looping
o For loop
o While
o Do while
2. Unconditional control statements
o Break
o Continue
o Goto

2. What are the Conditional Control Statements used in C-Program


These statements control the execution sequence based on the condition is true or false. Further
these can be divided in to branching and looping.
Branching: It is used to execute one of several possible options depending on the logical expression.
Looping: It is used to execute a group of instructions repeatedly, a fixed no of times or until a specified
condition is satisfied.
2.1 What are the different Branching control statements used in C-Programs?
2.1.1. Briefly discuss about if statement.
1. Simple if statement: The logical condition in if statement is
evaluate and found to be true, the single statement or compound
statements following the "if" is executed. If false, the following
statement is skipped.
Syntax : Example:
if (Condition) if(x<0)
statement1; printf(“\n x is negative”);

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;

2.1.2. Briefly discuss about switch statement.


4. Switch Statement: The switch statement is a multi way branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression. Switch is a
control statement that allows a value to change control of execution.

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.

3. What are the different un conditional control statements used in C-Program?


These statements control the execution sequence without verifying the condition.
1. The break statement: The break is a keyword in C which is used to bring the program control out
of the loop. The break statement is used inside for, while, do-while loops or switch statement.
Syntax : break;
Example:
int x, sum=0; int n=1;
while(n<=10)
{
scanf(“%d”,&x);
if(x<0) break;
sum=sum+x;
}
printf(“%d”,sum);

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

1. What is a function explain in detail?


Function: A function is a block of code that performs a specific task. Every C program has at least one
function, which is main(), and You can divide your program into multiple functions.
Advantages of C functions.
o By using functions, we can avoid rewriting same logic/code again and again in a program.
o We can call C functions any number of times in a program and from any place in a program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
Types of function
There are two types of function in C programming:
1. Standard library functions: The standard library functions are built-in functions in C
programming. These functions are defined in header files.
For example,
o The printf() is a standard library function to send formatted output to the screen. This function is
defined in the stdio.h header file.
o The sqrt() function calculates the square root of a number. The function is defined in
the math.h header file.
2. User-defined functions: You can also create functions as per your need. Such functions created by
the user are known as user-defined functions.
2. Briefly discuss about following terms Function prototype, Calling a function, Function
definition, Passing arguments to a function and Return Statement
Here is an example to add two integers. To perform this task, we have created an user-defined function
named addNumbers().
1. #include <stdio.h>
2. int addNumbers(int a, int b); // function prototype
3.
4. int main()
5. {
6. int n1,n2,sum;
7.
8. printf("Enters two numbers: ");
9. scanf("%d %d",&n1,&n2);
10.
11. sum = addNumbers(n1, n2); // function call
12. printf("sum = %d",sum);
13.
14. return 0;

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

4. Briefly discuss about scope of variable in C language?

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

Inside a function or a block. local variables

Out of all functions. Global variables

In the function parameters. Formal parameters

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);
}

void fun1(int x) /*x is a formal parameter*/


{
printf("%d\n",x);
}

Output:
5

5. Briefly discuss about storage classes in C language?


Storage Classes: A storage class represents the visibility and a location of a variable. It tells from what
part of code we can access a variable. A storage class is used to describe the following things:
o The variable scope.
o The location where the variable will be stored.
o The initialized value of a variable.
o A lifetime of a variable.
o Who can access a variable?
We have four different storage classes in a C program
 auto
 register
 static
 extern

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();

FEATURE STORAGE CLASS


auto extern register static
Within the Within all program Within the Within the function
Accessibility
function files function or block
Storage Main memory Main memory CPU register Main memory
Local: retains in
Exists when the Exits throughout Exists when the
function and block
Existence function in which the execution of the function in which
Global: preserves in
it is declared program it is declared
program files
Default
Garbage Zero Garbage zero
value

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

7. Write a C program to solve the Towers of Hanoi problem in recursive method.


Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective
of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another
stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.

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)

/* C Program to Solve Towers of Hanoi Problem */


#include<stdio.h>
#include<conio.h>
void hanoi(int, char, char, char);
void main()
{
int disks;
char source, destination, aux;
clrscr();
printf("\nEnter No. of Disks:");
scanf("%d",&disks);
printf("\nEnter Source, Destination and Auxillary Disk Names:");
scanf("%s%s%s",source, destination, aux);
hanoi(disks,source,destination,aux);
getch();
}
void hanoi(int n, char s, char d, char a)
{
if(n>0)
{
hanoi(n-1,s,a,d);
printf("\n%d is moved from %s to %s",n,s,d);
hanoi(n-1,a,d,s);
}
}

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.

9. Briefly discuss about Call by Value and Call by Reference.


There are two ways in which passing parameters to the function
1. Call by value: In which values of the variables are passed by the calling function to the called
function.
2. Call by reference: In which address of the variables are passed by the calling function to the
called function.
call by value call by reference
While calling a function, we pass values of While calling a function, instead of passing the
variables to it. values of variables, we pass address of variables.
In this method, the value of each variable in In this method, the address of actual variables in
calling function is copied into corresponding the calling function is copied into the dummy
dummy variables of the called function. variables of the called function.
With this method, the changes made to the
With this method, using addresses we would have
dummy variables in the called function have no
an access to the actual variables and hence we
effect on the values of actual variables in the
would be able to manipulate them.
calling function.
#include <stdio.h> #include <stdio.h>
main() main()
{ {
int a = 10, b = 20; int a = 10, b = 20;
swapx(a, b); swapx(&a, &b);
printf("a=%d b=%d\n", a, b); printf("a=%d b=%d\n", a, b);
return 0; return 0;
} }
swapx(int x, int y) swapx(int* x, int* y)
{ {
int t; int t;
t = x; t = *x;
x = y; *x = *y;
y = t; *y = t;
printf("x=%d y=%d\n", x, y); printf("x=%d y=%d\n", *x, *y);
} }

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

2. How to handled the arrays?


1. Declaration of Arrays:
Array variables are declared similar to ordinary variables declaration, except that the variable
name is followed by size in square brackets [ ].
Syntax: DataType NameOfArray [SizeOfArray];
Example: int a[3];
Here int is the data type, a is the array name and 3 is the
size of the array.

DataType: It specifies what kind of values stored in that array.


NameOfArray: It specifies the array name.
SizeOfArray: It specifies the maximum number of elements to be stored in an array.
2. Insert values into an Array:
Once an array has been initialized the elements can be inserted into them by using
the array's index value. The index defines the position of each element in the array. The first element
is at 0, the second element at 1 and so on. It's important to note that the index of the first element is 0.
To insert values in the array, there are two ways

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”;

Marks[0] Marks[1] Marks[2] Marks[3] Marks[4]


Marks 45 36 58 71 82

Name[0] Name[1] Name[2] Name[3] Name[4]


Name J o h n \0

ii. Inputting the values from the keyboard.


An array can be filled by inputting values from the keyboard. In this method, we can use any looping
statement. These loops are executed for each element of the array.
Example:
int i, marks[10];
for (i=0; i<=10; i++)
{
scanf(“%d”, &marks[i]);
}

3. Accessing elements of the array (Reading the elements of the array):


Elements of an array are accessed by specifying the index of the desired element within square [ ]
brackets after the array name. Array index value must be of integer type. Array Index value start at zero
in C. To access all elements of the array, you must use a loop.

For Ex: int i, a[6]={45,36,58,71,82,69};


for(i=0;i<6;i++)
{
Printf(“\d\t”,a[i]);
}

4. Calculating length of the array:


Length of the array is given by the number of elements stored in it. The general formula to
calculate the length of the array is Length = Upper bound - Lower bound + 1;
Where upper bound is the index (last index) and lower bound is the index of the first element in the
array. Usually lower bound is zero.

Page: 31
Example: int a[5];

Here a[0], a[1], a[2], a[3], a[4] are elements of the array.

0 is the lower bound


4 is the upper bound
Length = upper bound - lower bound + 1
= 4-0+1
=5

3. What are the Actions that can be performed on arrays?

The operations can be performed on arrays are:


1. Traversal
2. Search
3. Sort
4. Insertion
5. Deletion
6. Merging
1. Traversal: Traversal means accessing each and every element of the array for a specific purpose.
Traversal of an array is useful for counting the total number of elements, accessing the elements,
performing any operations on these elements and displaying every element.
2. Search: Searching can be defined as given element is present or not in a given list of array elements.
If the value is present in the array, the searching is said to be successful otherwise if the value is not
present in the array. There are two popular methods for searching .The are Linear search and Binary
search.
3. Sorting: It is an operation that can be performed on list array elements. The main purpose of this
operation is to arrange the list of elements in ascending or descending order.
4. Insertion: Insertion is an operation is used to insert the element in the list of array elements at a
specified position. This method also provides the inserting the element at the starting of the array,
ending of the array and anywhere in the array.
5. Deletion: Deleting an element from the array means removing the data element from the existing
array. The deleting of the element at a specified position is possible by using the different mechanisms.
6. Merging: Merging of two arrays in a third array means that first coping the contents of the first array
into third array and then copying the contents of the 2nd array into 3rd array. Hence the merged array
(3rd array) contains the contents of the first array followed by the contents of the 2nd array.

4. What are the different types of Arrays explain in detail?


Arrays are classified into three types according to the index of an array.
1. One dimensional array.
2. Two dimensional arrays.
3. Multi dimensional arrays.

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.

Operations on One Dimensional Array:


i. Declaration: To declare one dimensional array using the following syntax.
Syntax: DataType ArrayName[Size of array or Index];
Example: int Marks[10];
Here Marks is an array name. It contains all elements are integer type and maximum index size is 10.
ii. Initialization: Once an array has been initialized the elements can inserted into them by using
the array's index value. The index defines the position of each element in the array. The first element
is at 0. Insert the values into array in different ways
Syntax: Datatype Arrayname[Index]= {value1,value2,….,value n}

Example: int Marks[5]={64,55,48,34,47}

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)

Programs based on two dimensional arrays:


Write a C-Program to perform Addition of two Matrices.

#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();
}

OUTPUT: enter the order of matrix A


2 2
enter the order of matrix B
2 2
enter A matrix elements
3 4
5 6
enter B matrix elements
5 6
7 8
the multiplication of two matrices is
43 50
67 78

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'}

Read the String from key board


You can use the scanf() function to read a string. The scanf() function reads the sequence of
characters until it encounters whitespace (space, newline, tab etc.).
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

2. What are the different String Handling Functions supported by C language?


To perform manipulations on string data, there are built- in functions supported by C language. These
functions are available in <string.h> header file
The following are some of the string handling functions are:
1. strlen(s1) 2. strcmp(s1,s2) 3. strcpy(s1,s2) 4. strcat(s1,s2)
5. strlwr(s1) 6. strupr(s1) 7. strstr(s1) 8. strrev(s1)

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

3. What are the different Character functions supported by C language?


A character constant is represented as a character in a single quote. The value of character
constant is an integer. For example, a is represented as 'a' which is actually the integer value equal to
97 in ASCII.
Similarly, '\n' represents the integer value of newline equal to 10 in ASCII. C provides standard
character handling library <ctype.h>.
C programming character library functions with description

islower( ch ); It returns a true if ch is a lowercase letter and 0 otherwise.

isupper( ch ); It returns a true value if ch is a uppercase and 0 therwise.

tolower( ch ); This function converts uppercase letter into lowercase letter.

toupper( ch ); This function converts lowercase letter into uppercase letter.

isblank( ch ); This function checks whether ch is a blank character or not.

isdigit( ch ); This function checks whether ch is a digit or not.

isalpha ( ch ); This function checks whether ch is a letter or not.

isalnum( ch ); This function returns a 1 if ch is a digit or a letter and 0 otherwise.

isxdigit( ch ); This function checks if ch is a hexadecimal digit or not.

isspace( ch ); This function checks if ch is a whitespace character or not.

isgraph( ch ); This function checks if ch is a printing character other than a space or not.

iscntrl( ch ); This function checks if ch is a control character or not.

isprint( ch ); This function checks if ch is a printing character including 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 () {

int var = 20; /* actual variable declaration */


int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

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 () {

int *ptr = NULL;

printf("The value of ptr is : %x\n", ptr );

return 0;
}
When the above code is compiled and executed, it produces the following result:
The value of ptr is 0

3. Explain the Pointer Arithmetic in detail?


Pointer arithmetic: We can perform arithmetic operations on the pointers like addition, subtraction,
etc. However, as we know that pointer contains the address, the result of an arithmetic operation
performed on the pointer will also be a pointer if the other operand is of type integer. Following
arithmetic operations are possible on the pointer in C language:
o Increment
o Decrement
o Addition
o Subtraction
o Comparison
1. Incrementing Pointer in C: If we increment a pointer by 1, the pointer will start pointing to the
immediate next location. This is somewhat different from the general arithmetic since the value of the
pointer will get increased by the size of the data type to which the pointer is pointing.
Example1: int* i; In this case, pointer will be of 2 bytes. And when we increment it, it will
i++; increment by 2 bytes because int is also of 2 bytes.
Example2: float* i; In this case, size of pointer is still 2 bytes initially. But now, when we
i++; increment it, it will increment by 4 bytes because float datatype is of 4
bytes.

2. Decrementing Pointer in C: Like increment, we can decrement a pointer variable. If we decrement


a pointer, it will start pointing to the previous location.

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):

Type Size (in bytes)

int or signed int 2

char 1

long 4

float 4

double 8

long double 10

4. Briefly discuss about Dynamic memory allocation.


There are two types of memory allocation.
1. Static memory allocation: In this method memory is allocated by the compiler before you start the
execution of the program. Exact size and type of memory must be known at compile time.
2. Dynamic memory allocation: In this method memory is allocated during run time.
C provides some functions to achieve these tasks. There are 4 library functions provided by C defined
under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are:

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.

Realloc() It is used to modify the size of previously allocated memory space.

Free() Frees or empties the previously allocated memory space.

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);

5. Briefly discuss about Call by Value and Call by Reference.


There are two ways in which passing parameters to the function
1. Call by value: In which values of the variables are passed by the calling function to the called
function.
2. Call by reference: In which address of the variables are passed by the calling function to the
called function.
Page: 46
call by value call by reference
While calling a function, we pass values of While calling a function, instead of passing the
variables to it. values of variables, we pass address of variables.
In this method, the value of each variable in In this method, the address of actual variables in
calling function is copied into corresponding the calling function is copied into the dummy
dummy variables of the called function. variables of the called function.
With this method, the changes made to the
With this method, using addresses we would have
dummy variables in the called function have no
an access to the actual variables and hence we
effect on the values of actual variables in the
would be able to manipulate them.
calling function.
#include <stdio.h> #include <stdio.h>
main() main()
{ {
int a = 10, b = 20; int a = 10, b = 20;
swapx(a, b); swapx(&a, &b);
printf("a=%d b=%d\n", a, b); printf("a=%d b=%d\n", a, b);
return 0; return 0;
} }
swapx(int x, int y) swapx(int* x, int* y)
{ {
int t; int t;
t = x; t = *x;
x = y; *x = *y;
y = t; *y = t;
printf("x=%d y=%d\n", x, y); printf("x=%d y=%d\n", *x, *y);
} }

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;
};

Example: struct student


{
int rollno;
char sname;
float fees;
};

Creating structure member/variable/element: The purpose of structure variable is to access data


member in a structure to create structure variable.
Syntax: struct <tagname> <struct variable>;
Example: struct student stu1;
Accessing structure elements: Each member of a structure can be used just like a normal variable, but
its name will be little bit longer. A structure member variable is generally accessed using dot ( .)
operator.
Syntax : structure_varname.member_name
Example: stu1.rollno;

Page: 48
stu1.sname

Initializing Structure: Structure variables can be initialized at compile time.It includes


o Keyword “struct”.
o Tag
o Variable name
o Assignment operator (=).
o Members separated by commas enclosed in braces.
o Terminating with semi colon.
Syntax: <struct> <tagname> <structure variable>={ value1,value2,…………….};
Example: struct employee
{
int empno;
char name [20];
}emp1, emp2;
struct employee emp1=[346, “ kavitha”};
struct employee emp2={5,” ranjana”};
2. Write a C-Program to read and display the information about a student using structures
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
struct student
{
int rollno;
char sname[20];
float fees;
char DOB[30];
};
struct student stud1;
printf("\n enter the rollno: ");
scanf("%d",&stud1.rollno);
printf("\n enter the name of student: ");
scanf("%s",&stud1.sname);
printf("\n enter the fees: ");
scanf("%f",&stud1.fees);
printf("\n enter the date of birth: ");
scanf("%s",&stud1.DOB);
printf("\n * * * STUDENT DETAILS * * *");
printf("\n Roll no=%d",stud1.rollno);
printf("\n Student name=%s",stud1.sname);

Page: 49
printf("\n Student fees=%f",stud1.fees);
printf("\n DOB is=%s",stud1.DOB);
}

Output: enter the rollno: 1601


enter the name of student: rambabu
enter the fees: 12000
enter the date of birth: 26-05-1987
* * * STUDENT DETAILS * * *
Roll no=1601
Student name=rambabu
Student fees=12000.000000
DOB is=26-05-1987

3. What is a Nested Structure?


A structure can be paced with in another structure i.e. a structure may contain another structure as
its member. A structure that contains another structure as its member is called a nested structure.
4. Define Array of Structures.
To declare an array of structures, a structure is first defined, and then an array variable of that
type is declared. C permits the use of arrays as structure members. We have already used arrays of
characters inside a structure.
Array of structures is nothing but collection of structures.
Structure is collection of different data type. A variable of type structure represents a single
record in memory, if we want more than one record of structure type, we have to create an array of
structure.

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;

5. What is the Difference Between Structure and Union?

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.

struct struct_name{ union u_name{


type element1; type element1;
type element2; type element2;
Declaration
. .
. .
} variable1, variable2, ...; } variable1, variable2, ...;
struct student union employee
{ {
Example
int rollno; int eno;
int age; float salary;
Page: 51
char sex; char sex;
}a,b; }a,b,c;

6. Briefly discuss about Enumerated Data Types.


It is a user defined data type based on the standard integer type, an enumeration is a set of
named integer constants that specify all the legal values of a variable of that type may have. To define
enumerated data types, we use the key word enum, which is the abbreviation for enumerate.
Enumerations create new data type to contain values that are not limited to the values that the
fundamental data type may take.
Syntax: enum enumeration_name{identifier1,identifier2,……..identifier n};
Example: enum emp e1,e2;
enum colors{red, blue, black, green}
Declaration: enum <tagname> <enumeration list> <variable list>
This is also similar declaration of structures and unions.
enum variables: C also permits the user to declare variables of an enumerated data type in the same
way as we create variables of other basic data types.
The syntax for declaring a variable of an enumerated data type can be given as
enumeration_name variable_name
Example: enum colors bg_color;

7. Write about type def keyword


typedef is a keyword used in C language to assign alternative names to existing datatypes. Its
mostly used with user defined datatypes, when names of the datatypes become slightly complicated to
use in programs. Following is the general syntax for using typedef,
Syntax: typedef <existing_name> <alias_name>
Example: typedef unsigned long ulong;
The above statement defines a term ulong for an unsigned long datatype. Now this ulong identifier can
be used to define unsigned long type variables.
Example: ulong I, j;

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

You might also like