Write a Program to Display the Multiplication Table of a Given Number

24
1. Write a program to display the multiplication table of a given number. Program: Multiplication table of a given number view source print ? 01 #include <stdio.h> 02 int main() { 03 int num, i = 1; 04 printf("\n Enter any Number:"); 05 scanf("%d", &num); 06 printf("Multiplication table of %d: \n", num); 07 while (i <= 10) { 08 printf("\n %d x %d = %d", num, i, num * i); 09 i++; 10 } 11 return 0 ; 12 } Download Code Output: Enter any Number:5 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50 Explanation: We need to multiply the given number (i.e. the number for which we want the multiplication table) with value of ‘i’ which increments from 1 to 10. Back to top

Transcript of Write a Program to Display the Multiplication Table of a Given Number

Page 1: Write a Program to Display the Multiplication Table of a Given Number

1. Write a program to display the multiplication table of a given number.

Program:  Multipl ication table of a given number

view sourceprint ? 01 #include <stdio.h>

02 int main() {

03       int num, i = 1;

04       printf("\n Enter any Number:");

05       scanf("%d", &num);

06       printf("Multiplication table of %d: \n", num);

07       while (i <= 10) {

08             printf("\n %d x %d = %d", num, i, num * i);09             i++;

10       }

11       return 0;

12 }

Download Code

Output:

Enter any Number:5

5 x 1 = 5

5 x 2 = 10

5 x 3 = 15

5 x 4 = 20

5 x 5 = 25

5 x 6 = 30

5 x 7 = 35

5 x 8 = 40

5 x 9 = 45

5 x 10 = 50

Explanation:  We need to multiply the given number (i.e. the number for which we

want the multipl ication table) with value of ‘ i ’ which increments from 1 to 10.

Back to top

2. Write C program to print the following pattern:

1

Page 2: Write a Program to Display the Multiplication Table of a Given Number

2 2

3 3 3

4 4 4 4

5 5 5 5 5

Program:

view sourceprint ? 01 #include<stdio.h>

02 int main() {

03     int i, j, k, c = 5;

04     for (i = 1; i <= 5; i++) {05             /* k is taken for spaces */

06             for (k = 1; k <= c; k++) {

07                   /* blank space */

08                   printf(" ");

09             }

10             for (j = 1; j <= i; j++) {

11                   /* %2d ensures that the number is printed in

12 two spaces for alignment and the numbers are printed in the order. */13                   printf("%2d", i);

14             }

15             printf("\n");

16             /*c is decremented by 1 */17             c--;

18       }

19       return 0;

20 }

Download Code

Output:

1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

Page 3: Write a Program to Display the Multiplication Table of a Given Number

Explanation:  Here ‘ i ’ loop is used for printing the numbers in the respective rows

and ‘k’ loop is used for providing spaces. ‘ j ’ loop prints the numbers. ‘c’ is decremented

for numbers to be displayed in alternate columns.

Back to top

3. Write C program to print the following pattern:

1

1 2 1

1 2 3 2 1

1 2 3 4 3 2 1

1 2 3 4 5 4 3 2 1

Program:

view sourceprint ? 01 #include<stdio.h>

02 int main() {

03       /* c taken for columns */

04       int i, j, c = 9, m, k;

05       for (i = 1; i <= 5; i++) {

06             /* k is used for spaces */

07             for (k = 1; k <= c; k++) {

08                   printf(" ");

09             }

10            for (j = 1; j <= i; j++) {                  printf("%2d", j);             }             for (m = j - 2; m > 0; m--) {

11                   /* %2d ensures that the number

12                    * is printed in two spaces

13                    * for alignment */

14                   printf("%2d", m);

15             }

16             printf("\n");17             /* c is decremented by 2 */

18             c = c - 2;

19       }

20       return 0;21 }

Page 4: Write a Program to Display the Multiplication Table of a Given Number

Download Code

Output:

1

1 2 1

1 2 3 2 1

1 2 3 4 3 2 1

1 2 3 4 5 4 3 2 1

Explanation:  Here ‘ i ’ loop is used for printing numbers in rows and ‘k’ loop is used

