You are on page 1of 31

Code No: R19ES1101 R19 SET-1

I B. Tech I Semester Supplementary Examinations, November - 2020

PROGRAMMING FOR PROBLEM SOLVING USING C

1.a) Devlop an algorithm for sum of digits in a given number. Draw a flow chart for it.

Algorithm:

Step 1: Start

Step 2: Enter the number

Step 3: Calculate the modulus/remainder of the number.

Step 4: Add the remainder of the number to sum.

Step 5: Divide the number by 10.

Step 6: Repeat the step 3 while number is greater than 0.

Step 7: Stop
Flowchart:
1.b) Define algorithm? Write the characteristics of an algorithm.

An algorithm is an effective step-by-step procedure for solving a problem in a finite


number of steps. In other words, it is a finite set of well-defined instructions or step-by-step
description of the procedure written in human readable language for solving a given problem.
An algorithm itself is division of a problem into small steps which are ordered in sequence
and easily understandable.

Algorithms are very important to the way computers process information, because a
computer program is basically an algorithm that tells computer what specific tasks to perform
in what specific order to accomplish a specific task. The same problem can be solved with
different methods. So, for solving the same problem, different algorithms can be designed. In
these algorithms, number of steps, time and efforts may vary more or less.

How to design an algorithm?

In order to write an algorithm, following things are needed as a pre-requisite:

1. The problem that is to be solved by this algorithm.


2. The constraints of the problem that must be considered while solving the problem.
3. The input to be taken to solve the problem.
4. The output to be expected when the problem the is solved.
5. The solution to this problem, in the given constraints.
Characteristics of an algorithm:

Important characteristics to be considered while designing an algorithm for any program are
as follows:

• Clear and Unambiguous: Algorithm should be clear and unambiguous. Each of its
steps should be clear in all aspects and must lead to only one meaning.
• Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined
inputs.
• Well-Defined Outputs: The algorithm must clearly define what output will be yielded
and it should be well-defined as well.
• Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite loops
or similar.
• Feasible: The algorithm must be simple, generic and practical, such that it can be
executed upon will the available resources. It must not contain some future technology,
or anything.
• Language Independent: The Algorithm designed must be language-independent, i.e. it
must be just plain instructions that can be implemented in any language, and yet the
output will be same, as expected.
2.a) Draw the flowchart to find the factorial of a given number.
2.b) Write the importance of precedence and associativity? Write the table for operator
precedence.
Operator precedence: It dictates the order of evaluation of operators in an expression.

For Example, Solve 10+2*3, 10+2*3 is calculated as 10+(2*3) and not as (10+2)*3.

Operator Associativity: It defines the order in which operators of the same precedence are
evaluated in an expression. Associativity can be either from left to right or right to left.

For example, ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the
expression “100/10*10” is treated as “(100/10)*10”.

Operators Precedence and Associativity are two characteristics of operators that determine
the evaluation order of sub-expressions in absence of brackets.

Operator Precedence Table: In C, each operator has a fixed priority or precedence in


relation to other operators. As a result, the operator with higher precedence is evaluated
before the operator with lower precedence. Operators that appear in the same group have the
same precedence. The following table lists operator precedence and associativity:

Operator Description Associativity


() Function call
[] Array subscript
. Dot or Member selection operator Left to Right
-> Member selectors
++ -- Postfix Increment/Decrement
++ -- Prefix Increment/Decrement
+- Unary plus and Minus
!~ Not operator & bitwise compliment
(type) Type cast Right to Left
* Indirection or dereference operator
& Address of operator
sizeof Determine size in bytes
* / % Multiplication, division, and Modulus Left to Right
+ - Addition and Substraction Left to Right
<< >> Bitwise left shift and right shift Left to Right
< <= Relational less than/less than or equal to
> >= Relational greater than/greater than or Left to Right
equal to
== != Relational equal to and not equal to Left to Right
& Bitwise AND Left to Right
^ Bitwise exclusive OR Left to Right
| Bitwise inclusive OR Left to Right
&& Logical AND Left to Right
|| Logical OR Left to Right
? : Ternary operator Right to Left
= Assignment Operator
+= -= Addition/Substraction Assignment
*= /= Multiplication/division Assignment Right to Left
%= &= Modulus and bitwise Assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>=
, Comma operator Left to Right

