New Microsoft Office Word Document

Post on 12-Jan-2016

212 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

manual

Transcript

Q1. Write a program that prints the square of an integer.

#include <stdio.h>

#include <conio.h>

void main()

{

int n=0;

printf("\n\nEnter a number: ");

scanf("%d", &n);

n=n*n;

printf("\nThe square is %d ", n);

getch();

}

Q2. Write a program to check whether the given number is a Palindrome.

#include<stdio.h>

#include<conio.h>

void main()

{

int n;

printf("Enter a Number: ");

scanf("%d",&n);

int n1,mod;

n1=n;

int rev=0;

while(n>0)

{

mod = n%10;

rev = rev * 10 + mod;

n = n / 10;

}

if (n1 == rev)

printf("Number is Palindrome\n");

else

printf("Number is not Palindrome");

getch();

}

Q3. Write a program to multiply two matrices of any order.

// Matrix Multiplication

#include <stdio.h>

#include <stdlib.h>

#include <conio.h>

//Global Variables.

int **matrix[2];

int **ResultMatrix;

int row[3], col[3];

//Function Declarations.

void ErrorExit(char *msg);

void InitMatrix(int MatrixNo,int r,int c);

void ReadMatrix(int MatrixNo,int r,int c);

void PrintMatrix(int MatrixNo,int r,int c);

void freeMatrix(int MatrixNo,int r);

void MultiplyMatrix();

int main()

{

printf("\n\t/================================================\\");

printf("\n\t| C Program for Matrix Multiplication |");

printf("\n\t\\================================================/");

printf("\n\nFor first matrix.");

printf("\nEnter number of rows: ");

scanf("%d",&row[0]);

printf("Enter number of columns: ");

scanf("%d",&col[0]);

printf("\nFor Second matrix.");

printf("\nEnter number of rows: ");

scanf("%d",&row[1]);

printf("Enter number of columns: ");

scanf("%d",&col[1]);

if(col[0] != row[1])

{

ErrorExit("\n\nERROR:: Number of Columns in First matrix must be equal to \n\t\tnumber of ROWs in second matrix.");

}

row[2] = row[0];

col[2] = col[1];

InitMatrix(0,row[0],col[0]);

InitMatrix(1,row[1],col[1]);

InitMatrix(2,row[2],col[2]);

ReadMatrix(0,row[0],col[0]);

ReadMatrix(1,row[1],col[1]);

MultiplyMatrix();

printf("\nMatrix 1:");

PrintMatrix(0,row[0],col[0]);

printf("\n\nMatrix 2:");

PrintMatrix(1,row[1],col[1]);

printf("\n\nResultant Matrix:");

PrintMatrix(2,row[2],col[2]);

freeMatrix(0,row[0]);

freeMatrix(1,row[1]);

freeMatrix(2,row[2]);

printf("\n\n\nPress any key to exit....");

getch();

return 0;

}

void InitMatrix(int MatrixNo,int r,int c)

{

int i;

if(MatrixNo != 2)

{

matrix[MatrixNo] = (int **)calloc(r,sizeof(int));

if(matrix[MatrixNo] == NULL)

ErrorExit("Insufficient Memory.");

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

{ matrix[MatrixNo][i] = (int *)calloc(c, sizeof(int));

if(matrix[MatrixNo][i] == NULL)

ErrorExit("Insufficient Memory.");

}

}

else

{

ResultMatrix = (int **)calloc(r,sizeof(int));

if(ResultMatrix == NULL)

ErrorExit("Insufficient Memory.");

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

{

ResultMatrix[i] = (int *)calloc(c, sizeof(int));

if(ResultMatrix[i] == NULL)

ErrorExit("Insufficient Memory.");

}

}

}

void ReadMatrix(int MatrixNo,int r,int c)

{

int i,j;

printf("\nEnter matrix elements:");

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

{

printf("\nRow No %d \'s %d elements:",i+1,c);

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

scanf("%d",&matrix[MatrixNo][i][j]);

}

}

void PrintMatrix(int MatrixNo,int r,int c)

{

int i,j;

if(MatrixNo != 2)

{

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

{

printf("\n\t|");

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

printf("%d",matrix[MatrixNo][i][j]);

printf("|");

}

}

else

{

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

{

printf("\n\t| ");

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

printf("%d ",ResultMatrix[i][j]);

printf("|");

}

}

}

void ErrorExit(char *msg)

{

printf(msg);

getch();

exit(0);

}

void freeMatrix(int MatrixNo,int r)

{

int i;

if(MatrixNo != 2)

{

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

free(matrix[MatrixNo][i]);

free(matrix[MatrixNo]);

}

else

{

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

free(ResultMatrix[i]);

free(ResultMatrix);

}

}

void MultiplyMatrix()