for providing spaces. ‘ j ’ loop is used for printing numbers in increasing order. ‘m’ loop is

used for printing numbers in reverse order.

Back to top

4. Write a C program to display the following format:

------

a b

------

1 5

2 4

3 3

4 2

5 1

------

Program:

view sourceprint ? 01 #include<stdio.h>

02 int main() {

03       int i = 1, j = 5;

04       printf("----------\n");

05       printf("a \t b \n");

06       printf("----------\n");07       /* logic: while loop repeats

08        * 5 times i.e. until

09        * the condition i<=5 fails */

10       while (i <= 5) {

11             /* i and j value printed */12             printf("%d \t %d\n", i, j);13             /* i and j value incremented

Page 5: Write a Program to Display the Multiplication Table of a Given Number

14              by 1 for every iteration */15             i++;16             j--;

17       }

18       printf("----------");

19       return 0;

20 }

Download Code

Output:

------

a b

------

1 5

2 4

3 3

4 2

5 1

------

Explanation:  Here, ‘ i ’ is init ial ized to least value 1 and ‘ j ’ init ial ized to highest value

5. We keep incrementing the i ’ value and decrementing the ‘ j ’ value unti l the condit ion

fails. The value is displayed at each increment and at each decrement. Back to top

5. Write a C program to display the following format:

--------

no. sum

--------

1 1

2 3

3 6

4 10

5 15

--------

Program:

view sourceprint ? 01 #include<stdio.h>

02 int main() {

03       int num = 1, sum = 0;

Page 6: Write a Program to Display the Multiplication Table of a Given Number

04       printf("-----------\n");

05       printf("num \t sum\n");

06       printf("-----------\n");07       /* while loop repeats 5 times

08        *  i.e. until the condition

09        *  num <= 5 fails */

10       while (num <= 5) {

11             sum = sum + num;

12             printf("%d \t %d\n", num, sum);13             /* num incremented by 1

14              * for every time

15              * the loop is executed */

16             num++;

17       }

18       printf("-----------");

19       return 0;

20 }

Download Code

Output:

--------

no. sum

--------

1 1

2 3

3 6

4 10

5 15

--------

Explanation:   In the above program we have taken two variables ‘num’ and ‘sum’.

‘num’ is used to check the condit ion and to display the numbers up to 5. ‘sum’ is used to

add the numbers which are displayed using variable ‘num’. The ‘sum’ value is init ial ized to

zero. sum is added to the numbers which are incremented by ‘ i ’ and displayed.

//////////////////////////////////////////////////////////////////////////////////////////////////////////

C Language Interview Questions (1 to 5)

1. What does a static variable mean?

2. What is a pointer?

Page 7: Write a Program to Display the Multiplication Table of a Given Number

3. What is a structure?

4. How to print a pattern as shown below?

1

2 3

4 5 6

7 8 9 10

5. How to swap two numbers using bitwise operators?

All | Next Questions (6-11) >

1. What does a static variable mean?

A static variable is a special variable that is stored in the data segment unlike the default

automatic variable that is stored in stack. A static variable can be init ial ised by using

keyword static before variable name.

For Example:

static int a = 5;

A static variable behaves in a different manner depending upon whether it is a global

variable or a local variable. A static global variable is same as an ordinary global variable

except that it cannot be accessed by other f i les in the same program / project even with

the use of keyword extern. A static local variable is different from local variable. It is

init ial ised only once no matter how many times that function in which it resides is called. It

may be used as a count variable.

Example:

01 #include <stdio.h>

02 //program in file f1.c

03 void count(void) {

04  static int count1 = 0;05  int count2 = 0;

06  count1++;

07  count2++;

08  printf("\nValue of count1 is %d, Value of count2 is %d", count1, count2);09 }

10  

11 /*Main function*/

12 int main(){

Page 8: Write a Program to Display the Multiplication Table of a Given Number

13  count();14  count();

15  count();

16  return 0;17 }

Download Code

Output:

Value of count1 is 1, Value of count2 is 1

Value of count1 is 2, Value of count2 is 1