3.a) List and explain various Looping statements available in C with Example.

Programming languages provide various control structures that allow for more complicated
execution paths.

Loops in programming come into use when we need to repeatedly execute a block of
statements. A loop statement allows us to execute a statement or group of statements
multiple times. Given below is the general form of a loop statement in most of the
programming languages:
C programming language provides the following types of loops to handle looping
requirements:

1. For loop:

Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.

Syntax:

for(initialization; testExpression; updateStatement)

//Statements inside the body of loop

How for loop Works?

• Initialization statement executes only once.


• Then, the test expression is evaluated. If the test expression is false, the for loop is
terminated.
• However, if the test expression is evaluated to true, statements inside the body of for
loop are executed and the update expression is updated.
• Again test expression is evaluated.

Example:
#include<stdio.h>
Void main()
{
int i;
for(i=0;i<11;i++)
{
printf(“d”, i);

Output: 1 2 3 4 5 6 7 8 9 10

2. While loop:

Repeats a statement or group of statements while a given condition is true. It tests


the condition before executing the loop body.

Syntax:

While(test expression)

//Statements inside the body of the loop

How while loop works?

• The while loop evaluates the test expression inside the parenthesis ().
• If the test expression is true, statements inside the body of while loop are
executed. Then the test expression is evaluated again.
• The process goes on until the test expression is evaluated to false.
• If the test expression is false, the loop terminates.
Example:

#include<stdio.h>

Void main()

int i=1;

while(i<=5)

Printf(“%d”, i);

++i;

Output: 1 2 3 4 5

3. do…While loop:

It is more like a while statement, except that it tests the condition at the end of the loop body.

Syntax:

do

//Statements inside the body of the loop

}while(test expression);

How do…while loop works?

• The body of do…while loop is exexuted once. Only then, the test expression is
evaluated.
• If the test expression is true, the body of the loop is executed again and the test
expression is evaluated.
• This process goes on until the test expression becomes false.
• If the test expression is false, the loop terminates.
Example:

#include<stdio.h>

Void main()

int n,sum=0;

do

printf(“Enter a number:”);

scanf(“%d”, &n);

sum+=n;

} while(n!=0);

printf(“Sum = %d”, sum);

Output:

Enter a number: 10

Enter a number: 20

Enter a number: 30

Enter a number: 40

Enter a number: 0

Sum = 100

4. Nested Loops:

You can use one or more loops inside any other while, for, or do..while loop.
3.b) Develop a program to check whether the given number is Armstrong number or
not?

Program to check whether a given 3-digit number is amstrong or not:

#include <stdio.h>

int main()

int num, temp, i, sum = 0;

printf(“Enter a three-digit number: “);

scanf(“%d”, &num);

temp = num;

while (temp != 0)

i = temp % 10;

sum += i * i * i;

temp /= 10;

if (sum == num)

printf(“%d is an Armstrong number.”, num);

else

printf(“%d is not an Armstrong number.”, num);

return 0;

Output: Enter a three-digit number: 153

153 is an Armstrong number.


Program to check whether a given n-digit number is amstrong or not:

#include<stdio.h>

#include<math.h>

int digi(long int);

int main()

long int n,s=0;

int a,t,d;

printf(“Enter a value : “);

scanf(“%ld”,&n);

t=n;

d=digi(n);

while(t>0)

a=t%10;

s=s+pow(a,d);

t=t/10;

if(n==s)

printf(“Given number is Armstrong\n”);

else

printf(“Given number is not Armstrong\n”);

return 0;

}
int digi(long int t)

int dig=0;

while(t>0)

dig++;

t=t/10;

return dig;

Output:

Enter a value : 1634

Given number is Armstrong.

4.a) Develop a program for the printing the following pattern on the screen.

* *

* * *

* * * *

Program:

#include <stdio.h>

void main()

int i, j, num;
printf("\nEnter number of rows:");

scanf("%d", &num);

for(i=0;i<=num;i++)

for(j=0;j<=i;j++)

printf("*");

printf("\n");

Output:

Enter number of rows: 4

* *

* * *

* * * *

4.b) Differentiate between Implicit Conversion and Explicit Conversion? Give


appropriate example.

Implicit Conversion Explicit Conversion


Implicit Conversion is done automatically. Explicit Conversion is done programatically.
In Implicit conversion, no data loss take In explicit conversion, data loss may or may
place during the data conversion. not be take place during data conversion.
Hence there is a risk of information loss.
No possibility of throwing exception during It might throw error if tried to do
the conversion and therefore is called type without type casting.
safe
Implicit conversion do not require Explicit conversion do require cast
any special syntax. operator to perform conversion.
Example : Example :
Conversion of smaller number to larger Conversion of larger number to smaller
number is implicit conversion. number is explicit conversion.
Conversion of integer type data to float. float Float k=123.456
i=0;
int j=10; int i= (int) k

i=j;

5.a) Develop a C program to multiply two ‘m × n’ matrices. Cover all necessary


conditions.

Program:

#include<stdio.h>

int main()

int m1, n1, m2, n2;

int a[10][10], b[10][10], c[10][10], i, j, k;

printf(“Enter size of 1st matrix:\n”);

scanf(“%d%d”, &m1, &n1);

printf(“Enter size of 2nd matrix:\n”);

scanf(“%d%d”, &m2, &n2);

if(m2!=n1)

printf(“Multiplication is not possible for these matrices\n”);


return 0;

printf(“Enter First Matrix:\n”);

for(i=0;i<m1;i++)

for(j=0;j<n1;j++)

scanf(“%d”,&a[i][j]);

printf(“Enter Second Matrix:\n”);

for(i=0;i<m2;i++)

for(j=0;j<n2;j++)

scanf(“%d”,&b[i][j]);

printf(“Multiplication of two Matrices is:\n”);

for(i=0;i<m1;i++)

for(j=0;j<n2;j++)

c[i][j]=0;

for(k=0;k<n1;k++)

c[i][j]=c[i][j]+(a[i][k]*b[k][j]);

printf(“%d\t”,c[i][j]);

printf(“\n”);

return 0;

}
Output 1:

Enter size of 1st matrix:

2 3

Enter size of 2nd matrix:

3 2

Enter First Matrix:

1 2 3

4 5 6

Enter Second Matrix:

1 2

2 3

0 5

Multiplication of two Matrices is:

5 23

14 53

Output 2:

Enter size of 1st Matrix:

2 3

Enter size of 2nd Matrix:

2 2

Multiplication is not possible for these matrices


5.b) Develop a program to find the length of the string without using predefined
functions.

Program:

#include <stdio.h>

#include<string.h>

void main()

int i, l=0;

char str[50];

printf("Enter the string:");

scanf("%s", str);

for(i=0;str[i]!='\0';i++)

l++;

printf("Length of the string %s is %d", str, l);

Output:

Enter the string: computer

Length of the string computer is 8


6.a) Develop a program to count sum of even numbers in a given array.

Program:

#include <stdio.h>

int main(){

int arr[10], i, n, sum=0;

printf("Enter size of array:");

scanf("%d",&n);

printf("Elements in array:");

for(i=0;i<n;i++)

scanf("%d",&arr[i]);

for(i=0;i<n;i++)

if(arr[i]%2==0)

sum+=arr[i];

printf("Sum of even numbers in an array is %d",sum);

return 0;

Output:

Enter the size of array: 6

Elements in array: 2 3 4 5 6 7

Sum of even numbers in the array is 12


6.b) Differentiate one dimensional array and two dimensional arrays with example.

One-dimensional array Two-dimensional array


A simple data structure that stores a A type of array that stores multiple data
collection of similar type data in a contiguous elements of the same type in matrix or table
block of memory. format with a number of rows and columns.
Stores a single list of the element of a similar Store a “list of lists” of the element of a
data type. similar data type.
Size of one-dimensional(1-D) array is Total Size of two-dimensional(2-D) array is
Bytes=sizeof(datatype of array variable)*size Total Bytes = sizeof(datatype of array
of array. variable)*size of first index*size of second
index.
Syntax: Syntax:
data_type array_name[size]; Data_type array_name[size][size];
Example: int array[10]; Example int array[10][10];