{

int i,j,k;

for(i=0;i<row[2];i++)

for(j=0;j<col[2];j++)

for(k=0;k<col[0];k++)

ResultMatrix[i][j] += matrix[0][i][k] * matrix[1][k][j];

}

Q4. Write a program that will accept a string and character to search. The program will call a function, which will search for the occurrence position of the character in the string and return its position. Function should return –1 if the character is not found in the input string.

Answer:

/Coded by Student for http://smu.covertbay.com/

#include <stdio.h>

#include <string.h>

#include <conio.h>

#include <stdlib.h>

int main ()

{

char str[100] = "";

char *p;

char ch;

int count=0;

printf("\tThis program searches for a character in the given string\n");

printf("\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n");

printf("Enter a string: ");

fflush(stdin);

scanf(("%[^\t\n]"), str);

printf("\nEnter a character to search: ");

scanf("%s", &ch);

printf ("\nSearching for '%s' character in '%s' ...\n", &ch,str);

p = strchr (str, ch);

int i;

const int end = strlen(str);

for(i = 0; i < end; ++i) {

if( str[i] == ch ) {

printf ("found at position %d\n",p - str + 1);

p = strchr(p + 1, ch);

++count;

}

}

/* while (p != NULL) //while loop stops when p = null

{

printf ("found at position %d\n",p - str + 1);

p = strchr(p + 1, ch);

count = count +1;

}

*/

printf("Occurence %d\n\n", count);

if(count==0)

{

printf("Character not found\n");

system("PAUSE");

return -1;

}

system("PAUSE");

return 0;

}

Q5. Write a program to implement a calculator to perform all the four basic arithmetic operations on integers.

Answer: Page No. 40

//Coded by Student http://smu.covertbay.com

#include <stdlib.h>

#include <stdio.h>

#include <conio.h>

int sum(int, int);

int sub(int, int);

int mul(int, int);

int div1(int, int);

int main() {

int a,b,d;

int ch;

printf("\t\tCalculator Implementation\n");

printf("\t\t~~~~~~~~~~~~~~~~~~~~~~~~~\n");

printf("\t\t 1: Add\n");

printf("\t\t 2: Sub\n");

printf("\t\t 3: Multiply\n");

printf("\t\t 4: Divide\n");

printf("\t\t 5: Exit\n\n\n");

printf("\t\t Enter the choice: ");

scanf("%d", &ch);

if(ch==5)

exit(0);

printf("\nEnter first number: ");

scanf("%d", &a);

printf("\nEnter Second number: ");

scanf("%d", &b);

printf("\na = %d; b = %d;\n", a, b);

printf("==============\n\n");

switch(ch)

{

case 1 :

d=sum(a,b);

printf("Sum %d + %d = %d",a,b,d);

break;

case 2:

d=sub(a,b);

printf("Subtraction %d - %d = %d",a,b,d);

break;

case 3:

d=mul(a,b);

printf("Multiplication %d * %d = %d",a,b,d);

break;

case 4 :

d=div1(a,b);

printf("Division %d / %d = %d",a,b,d);

break;

default:

printf("Invalid Choice!");

getch();

}

getch();

return 0;

}

int sum(int a, int b) {

return a + b;

}

int sub(int a, int b) {

return a - b;

}

int mul(int a, int b) {

return a * b;

}

int div1(int a, int b) {

return a / b;

}

Q6. Write a program to implement the Stacks using the concept of arrays.

Answer: Page No. 137

Q7. Write a program to implement linked lists using pointers.

Answer: Page No. 172

Q8. Write a program to implement the Minimum Spanning Tree Problem using Prim's Algorithm.

Answer: link

#include <stdio.h>

02.

03.

/*

04.

The input file (weight.txt) look something like this

05.

4

06.

0 0 0 21

07.

0 0 8 17

08.

0 8 0 16

09.

21 17 16 0

10.

11.

The first line contains n, the number of nodes.

12.

Next is an nxn matrix containg the distances between the nodes

13.

NOTE: The distance between a node and itself should be 0

14.

*/

15.

16.

int n; /* The number of nodes in the graph */

17.

18.

int weight[100][100]; /* weight[i][j] is the distance between node i and node j;

19.

if there is no path between i and j, weight[i][j] should

20.

be 0 */

21.

22.

char inTree[100]; /* inTree[i] is 1 if the node i is already in the minimum

23.

spanning tree; 0 otherwise*/

24.

25.

int d[100]; /* d[i] is the distance between node i and the minimum spanning

26.

tree; this is initially infinity (100000); if i is already in

27.

the tree, then d[i] is undefined;

28.

this is just a temporary variable. It's not necessary but speeds

29.

up execution considerably (by a factor of n) */

30.

31.