Value of count1 is 3, Value of count2 is 1

Back to top

2. What is a pointer?

A pointer is a special variable in C language meant just to store address of any other variable or

function. Pointer variables unlike ordinary variables cannot be operated with all the arithmetic

operations such as ‘*’,'%’ operators.

It follows a special arithmetic called as pointer arithmetic.

A pointer is declared as:

int *ap;

int a = 5;

In the above two statements an integer a was declared and init ial ized to 5. A pointer

to an integer with name ap was declared.

Next before ap is used

ap=&a;

This operation would init ial ize the declared pointer to int. The pointer ap is now said

to point to a.

Operations on a pointer:

o Dereferencing operator ‘ * ‘:

This operator gives the value at the address pointed by the pointer . For

example after the above C statements if we give

printf("%d",*ap);

Actual value of a that is 5 would be printed. That is because ap points to a.

o Addition operator ‘ + ‘:

Page 9: Write a Program to Display the Multiplication Table of a Given Number

Pointer arithmetic is different from ordinary arithmetic.

ap=ap+1;

Above expression would not increment the value of ap by one, but would

increment it by the number of bytes of the data type it is pointing to. Here ap is

pointing to an integer variable hence ap is incremented by 2 or 4 bytes depending

upon the compiler.

A pointer is a special variable in C language meant just to store address of any other

variable or function. Pointer variables unlike ordinary variables cannot be operated with all

the arithmetic operations such as ‘*’, '%’ operators. It fol lows a special arithmetic called as

pointer arithmetic.

A pointer is declared as:

int *ap;

int a = 5;

In the above two statements an integer a was declared and init ial ized to 5. A pointer

to an integer with name ap was declared.

Next before ap is used

ap=&a;

This operation would init ial ize the declared pointer to int. The pointer ap is now said

to point to a.

Back to top

3. What is a structure?

A structure is a collection of pre-defined data types to create a user-defined data

type. Let us say we need to create records of students. Each student has three fields:

int roll_number;

char name[30];

int total_marks;

This concept would be particularly useful in grouping data types. You could declare a

structure student as:

1 struct student {

2  int roll_number;

3  char name[30];

4  int total_marks;

Page 10: Write a Program to Display the Multiplication Table of a Given Number

5 } student1, student2;

The above snippet of code would declare a structure by name student and it

init ial izes two objects student1, student2. Now these objects and their f ields could be

accessed by saying student1.

style='font-size:10.0pt;font-family:"Courier New";color:#0000C0'>roll_number  for accesing

roll number f ield of student1 object, similarly  student2.

style='font-size:10.0pt;font-family:"Courier New";color:#0000C0'>name  for accesing name

field of student2 object.

Back to top

4. How to print below pattern?

1

2 3

4 5 6

7 8 9 10

Program:

01 #include <stdio.h>

02  

03 int main() {

04  int i, j, ctr = 1;

05  for (i = 1; i < 5; i++) {

06   for (j = 1; j <= i; j++){07   printf("%2d ", ctr++);

08   }

09  printf("\n");

10  }

11  return 0;

12 }

Download Code

Explanation:

There are two loops, a loop inside another one. Outer loop iterates 5 t imes. Inner loop

iterates as many times as current value of i . So for f irst t ime outer loop is executed, inner

loop is executed once. Second time the outer loop is entered, inner loop is executed twice

and so on. And every t ime the program enters inner loop, value of variable ctr is printed

and is incremented by 1. %2d ensures that the number is printed in two spaces for proper

alignment.

Page 11: Write a Program to Display the Multiplication Table of a Given Number

Back to top

5. How to swap two numbers using bitwise operators?

Program:

01 #include <stdio.h>

02 int main() {

03  int i = 65;

04  int k = 120;05  printf("\n value of i=%d k=%d before swapping", i, k);

06  i = i ^ k;

07  k = i ^ k;08  i = i ^ k;09  printf("\n value of i=%d k=%d after swapping", i, k);

10  return 0;

11 }

Download Code

Explanation:

i = 65; binary equivalent of 65 is 0100 0001