Example for one-dimensional array:

#include<stdio.h>

Void main()

int arr[5], i, n;

printf(“Enter array elements:”);

for(i=0;i<5;i++)

scanf(“%d”, &arr[i]);

printf(“Array elements are:”);

for(i=0;i<5;i++)

printf(“%d\t”, arr[i]);

}
Example for two-dimensional array:

#include<stdio.h>

Void main()

int arr[5][5], i, n;

printf(“Enter array elements:”);

for(i=0;i<5;i++)

for(j=0;j<5;j++)

scanf(“%d”, &arr[i][j]);

printf(“Array elements are:”);

for(i=0;i<5;i++)

for(j=0;j<5;j++)

printf(“%d\t”, arr[i][j]);

7.a) Develop a C program to swap two numbers using pointers.

Program:

#include <stdio.h>

int main()

int *p, *q, a, b, temp;

printf("\nEnter the values to be swapped:");

scanf("%d %d", &a, &b);

p=&a;

q=&b;
temp=*p;

*p=*q;

*q=temp;

printf("Values after swapping:%d \t %d",a,b);

return 0;

Output:

Enter the values to be swapped: 4 5

Values after swapping: 5 4

7.b) How to pass pointer variables as function arguments? Illustrate.

C programming allows passing a pointer to a function. To do so, simply declare the function
parameter as a pointer type.

Pointer as a function parameter is used to hold addresses of arguments passed during function
call. This is also known as call by reference. When a function is called by reference any
change made to the reference variable will effect the original variable.

Following is a simple example where we pass an unsigned long pointer to a function and
change the value inside the function which reflects back in the calling function –

#include<stdio.h>

Void addOne( int *ptr)

(*ptr)++;

int main()

int *p, i=10;


p=&i;

addOne(p);

printf(“%d”, *p);

return 0;

Output: 11

Here, the value stored at *p is 10 initially.

We then passed the pointer p to the addOne() function. The ptr pointer gets this address in the
addOne() function.

Inside this fiunction, we increased the value stored at ptr by 1 using (*ptr)++;. Since ptr and p
pointers both have the same address, *p inside main() is also 11.

8.a) What is pointer? How to initialize and declare pointer variables? Explain with
examples.
Pointer is a variable that stores the address of another variable. C pointer is used to allocate
memory dynamically i.e. at run-time. The variable might be any of the data type such as int,
float, char, double, short etc.

Like any variable or constant, you must declare a pointer before using it to store any variable
address.

Declaration of Pointer variable:

The general syntax of pointer declaration is,

data_type *pointer_name;

The data type of the pointer and the variable to which the pointer variable is pointing must be
the same.

Initialization of Pointer variable:

Pointer Initialization is the process of assigning address of a variable to a pointer variable. It


contains the address of a variable of the same data type. In C language address operator & is
used to determine the address of a variable. The & (immediately preceding a variable name)
returns the address of the variable associated with it.
Example:

int a;

int *ptr; //Pointer declaration

ptr=&a; //Pointer Initialization

Example Program to demonstrate Pointers:

#include stdio.h>

int main()

int a;

int *ptr;

a=110;

ptr=&a;

//Prints the Value of a

printf(“%d\n”, a);

printf(“%d\n”, *ptr);

//Prints the address of a

printf(“%u\n”, &a);

printf(“%u\n”, ptr);

printf(“%u\n”, &ptr); \\ Prints address of ptr

return 0;

Output:

110

110
3795480300

3795480300

3795480304

8.b) Develop a C Program to Access Elements of an Array Using Pointer.

Program:

#include <stdio.h>

int main()

int arr[10], n, i;

int *ptr;

printf("\nEnter size of array:");

scanf("%d", &n);

printf("Enter Elements of an array:");

for(i=0; i<n; i++)

scanf("%d",&arr[i]);

ptr=&arr[0];

printf(“Elements of array are:”);

for(i=0; i<n; i++)

printf("%d\t", *(ptr+i));

return 0;
}

Output:

Enter size of array: 5

Enter elements of array: 10 20 30 40 50

Elements of the array are:10 20 30 40 50