int whoTo[100]; /* whoTo[i] holds the index of the node i would have to be

32.

linked to in order to get a distance of d[i] */

33.

34.

/* updateDistances(int target)

35.

should be called immediately after target is added to the tree;

36.

updates d so that the values are correct (goes through target's

37.

neighbours making sure that the distances between them and the tree

38.

are indeed minimum)

39.

*/

40.

void updateDistances(int target) {

41.

int i;

42.

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

43.

if ((weight[target][i] != 0) && (d[i] > weight[target][i])) {

44.

d[i] = weight[target][i];

45.

whoTo[i] = target;

46.

}

47.

}

48.

49.

int main(int argc, char *argv[]) {

50.

FILE *f = fopen("dist.txt", "r");

51.

fscanf(f, "%d", &n);

52.

int i, j;

53.

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

54.

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

55.

fscanf(f, "%d", &weight[i][j]);

56.

fclose(f);

57.

58.

/* Initialise d with infinity */

59.

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

60.

d[i] = 100000;

61.

62.

/* Mark all nodes as NOT beeing in the minimum spanning tree */

63.

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

64.

inTree[i] = 0;

65.

66.

/* Add the first node to the tree */

67.

printf("Adding node %c\n", 0 + 'A');

68.

inTree[0] = 1;

69.

updateDistances(0);

70.

71.

int total = 0;

72.

int treeSize;

73.

for (treeSize = 1; treeSize < n; ++treeSize) {

74.

/* Find the node with the smallest distance to the tree */

75.

int min = -1;

76.

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

77.

if (!inTree[i])

78.

if ((min == -1) || (d[min] > d[i]))

79.

min = i;

80.

81.

/* And add it */

82.

printf("Adding edge %c-%c\n", whoTo[min] + 'A', min + 'A');

83.

inTree[min] = 1;

84.

total += d[min];

85.

86.

updateDistances(min);

87.

}

88.

89.

printf("Total distance: %d\n", total);

90.

91.

return 0;

92.

}

Q9. Write a program to implement the Single Source Shortest Path problem.

Answer: link

One Source Shortest Path: Dijkstra’s Algorithm

Posted by scvalex under Algorithms, Graphs, Greedy | Tags: algorithm, code, dijkstra, dijsktra's algorithm, explanation, graph, graph algorithms, Greedy, greedy algorithms, programming, sourcecode, tutorial |

[71] Comments

In this article I describe Dijkstra’s algorithm for finding the shortest path from one source to all the other vertexes in a graph. Afterwards, I provide the source code in C of a simple implementation.

To understand this you should know what a graph is, and how to store one in memory. If in doubt check this and this.

Another solution for this problem is the Bellman-Ford algorithm.

The Problem

Given the following graph calculate the length of the shortest path from node 1 to every other node.

Lets take the nodes 1 and 3. There are several paths (1 -> 4 -> 3, 1 -> 2 -> 3, etc.), but the shortest of them is 1 -> 4 -> 2 -> 3 of length 9. Our job is to find it.

The Algorithm

Dijkstra’s algorithm is one of the most common solutions to this problem. Even so, it only works on graphs which have no edges of negative weight, and the actual speed of the algorithm can vary from O(n*lg(lg(n))) to O(n2).

The idea is somewhat simple:

Take the length of the shortest path to all nodes to be infinity. Mark the length of the shortest path to the source as 0.

Now, we already know that the graph has no edges of negative weight so the a path of length 0 is the best we can come up with. The path to the source is 0, so it’s optimal.

This algorithm works by making the paths to one more node optimal at each step. So, at the kth step, you know for sure that there are at least k nodes to which you know the shortest path.

At each step, choose the node, which is not yet optimal, but which is closest to the source; i.e. the node to which the current calculated shortest path is smallest. Then, from it, try to optimise the path to every node connected to it. Finally, mark the said node as optimal (visited, if you prefer). In the previous example, the node which is closest to the source and is not yet optimal is the source. From it, you can optimise the path to nodes 2 and 4.

At this point, the only visited/optimal node is 0. Now we have to redo this step 4 more times (to ensure that all nodes are optimal).

The next node to consider is 4:

It’s worthwhile to note that at this step, we’ve also found a better path to node 2.

Next is node 2:

Finally, we look at nodes 5 and 3 (none of which offer any optimisations):

The actual code in C looks something like this:

void dijkstra(int s) {

int i, k, mini;

int visited[GRAPHSIZE];

for (i = 1; i <= n; ++i) {

d[i] = INFINITY;

visited[i] = 0; /* the i-th element has not yet been visited */

}

d[s] = 0;

for (k = 1; k <= n; ++k) {

mini = -1;

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

if (!visited[i] && ((mini == -1) || (d[i] < d[mini])))

mini = i;

visited[mini] = 1;

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

if (dist[mini][i])

if (d[mini] + dist[mini][i] < d[i])

d[i] = d[mini] + dist[mini][i];

}

}