k = 120; binary equivalent of 120 is 0111 1000

i = i^k;

i...0100 0001

k...0111 1000

---------

val of i = 0011 1001

---------

k = i^k

i...0011 1001

k...0111 1000

---------

val of k = 0100 0001 binary equivalent of this is 65

---------(that is the initial value of i)

i = i^k

i...0011 1001

k...0100 0001

---------

val of i = 0111 1000 binary equivalent of this is 120

Page 12: Write a Program to Display the Multiplication Table of a Given Number

---------(that is the initial value of k)/////////////////////////////////////////////////////////////////////////////////////////////////////////////

C Language Interview Questions (6 to 11)

6. What is recursion? Write a program using recursion (factorial)?

7. To which numbering system, can the binary number 1101100100111100 be easily converted to?

8. What are the differences between structures and unions?

9. What are the advantages of using unions?

10. What is scope & storage allocation of global and extern variables? Explain with an example.

11. What is scope & storage allocation of static, local and register variables? Explain with an

example.

< Previous Questions(1-5) | All | Next Questions(12-16) >

6. What is recursion? Write a program using recursion (factorial)?

Recursion:  A function is called ‘recursive’ i f a statement within the body of a

function calls the same function. It is also called ‘circular definit ion’. Recursion is thus a

process of defining something in terms of i tself.

Program:  To calculate the factorial value using recursion.

01 #include <stdio.h>

02 int fact(int n);

03  

04 int main() {

05  int x, i;

06  printf("Enter a value for x: \n");07  scanf("%d", &x);

08  i = fact(x);

09  printf("\nFactorial of %d is %d", x, i);

10  return 0;

11 }

12  

13 int fact(int n) {

14  /* n=0 indicates a terminating condition */

15  if (n <= 0) {

16   return (1);

17  } else {

Page 13: Write a Program to Display the Multiplication Table of a Given Number

18   /* function calling itself */

19   return (n * fact(n - 1));

20   /*n*fact(n-1) is a recursive expression */21  }

22 }

Download Code

Output:

Enter a value for x:

4

Factorial of 4 is 24

Explanation:

fact(n) = n * fact(n-1)

If n=4

fact(4) = 4 * fact(3) there is a call to fact(3)

fact(3) = 3 * fact(2)

fact(2) = 2 * fact(1)

fact(1) = 1 * fact(0)

fact(0) = 1

fact(1) = 1 * 1 = 1

fact(2) = 2 * 1 = 2

fact(3) = 3 * 2 = 6

Thus fact(4) = 4 * 6 = 24

Terminating condit ion(n <= 0 here;) is a must for a recursive program. Otherwise the

program enters into an infinite loop.

Back to top

7. To which numbering system, can the binary number 1101100100111100 be easily converted to?

1101100100111100 can be easily converted to hexadecimal numbering system.

Hexa-decimal integer constants consist of combination of digits from 0 to 9 and alphabets

‘A’ to ‘F’. The alphabets represent numbers 10 to 15 respectively. Hexa-decimal numbers

are preceeded by ’0x’.

1101,1001,0011,1100

1101 = D

1001 = 9

0011 = 3

1100 = C

Page 14: Write a Program to Display the Multiplication Table of a Given Number

1101,1001,0011,1100 = 0xD93C

Thus the given binary number 1101100100111100 in hexadecimal form is 0xD93C

Back to top

8. What are the differences between structures and unions?

Structures and Unions are used to store members of different data types.

STRUCTURE UNIONa)Declaration:struct { data type member1; data type member2; };

a)Declaration:union { data type member1; data type member2; };

b)Every structure member is allocated memory when a structure variable is defined.Example:

struct emp {

 char name[5];

 int age;

 float sal;};

 

struct emp e1;

Memory allocated for structure is

5+4+4=13 bytes(assuming sizeof int is 4, float is

4, char is 1). 5 byte for name, 4 bytes for age and

4 bytes for sal.

b)The memory equivalent to the largest item is allocated commonly for all members.Example:

union emp1 {

 char name[5];

 int age;

 float sal;};

 

union emp1 e2;

Memory allocated to a union is equal to size of