9.a) Explain various standard library functions for handling files.

File handling in C enables us to create, update, read, and delete the files stored on the local
file system through our C program. The following operations can be performed on a file.

• Creation of the new file


• Opening an existing file
• Reading from the file
• Writing to the file
• Deleting the file

Functions for File handling:

There are many functions in the C library to open, read, write, search and close the file. A list
of file functions are given below:

S.No Function Description

1 fopen() Opens new or existing file

2 fprintf() Write data into the file

3 fscanf() Reads data into the file

4 fputc() Writes a character into the file

5 fgetc() Reads a character from file

6 fclose() Closes the file

7 fseek() Sets the file pointer to given position

8 fputw() Writes an integer to file

9 fgetw() Reads an integer from file


10 ftell() Returns current position

11 rewind() Sets the fil pointer to the beginning of the file

Opening a file:

fp=fopen(filename, mode);

The filename and mode both are strings.

Here modes can be:

Mode Description

r Opens a text file in read mode

w Opens a text file in write mode

a Opens a text file in append mode

r+ Opens a text file in read and write mode

w+ Opens a text file in read and write mode

a+ Opens a text file in read and write mode

rb Opens a binary file in read mode

wb Opens a binary file in write mode

ab Opens a binary file in append mode

rb+ Opens a binary file in read and write mode

wb+ Opens a binary file in read and write mode

ab+ Opens a binary file in read and write mode


9.b) Assume that there are two text files say a.txt and b.txt. Develop simple C code copy
the text from a.txt to b.txt.

Program:

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;

printf("Enter the filename to open for reading \n");


scanf("%s", filename);

fptr1 = fopen(filename, "r");


if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
Output:
Enter the filename to open for reading

a.txt

Enter the filename to open for writing

b.txt

Contents copied to b.txt

10.a) Define File? Briefly explain various modes and operations on files with examples.

A file is a space in a memory where data is stored. 'C' programming provides various
functions to deal with a file. A mechanism of manipulating with the files is called
as file management. A file must be opened before performing operations on it. A file can be
opened in a read, write or an append mode.

The following are the various modes for opening a file:

• r - open a file in read mode.


• w - opens or create a text file in write mode.
• a - opens a file in append mode.
• r+ - opens a file in both read and write mode.
• a+ - opens a file in both read and write mode.
• w+ - opens a file in both read and write mode.
• rb- Opens a binary file in read mode.
• wb- Opens a binary file in write mode.
• ab- Opens a binary file in append mode.
• rb+- Opens a binary file in read and write mode.
• wb+ - Opens a binary file in read and write mode.
• ab+ - Opens a binary file in read and write mode.
Different operations that can be performed on a file are:
• Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
• Opening an existing file (fopen)
• Reading from file (fscanf or fgets)
• Writing to a file (fprintf or fputs)
• Moving to a specific location in a file (fseek, rewind)
• Closing a file (fclose)
10.b) How to pass an array to a function? Explain with a code snippet.
In C, there are various general problems which requires passing more than one variable of
the same type to a function. For example, consider a function which sorts the 10 elements in
ascending order. Such a function requires 10 numbers to be passed as the actual parameters
from the main function. Here, instead of declaring 10 different numbers and then passing into
the function, we can declare and initialize an array and pass that into the function. This will
resolve all the complexity since the function will now work for any number of values.

Methods to declare a function that receives an array as an argument:

There are 3 ways to declare the function which is intended to receive an array as an argument.

• return_type function(type arrayname[])


• return_type function(type arrayname[SIZE])
• return_type function(type *arrayname)

When we pass an array to a function say fun(), it is always treated as a pointer by fun().
Consider the following example:

#include <stdio.h>
void fun (int arr[ ])
{
unsigned int n = sizeof(arr)/sizeof(arr[0]);
printf("\nArray size inside fun() is %d", n);
}
int main()
{
int arr[ ] = {1, 2, 3, 4, 5, 6, 7, 8};
unsigned int n = sizeof(arr)/sizeof(arr[0]);
printf("Array size inside main() is %d", n);
fun(arr);
return 0;
}
Output:
Array size inside main() is 8

Array size inside fun() is 1

You might also like