The Programme

Putting the above into context, we get the O(n2) implementation. This works well for most graphs (it will not work for graphs with negative weight edges), and it’s quite fast.

Here’s the source code in C (dijkstra.c):

#include <stdio.h>

#define GRAPHSIZE 2048

#define INFINITY GRAPHSIZE*GRAPHSIZE

#define MAX(a, b) ((a > b) ? (a) : (b))

int e; /* The number of nonzero edges in the graph */

int n; /* The number of nodes in the graph */

long dist[GRAPHSIZE][GRAPHSIZE]; /* dist[i][j] is the distance between node i and j; or 0 if there is no direct connection */

long d[GRAPHSIZE]; /* d[i] is the length of the shortest path between the source (s) and node i */

void printD() {

int i;

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

printf("%10d", i);

printf("\n");

for (i = 1; i <= n; ++i) {

printf("%10ld", d[i]);

}

printf("\n");

}

void dijkstra(int s) {

int i, k, mini;

int visited[GRAPHSIZE];

for (i = 1; i <= n; ++i) {

d[i] = INFINITY;

visited[i] = 0; /* the i-th element has not yet been visited */

}

d[s] = 0;

for (k = 1; k <= n; ++k) {

mini = -1;

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

if (!visited[i] && ((mini == -1) || (d[i] < d[mini])))

mini = i;

visited[mini] = 1;

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

if (dist[mini][i])

if (d[mini] + dist[mini][i] < d[i])

d[i] = d[mini] + dist[mini][i];

}

}

int main(int argc, char *argv[]) {

int i, j;

int u, v, w;

FILE *fin = fopen("dist.txt", "r");

fscanf(fin, "%d", &e);

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

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

dist[i][j] = 0;

n = -1;

for (i = 0; i < e; ++i) {

fscanf(fin, "%d%d%d", &u, &v, &w);

dist[u][v] = w;

n = MAX(u, MAX(v, n));

}

fclose(fin);

dijkstra(1);

printD();

return 0;

}

And here’s a sample input file(dist.txt):

10

1 2 10

1 4 5

2 3 1

2 4 3

3 5 6

4 2 2

4 3 9

4 5 2

5 1 7

5 3 4

The graph is given as an edge list:

the first line contains e, the number of edges

the following e lines contain 3 numbers: u, v and w signifying that there’s an edge from u to v of weight w

That’s it. Good luck and have fun. Always open to comments.

Finding the shortest path

UPDATE In response to campOs‘ comment.

Now we know the distance between the source node and any other node (the distance to the ith node is remembered in d[i]). But suppose we also need the path (which nodes make up the path).

Look at the above code. Where is d modified? Where is the recorded distance between the source and a node modified? In two places:

Firstly, d[s] is initialised to be 0.

d[s] = 0;

And then, when a new shortest path is found, d[i] is updated accordingly:

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

if (dist[mini][i])

if (d[mini] + dist[mini][i] < d[i])

d[i] = d[mini] + dist[mini][i];

The important thing to notice here is that when you update the shortest distance to node i, you know the previous node in the path to i. This is, of course, mini. This suggests the solution to our problem.

For every node i other than the source, remember not only the distance to it, but also the previous node in the path to it. Thus we have a new array, prev.

Now, we need to make to modifications.

First, we initialise the value of prev[i] to something impossible (say -1) at the start of dijkstra().

for (i = 1; i <= n; ++i) {

d[i] = INFINITY;

prev[i] = -1; /* no path has yet been found to i */

visited[i] = 0; /* the i-th element has not yet been visited */

}

Secondly, we update the value of prev[i] every time a new shortest path is found to i.

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

if (dist[mini][i])

if (d[mini] + dist[mini][i] < d[i]) {

d[i] = d[mini] + dist[mini][i];

prev[i] = mini;

}

Good. For every node reachable from the source we know which node is just before it in the shortest path. For the above example, we would have the following array:

i - prev[i]

1 - -1

2 - 4

3 - 2

4 - 1

5 - 4

Using this, how do you get the path? Let’s say you want to get to 3. Which node comes right before 3? Node 2. Which node comes right before node 2? Node 4. Which node comes before 4? Node 1. We’ve reached the source, so we’re done. Go through this list backwards and you get the path: 1 -> 4 -> 2 -> 3. This is easily implemented with recursion.

void printPath(int dest) {

if (prev[dest] != -1)

printPath(prev[dest]);

printf("%d ", dest);

}

Here is the updated source: dijkstraWithPath.c.

Q10. Write a program to implement the Heapsort technique.

Answer: Page No. 275

top related