the largest member. In this case, char name[5] is the

largest-sized member. Hence memory allocated to this

union is 5 bytes.

c)All structure variables can be initialized at a timestruct st {

 int a;

 float b;

};

struct st s = { .a=4, .b=10.5 };

Structure is used when all members are to

be independently used in a program.

c)Only one union member can be initialized at a timeunion un {

 int a;

 float b;

};

 

union un un1 = { .a=10 };

Union is used when members of it are not

required to be accessed at the same time.

Page 15: Write a Program to Display the Multiplication Table of a Given Number

Back to top

9. What are the advantages of using unions?

Union is a collection of data items of different data types.

It can hold data of only one member at a t ime though it has members of different data

types.

If a union has two members of different data types, they are allocated the same

memory. The memory allocated is equal to maximum size of the members. The data is

interpreted in bytes depending on which member is being accessed.

Example:

1 union pen {2  char name;3  float point;

4 };

Here name and point are union members. Out of these two variables, ‘point’ is larger

variable which is of f loat data type and it would need 4 bytes of memory. Therefore 4

bytes space is allocated for both the variables. Both the variables have the same memory

location. They are accessed according to their type.

Union is eff icient when members of i t are not required to be accessed at the same time.

Back to top

10. What is scope & storage allocation of global and extern variables? Explain with an example

Extern variables:  belong to the External storage class and are stored in the main

memory. extern   is used when we have to refer a function or variable that is implemented

in other f i le in the same project. The scope of the extern variables is Global.

Example:

01 /***************

02 Index: f1.c

03 ****************/

04 #include <stdio.h>

05 extern int x;

06  

07 int main() {

08  printf("value of x %d", x);

09  return 0;

Page 16: Write a Program to Display the Multiplication Table of a Given Number

10 }

Download Code

1 /***************

2 Index: f2.c

3 ****************/

4 int x = 3;

Here, the program written in f i le f1.c has the main function and reference to variable

x. The fi le f2.c has the declaration of variable x. The compiler should know the datatype of

x and this is done by extern  definit ion.

Global variables:  are variables which are declared above the main( ) function.

These variables are accessible throughout the program. They can be accessed by all the

functions in the program. Their default value is zero.

Example:

01 #include <stdio.h>

02 int x = 0;

03 /* Variable x is a global variable.

04 It can be accessed throughout the program */

05 void increment(void) {

06  x = x + 1;

07  printf("\n value of x: %d", x);

08 }

09  

10 int main(){11  printf("\n value of x: %d", x);

12  increment();

13  return 0;

14 }

Download Code

Back to top

11. What is scope & storage allocation of static, local and register variables? Explain with an

example.

Page 17: Write a Program to Display the Multiplication Table of a Given Number

Register variables:  belong to the register storage class and are stored in the CPU

registers. The scope of the register variables is local to the block in which the variables

are defined. The variables which are used for more number of t imes in a program are

declared as register variables for faster access.

Example: loop counter variables.

register int y=6;

Static variables:  Memory is allocated at the beginning of the program execution and

it is reallocated only after the program terminates. The scope of the static variables is

local to the block in which the variables are defined.

Example:

01 #include <stdio.h>

02 void decrement(){

03   static int a=5;

04   a--;

05   printf("Value of a:%d\n", a);

06 }

07  

08 int main(){09  decrement();

10  return 0;

11 }

Download Code

Here ‘a’ is init ial ized only once. Every t ime this function is called, ‘a’ does not get

init ial ized. so output would be 4 3 2 etc.,

Local variables:  are variables which are declared within any function or a block.

They can be accessed only by function or block in which they are declared. Their default

value is a garbage value.

//////////////////////////////////////////////////////////////////////////////////////////////////////

12. What is Pass by Value? Write a C program showing this concept.

Pass by Value:   In this method, the value  of each of the actual arguments in the

call ing function is copied into corresponding formal arguments of the called function. In

pass by value, the changes made to formal arguments in the called function have no effect

on the values of actual arguments in the call ing function.

Example:

Page 18: Write a Program to Display the Multiplication Table of a Given Number

01 #include <stdio.h>

02  

03 void swap(int x, int y) {

04  int t;

05  t = x;06  x = y;07  y = t;

08 }

09  

10 int main() {

11  int m = 10, n = 20;

12  printf("Before executing swap m=%d n=%d\n", m, n);

13  swap(m, n);

14  printf("After executing swap m=%d n=%d\n", m, n);

15  return 0;

16 }

Download Code

Output:

Before executing swap m=10 n=20

After executing swap m=10 n=20

Explanation:

In the main function, value of variables m, n are not changed though they are passed to

function ‘swap’. Swap function has a copy of m, n and hence it can not manipulate the

actual value of arguments passed to it.

Back to top

13. What is Pass by Reference? Write a C program showing this concept.

Pass by Reference:   In this method, the addresses of actual arguments in the call ing

function are copied into formal arguments of the called function. This means that using

these addresses, we would have an access to the actual arguments and hence we would

be able to manipulate them.  C does not support Call by reference . But it can be simulated

using pointers.

Example:

01 #include <stdio.h>

02 /* function definition */

Page 19: Write a Program to Display the Multiplication Table of a Given Number

03 void swap(int *x, int *y) {

04  int t;

05  t = *x; /* assign the value at address x to t */

06  *x = *y; /* put the value at y into x */

07  *y = t; /* put the value at to y */

08 }

09  

10 int main() {

11  int m = 10, n = 20;

12  printf("Before executing swap m=%d n=%d\n", m, n);

13  swap(&m, &n);

14  printf("After executing swap m=%d n=%d\n", m, n);

15  return 0;

16 }

Download Code

Output:

Before executing swap m=10 n=20

After executing swap m=20 n=10

Explanation:

In the main function, address of variables m, n are sent as arguments to the function

‘swap’. As swap function has the access to address of the arguments, manipulation of

passed arguments inside swap function would be directly reflected in the values of m, n.

Back to top

14. What is an Enumeration?

Enumeration is a data type. We can create our own data type and define values that

the variable can take. This can help in making program more readable.  enumdefinit ion is

similar to that of a structure.

Example:  consider l ight_status as a data type. It can have two possible values – on

or off.

1 enum light_status

2 {

3   on, off

4 };

Page 20: Write a Program to Display the Multiplication Table of a Given Number

5  

6 enum light_status bulb1, bulb2;7 /* bulb1, bulb2 are the variables */

Declaration of enum has two parts:

a) First part declares the data type and specif ies the possible values, called

‘enumerators’.

b) Second part declares the variables of this data type.

We can give values to these variables:

bulb1 = on;

bulb2 = off;

Back to top

15. What is the use of typedef?

typedef  declaration helps to make source code of a C program more readable. Its

purpose is to redefine the name of an existing variable type. It provides a short and

meaningful way to call a data type. typedef is useful when the name of the data type is

long. Use of typedef can reduce length and complexity of data types.

Note:  Usually uppercase letters are used to make it clear that we are dealing with our own

data type.

Example:

1 struct employee {

2  char name[20];

3  int age;

4 };

5  

6 struct employee e;

The above declaration of the structure would be easy to use when renamed using

typedef as:

1 struct employee {

2  char name[20];

3  int age;

4 };

5  

6 typedef struct employee EMP;7 EMP e1, e2;

Back to top

Page 21: Write a Program to Display the Multiplication Table of a Given Number

16. What are register variables? What are advantages of using register variables?

Register variables are stored in the CPU registers. Its default value is a garbage

value. Scope of a register variable is local to the block in which it is defined. Lifetime is t i l l

control remains within the block in which the register variable is defined. Variable stored

in a CPU register can always be accessed faster than the one that is stored in memory.

Therefore, i f a variable is used at many places in a program, it is better to declare its

storage class as register

Example:

register int x=5;

Variables for loop counters can be declared as register. Note that register keyword may be

ignored by some compilers.

http://www.chiteswarsolutions.com/viewFreshers.jsp?tutorialId=1602

http://interviewmantra.net/2008/10/c-interview-questions-with-solutions-2.html