Thursday, 1 April 2021

c++ file work assignment-2

*when you work in file  , please use your intelligence  

c++ file work 

Assignment 2

1. Discuss the characteristics of c++ language.

answer 1 : 


1) Simple

C++ is a simple language in the sense that it provides structured approach (to break the problem into parts), rich set of library functions, data types etc.

2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with little bit or no change. But it is not platform-independent.

3) Mid-level programming language

C++ is also used to do low level programming. It is used to develop system applications such as kernel, driver etc. It also supports the feature of high level language. That is why it is known as mid-level language.

4) Structured programming language

C++ is a structured programming language in the sense that we can break the program into parts using functions. So, it is easy to understand and modify.

5) Rich Library

C++ provides a lot of inbuilt functions that makes the development fast.

6) Memory Management

It supports the feature of dynamic memory allocation. In C++ language, we can free the allocated memory at any time by calling the free() function.

7) Speed

The compilation and execution time of C++ language is fast.

8) Pointer

C++ provides the feature of pointers. We can directly interact with the memory by using the pointers. We can use pointers for memory, structures, functions, array etc.

9) Recursion

In C++, we can call the function within the function. It provides code reusability for every function.

10) Extensible

C++ language is extensible because it can easily adopt new features.

11) Object Oriented

C++ is object oriented programming language. OOPs makes development and maintenance easier where as in Procedure-oriented programming language it is not easy to manage if code grows as project size grows.

12) Compiler based

C++ is a compiler based programming language, it means without compilation no C++ program can be executed. First we need to compile our program using compiler and then we can execute our program.



2. Explain the structure of c++ program.

answer : 

  • comments – (non executable code of program ) are portions of the code ignored by the compiler which allow the user to make simple notes in the relevant areas of the source code.

simple comment

type 1 => // This is a comment

type 2 => cout << "Hello World!"; // This is a comment

type 3 => multi line command

/* The code below will print the words Hello World!
to the screen, and it is amazing */

  •  pre-process direction - which give instructions to the compiler to preprocess the information before actual compilation starts. 
  •  global declaration - They are available through out the life time of a program,They are declared at the top of the program outside all of the functions or blocks.
  •  main function - The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program. A program usually stops executing at the end of main.
  • local declaration - Variables defined within a function or block are said to be local to those functions.
    • Anything between ‘{‘ and ‘}’ is said to inside a block.
    • Local variables do not exist outside the block in which they are declared, i.e. they can not be accessed or used outside that block.
  • user defined function - A user defined function is a programmed routine that has its parameters set by the user of the system. User defined functions often are seen as programming shortcuts as they define functions that perform specific tasks within a larger system


3. What are tokens? Write their names and use.

answer :

Token is a building block of programme 

Token is a smallest part of programme , Group of characters

That group of characters which have existence in self are called Token

Token –

·         variable - Variables are containers for storing data values . that types of number are can changeable her value during execute a programme .

·         constant - Constants refer to fixed values that the program may not alter and they are called literals. Constants can be of any of the basic data types and can be divided into Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.

·         reserve and keyword- A reserved word is a word that cannot be used as an identifier, such as the name of a variable, function, or label – it is "reserved from use". int ,char , bool , main , goto , return etc.

·         identifiers -  The C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. 

·         special symbol – special symbol that are necessary and pre-compile in compiler in c language are called special symbol. / : ; '][,./?><": }{


4. Explain the various data types used in c++ language.

answer :

datatypes in c++

Data Type

Meaning

Size (in Bytes)

int

Integer

2 or 4

float

Floating-point

4

double

Double Floating-point

8

char

Character

1

Bool

Boolean

1

1. C++ int

·         The int keyword is used to indicate integers.

·         Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to 2147483647.

·         For example,

int salary = 85000;

2. C++ float and double

·         float and double are used to store floating-point numbers (decimals and exponentials).

·         The size of float is 4 bytes and the size of double is 8 bytes. Hence, double has two times the precision of float. To learn more, visit C++ float and double.

·         For example,

float area = 64.74;
double volume = 134.64534;

 

3. C++ char

·         Keyword char is used for characters.

·         Its size is 1 byte.

·         Characters in C++ are enclosed inside single quotes ' '.

·         For example,

char test = 'h';

 

4. C++ bool

·         The bool data type has one of two possible values: true or false.

·         Booleans are used in conditional statements and loops (which we will learn in later chapters).

·         For example,

bool cond = false;

5. What is operator? List out the various operator available in c++ language. Classify operators on the bases of operand.

Answer : 

Operator : An operator in a programming language is a symbol that tells the compiler or interpreter to perform specific mathematical, relational or logical operation and produce final result.

C++ is rich in built-in operators and provide the following types of operators −

An operator in a programming language is a symbol that tells the compiler or interpreter to perform specific mathematical, relational or logical operation and produce final result.

operators on the bases of operand are :

1.Unary Operators - Require only one operand

Unary operator: are operators that act upon a single operand to produce a new value.

Types of unary operators:

1:               unary minus(-)

2:               increment(++)

3:               decrement(- -)

4:               NOT(!)

 

1: Unary minus
The minus operator changes the sign of its argument. A positive number becomes negative, and a negative number becomes positive.

 int a = 10;

 int b = -a;  // b = -10

2: increment
It is used to increment the value of the variable by 1. The increment can be done in two ways:

prefix increment
In this method, the operator preceeds the operand (e.g., ++a). The value of operand will be altered before it is used.

int a = 1;

int b = ++a;  // b = 2

postfix increment
In this method, the operator follows the operand (e.g., a++). The value operand will be altered after it is used.

int a = 1;

int b = a++;   // b = 1

int c = a;     // c = 2

 

 

3: decrement
It is used to decrement the value of the variable by 1. The decrement can be done in two ways:

prefix decrement
In this method, the operator preceeds the operand (e.g., – -a). The value of operand will be altered before it is used.

int a = 1;

int b = --a;  // b = 0

posfix decrement
In this method, the operator follows the operand (e.g., a- -). The value of operand will be altered after it is used.

int a = 1;

int b = a--;   // b = 1

int c = a;     // c = 0

4: NOT(!): 

It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.

   If x is true, then !x is false

   If x is false, then !x is true

2.Binary Operators - Require two operands

Arithmetic Operators

Assume variable A holds 10 and variable B holds 20, then −

 

Operator

Description

Example

+

Adds two operands

A + B will give 30

-

Subtracts second operand from the first

A - B will give -10

*

Multiplies both operands

A * B will give 200

/

Divides numerator by de-numerator

B / A will give 2

%

Modulus Operator and remainder of after an integer division

B % A will give 0

 

Relational Operators

Assume variable A holds 10 and variable B holds 20, then –

Operator

Description

Example

==

Checks if the values of two operands are equal or not, if yes then condition becomes true.

(A == B) is not true.

!=

Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.

(A != B) is true.

> 

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

< 

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>=

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<=

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

Logical Operators

Operator

Description

Example

&&

Called Logical AND operator. If both the operands are non-zero, then condition becomes true.

(A && B) is false.

||

Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true.

(A || B) is true.

!

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false.

!(A && B) is tr

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation

Operator

Description

Example

&

Binary AND Operator copies a bit to the result if it exists in both operands.

(A & B) will give 12 which is 0000 1100

|

Binary OR Operator copies a bit if it exists in either operand.

(A | B) will give 61 which is 0011 1101

^

Binary XOR Operator copies the bit if it is set in one operand but not both.

(A ^ B) will give 49 which is 0011 0001

~

Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.

(~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.

<< 

Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

A << 2 will give 240 which is 1111 0000

>> 

Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

A >> 2 will give 15 which is 0000 1111

Assignment Operators

Operator

Description

Example

=

Simple assignment operator, Assigns values from right side operands to left side operand.

C = A + B will assign value of A + B into C

+=

Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand.

C += A is equivalent to C = C + A

-=

Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand.

C -= A is equivalent to C = C - A

*=

Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand.

C *= A is equivalent to C = C * A

 

3.Ternary Operators - Require three operands

The ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:

Syntax

variable = (condition) ? expressionTrue : expressionFalse;

Example

int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;

6. Explain various console i/o statements used in c++ language.

Answer : There are two kinds of console input/output functions :

1.Formatted input/output functions.

2. Unformatted input/output functions.

 

1.      Formatted input/output functions.

cout :- The Standard Output Stream (cout) The cout object is said to be "connected to" the standard output device, which usually is the display screen.

cin:- The Standard Input Stream (cin) The cin object is said to be attached to the standard input device, which usually is the keyboard.

cout << "Please enter your name: ";
   cin >> name;
   cout << "Your name is: " << name << endl;

 

2.      Unformatted input/output functions.

unformatted input function

Unformatted Console Input Functions

Description

getch()


Reads a single character from the user at the console, without echoing it.

getche()


Reads a single character from the user at the console, and echoing it.

getchar()


Reads a single character from the user at the console, and echoing it, but needs an Enter key to be pressed at the end.

gets()


Reads a single string entered by the user at the console.

unformatted output functions 

Unformatted Console Input Functions

Description

put(char ch)


Writes a single character at the console.

write(char *arr, int num)


Writes a number of characters in a char array to the console.

7. What are the various control statements available in c++ language? Explain with suitable example.

Answer : 

control statements

S.NO.

Control Statement & Description

1

If statement

It takes an expression in parenthesis and a statement or block of statements. If the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.

2

If …else statement

An if statement can be followed by an optional else statement, which executes when the expression is false.

3

If…else if …else statement

The if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.

4

switch case statement

Similar to the if statements, switch...case controls the flow of programs by allowing the programmers to specify different codes that should be executed in various conditions.

The syntax of the if statement in C programming is:

if (test expression)

{

   // code

}

example

The syntax of the if - else statement is:

if (condition) {
    // block of code if condition is true
}
else {
    // block of code if condition is false
}

if … else if …else Statements Syntax

if (expression_1) {

   Block of statements;

}

 

else if(expression_2) {

   Block of statements;

}

.

.

.

 

else {

   Block of statements;

}

 

switch case Statements Syntax

include <iostream>

using namespace std;

 

int main() {

int x = 2;

    switch (x)

    {

        case 1:

            cout << "Choice is 1";

            break;

        case 2:

            cout << "Choice is 2";

            break;

        case 3:

            cout << "Choice is 3";

            break;

        default:

            cout << "Choice other than 1, 2 and 3";

            break; 

    }

return 0;

}

 

input : 1

output : choice is 1

8. What do you mean by type conversion? Explain with suitable examples.

Answer :  Ans. In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another. An example would be the conversion of an integer value into a floating point value or its textual representation as a string, and vice versa.

Implicit type casting

Implicit type casting means conversion of data types without losing its original meaning. This type of typecasting is essential when you want to change data types without changing the significance of the values stored inside the variable.

#include<stdio.h>

int main(){

                    short a=10; //initializing variable of short data type

                    int b; //declaring int variable

                    b=a; //implicit type casting

                    printf("%d\n",a);

                    printf("%d\n",b);

}

 

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;

Implicit Conversion

Explicit Conversion

Implicit Conversion is done automatically.

Explicit Conversion is done programatically.

In Implicit conversion, no data loss take place during the data conversion.

In explicit conversion, data loss may or may not be take place during data conversion. Hence there is a risk of information loss.

No possibility of throwing exception during the conversion and therefore is called type safe.

It might throw error if tried to do without type casting.

Implicit conversion do not require any special syntax.

Explicit conversion do require cast operator to perform conversion.

 Example :
Conversion of smaller number to larger number is implicit conversion.
Conversion of integer type data to float.float i=0;
int j=10;
i=j;  

 Example :
Conversion of larger number to smaller number is explicit conversion.float k=123.456
int i= (int) k  

9. What do you mean by scope of variable how it effects on its visibility and limitations?

  Answer :-  Variables defined outside a function are […] called global variables. Variables defined within a function are local variables.

“Scope” is just a technical term for the parts of your code that have access to a variable.

Global variable example

#include <iostream.h>

#include <conio.h>

 

int g;

int main(){

                    int a = 4;

                    g = a * 2;

                    cout << g << endl;

}

 

Output

8

 

 

example of local variable

#include <iostream>

using namespace std;

 

int multiply(int a, int b){

        return a * b;

}

 

int main() {

        int x = 3, y = 5;

        int z;

        z = multiply( x, y );

        cout << z << endl;

        return 0;

}

 

Output

15

how it effects on its visibility and limitations? 

Local variable is declared inside a function whereas Global variable is declared outside the function. Local variables are created when the function has started execution and is lost when the function terminates, on the other hand, Global variable is created as execution starts and is lost when the program ends.

Global varibable can acceced in whole variable but local variable can acceces in only with in a function where it declared. 

Scope refers to the visibility of variables. In other words, which parts of your program can see or use it. Normally, every variable has a global scope. Once defined, every part of your program can access a variable.

10. Compare switch statements with nested if-else statements.

Answer : 

Sr. No

Switch statement

Nested if else statement

1.

We can test multiple conditions.

We can test multiple conditions

2.

We can have only one expression.

Conditions are independent to each other.

3.

Used when there is only one condition and multiple values of the same is to be tested.

Used when there is multiple conditions are to be tested

4.

Values are based on user choice

Values are based on constraint

5.

In this first condition is checked and then it switches to that case.

In this first condition is tested then it comes to else if the condition is not true and then the other conditions are tested.

6.

It is used to test multiple values of the same variable or expression like 1, 2 3 etc.

It is used to evaluate multiple conditions based on previous condition to be true to decide whether to perform a task or not.

 

11. What are the importance of operator precedence? Write the hierarchy of operator?

Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. 

Operators Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left.

Category

Operator

Associativity

Postfix

() [] -> . ++ - -

Left to right

Unary

+ - ! ~ ++ - - (type)* & sizeof

Right to left

Multiplicative

* / %

Left to right

Additive

+ -

Left to right

Shift

<< >>

Left to right

Relational

< <= > >=

Left to right

Equality

== !=

Left to right

Bitwise AND

&

Left to right

Bitwise XOR

^

Left to right

Bitwise OR

|

Left to right

Logical AND

&&

Left to right

Logical OR

||

Left to right

Conditional

?:

Right to left

Assignment

= += -= *= /= %=>>= <<= &= ^= |=

Right to left

Comma

,

Left to right

 

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

1)                 1)Associativity is only used when there are two or more operators of same precedence.

2) All operators with the same precedence have same associativity

3) Precedence and associativity of postfix ++ and prefix ++ are different

4) Comma has the least precedence among all operators and should be used carefully

 

12. Difference between while loop and do-while  loop with example.

difference table of while – do while loop :

while

do-while

Condition is checked first then statement(s) is executed.

Statement(s) is executed atleast once, thereafter condition is checked.

It might occur statement(s) is executed zero times, If condition is false.

At least once the statement(s) is executed.

No semicolon at the end of while.
while(condition)

Semicolon at the end of while.
while(condition);

If there is a single statement, brackets are not required.

Brackets are always required.

Variable in condition is initialized before the execution of loop.

variable may be initialized before or within the loop.

while loop is entry controlled loop.

do-while loop is exit controlled loop.

while(condition)
{ statement(s); }

do { statement(s); }
while(condition);

 

13. What are break, continue and goto with suitable example.

Break

//Write a C Program Which use of break statement.

#include<stdio.h>

#include<conio.h>

void main()

{    

int num, sum=0;    

int i,n;    

printf("Note: Enter Zero for break loop!\n");    

printf("Enter Number of inputs\n");          

scanf("%d",&n);

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

{        

printf("Enter num%d: ",i);        

scanf("%d",&num);

if(num==0)

{

  break;      /*this breaks loop if num == 0 */

     printf("Loop Breaked\n");

}

sum=sum+num;    

}    

printf("Total is %d",sum);     getch();

}

Output :

Note : Enter Zero for break loop 

Enter Number of inputs

5

Enter num1 : 5

Ennter num 2: 10

Enter num3 : 0

Loop Breaked

Total is 5

continue statement example

//Write a C Program Which use of continue statment. #include<stdio.h> #include<conio.h> void main(){     int i, n=20;     clrscr();     for(i=1;i<=n;++i){         if(i % 5 == 0) {             printf("pass\n");             continue;      /*this continue the execution of loop if i % 5 == 0 */         }         printf("%d\n",i);     }     getch(); }



output

1

2

3

4

pass

6

7

8

9

pass

11

12

13

14

pass

16

17

18

19

pass

  exampal of goto statement 

//Write a C Program Which Print 1 To 10 Number Using goto statement. #include<stdio.h> #include<conio.h> void main() {     int i=1;     clrscr();     count:              //This is Label     printf("%d\n",i);     i++;     if(i<=10) {         goto count;     //This jumps to label "count:"     }     getch(); }

Output 1

2

3

4

5

6

7

8

9

10

14. What do you mean by pointer? How declare pointer and initializes? What are advantages of pointer?

pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory items. Pointers are very useful for another type of parameter passing, usually referred to as Pass By Address. Pointers are essential for dynamic memory allocation.

initialize pointer

Like variables, pointers in C programming have to be declared before they can be used in your program. Pointers can be named anything you want as long as they obey C's naming rules. A pointer declaration has the following form.

data_type * pointer_variable_name;

 

Initialize a pointer

After declaring a pointer, we initialize it like standard variables with a variable address.

Pointer Syntax

 pointer = &variable; 

 

Major advantages of pointers are:

(i)                 It allows management of structures which are allocated memory dynamically.

(ii)               It allows passing of arrays and strings to functions more efficiently.

(iii)             It makes possible to pass address of structure instead of entire structure to the functions.

15. Describe pointer with reference to variable function and array?

Pointers With Arrays

// C++ Program to display address of each element of an array 
 
#include <iostream>
using namespace std;
 
int main()
{
    float arr[3];
 
    // declare pointer variable
    float *ptr;
    
    cout << "Displaying address using arrays: " << endl;
 
    // use for loop to print addresses of all array elements
    for (int i = 0; i < 3; ++i)
    {
        cout << "&arr[" << i << "] = " << &arr[i] << endl;
    }
 
    // ptr = &arr[0]
    ptr = arr;
 
    cout<<"\nDisplaying address using pointers: "<< endl;
 
    // use for loop to print addresses of all array elements
    // using pointer notation
    for (int i = 0; i < 3; ++i)
    {
        cout << "ptr + " << i << " = "<< ptr + i << endl;
    }
 
    return 0;
}

Output

Displaying address using arrays: 
&arr[0] = 0x61fef0
&arr[1] = 0x61fef4
&arr[2] = 0x61fef8
 
Displaying address using pointers: 
ptr + 0 = 0x61fef0
ptr + 1 = 0x61fef4
ptr + 2 = 0x61fef8

 


 

 pointer with reference variable

#include<iostream>

using namespace std;

 

int main()

{

int x = 10;

 

// ref is a reference to x.

int& ref = x;

 

// Value of x is now changed to 20

ref = 20;

cout << "x = " << x << endl ;

 

// Value of x is now changed to 30

x = 30;

cout << "ref = " << ref << endl ;

 

return 0;

}

 

Output: 

 x = 20
ref = 30

 

16. What do you understand by function what are the elements of function?

Answer :- function is a group of statements that together perform a task. ... A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.


  • The general form of a C++ function

    return_type function_name( parameter list ) {
       body of the function
    }

    ·        Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

    ·        Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.

    ·        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. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

    ·        Function Body − The function body contains a collection of statements that define what the function does.

    Function Declarations

    A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.

    A function declaration has the following parts −

    return_type function_name( parameter list );

    Calling a Function

    While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.

    Calling a Function

    we have declared a function named greet(). To use the greet() function, we need to call it.

    Here's how we can call the above greet() function.

    int main() {
         
        // calling a function   
        greet(); 
     
    }

     


17. Classified function with reference to parameter passing and return.

//  arguments and no return value

#include <iostream.h>

#include <stdio.h>

void value(void);

void main()

{

    value();

}

void value(void)

{

    int year = 1, period = 5, amount = 5000, inrate = 0.12;

    float sum;

    sum = amount;

    while (year <= period) {

        sum = sum * (1 + inrate);

        year = year + 1;

    }

    printf(" The total amount is %f:", sum);

}

Output:

The total amount is 5000.000000

// with argument but no return value

#include <iostream.h>

#include <stdio.h>

  

void function(int, int[], char[]);

int main()

{

    int a = 20;

    int ar[5] = { 10, 20, 30, 40, 50 };

    char str[30] = "student1guru";

    function(a, &ar[0], &str[0]);

    return 0;

}

  

void function(int a, int* ar, char* str)

{

    int i;

    printf("value of a is %d\n\n", a);

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

        printf("value of ar[%d] is %d\n", i, ar[i]);

    }

    printf("\nvalue of str is %s\n", str);

}

Output:

value of a is 20

value of ar[0] is 10

value of ar[1] is 20

value of ar[2] is 30

value of ar[3] is 40

value of ar[4] is 50

The given string is : student1guru

code for function with no arguments but have return value

#include <math.h>

#include <iostream.h>

#include <stdio.h>

int sum();

int main()

{

    int num;

    num = sum();

    printf("\nSum of two given values = %d", num);

    return 0;

}

  int sum()

{

    int a = 50, b = 80, sum;

    sum = sqrt(a) + sqrt(b);

    return sum;

}

Output:

Sum of two given values = 16

function with arguments and with return value

#include <iostream.h>

#include <stdio.h>

#include <string.h>

int function(int, int[]);

int main()

{

    int i, a = 20;

    int arr[5] = { 10, 20, 30, 40, 50 };

    a = function(a, &arr[0]);

    printf("value of a is %d\n", a);

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

        printf("value of arr[%d] is %d\n", i, arr[i]);

    }

    return 0;

}

int function(int a, int* arr)

{

    int i;

    a = a + 20;

    arr[0] = arr[0] + 50;

    arr[1] = arr[1] + 50;

    arr[2] = arr[2] + 50;

    arr[3] = arr[3] + 50;

    arr[4] = arr[4] + 50;

    return a;

}

Output:

value of a is 40

value of arr[0] is 60

value of arr[1] is 70

value of arr[2] is 80

value of arr[3] is 90

value of arr[4] is 100

 

18. What are recursive functions? Explain with example.

recursive function is a function that calls itself during its execution. The process may repeat several times, outputting the result and the end of each iteration. ... Recursive functions allow programmers to write efficient programs using a minimal amount of code.

C++ recursion example: Factorial

#include <iostream>

using namespace std;

//Factorial function

int f(int n){

   /* This is called the base condition, it is

    * very important to specify the base condition

    * in recursion, otherwise your program will throw

    * stack overflow error.

    */

   if (n <= 1)

        return 1;

   else 

       return n*f(n-1);

}

int main(){

   int num;

   cout<<"Enter a number: ";

   cin>>num;

   cout<<"Factorial of entered number: "<<f(num);

   return 0;

}

Output:

Enter a number: 5

Factorial of entered number: 120

 

19. Difference between pass by value and pass by reference.

Call By Value

Call By Reference

While calling a function, we pass values of variables to it. Such functions are known as “Call By Values”.

While calling a function, instead of passing the values of variables, we pass address of variables(location of variables) to the function known as “Call By References.

In this method, the value of each variable in calling function is copied into corresponding dummy variables of the called function.

In this method, the address of actual variables in the calling function are copied into the dummy variables of the called function.

With this method, the changes made to the dummy variables in the called function have no effect on the values of actual variables in the calling function.

With this method, using addresses we would have an access to the actual variables and hence we would be able to manipulate them.

Thus actual values of a and b remain unchanged even after exchanging the values of x and y.

Thus actual values of a and b get changed after exchanging values of x and y.

In call by values we cannot alter the values of actual variables through function calls.

In call by reference we can alter the values of variables through function calls.

Values of variables are passes by Simple technique.

Pointer variables are necessary to define to store the address values of variables.

 

20. Write a c++ program to read a number and display reverse of it.

answer : 

#include <iostream.h>  

#include<conio.h>

void main()  

{  

    int n, reverse=0, rem;    

    cout<<"Enter a number: ";    

    cin>>n;    

      while(n!=0)    

      {    

             rem=n%10;      

             reverse=reverse*10+rem;    

             n/=10;    

      }    

     cout<<"Reversed Number: "<<reverse<<endl;     

getch();

}  

Input :  852369

output : 963258

21. Write a program to read a string and check whether it is palindrome or not.

 Check Palindrome Number

#include <iostream>

#include <string.h>

using namespace std;

int main()

{

    char str1[20], str2[20];

    int i, j, len = 0, flag = 0;

    cout << "Enter the string :";

    gets(str1);

    len = strlen(str1) - 1;

    for (i = len, j = 0; i >= 0 ; i--, j++)

        str2[j] = str1[i];

    if (strcmp(str1, str2))

        flag = 1;

    if (flag == 1)

        cout << str1 << " is not a palindrome";

    else

        cout << str1 << " is a palindrome";

    return 0;

}

output

Case 1 :

Enter the string : nun

nun is a palindrome

 

Case 2 :

Enter the string : fast                                                                                                       

fast is not a palindrome

 

22. Write a program to count even or odd number from given n number.

 

Program:-

// CPP program to count number of even

#include<iostream>

using namespace std;

void CountingEvenOdd(int arr[], int arr_size)

{

                int even_count = 0;

                int odd_count = 0

                // loop to read all the values in the array

                for (int i = 0; i < arr_size;i++)

                {

                if (arr[i] & 1 == 1)

                odd_count++;

                else

                 even_count++;

}

cout << "Number of even elements = " << even_count<< "\nNumber of odd elements = " << odd_count;

}

// Driver Code

int main()

{

                int arr[] = { 2, 3, 4, 5, 6 };

                int n = sizeof(arr) / sizeof(arr[0]);

                // Function Call

                 CountingEvenOdd(arr, n);

}

Output

Number of even elements = 3

Number of odd elements = 2

 

 

23. Write a program to read a string and find length of it with library function and without library function. 

Length of String Object

#include <iostream>
using namespace std;
 
int main() {
    string str = "C++ Programming";
 
    // you can also use str.length()
    cout << "String Length = " << str.size();
 
    return 0;
}

Output

String Length = 15

 

24. Write a program to print Fibonacci series using function.

Programs to Display Fibonacci Series

 
#include<iostream>
using namespace std;
void fib(int n) {
   int f[n];
   int i;
   f[0] = 0;
   f[1] = 1;
   for (i = 2; i < n; i++) {
      f[i] = f[i-1] + f[i-2];
   }
   for (i = 0; i < n; i++) {
      cout<<f[i]<<" ";
   }
}
int main () {
   int n = 10;
   fib(n);
   getchar();
   return 0;
}

 

Output

0 1 1 2 3 5 8 13 21 34

 

25. Write a program to find factorial of number using recursion.

#include <iostream>  

using namespace std;  

int main()  

{  

   int i,fact=1,number;    

  cout<<"Enter any Number: ";    

 cin>>number;    

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

      fact=fact*i;    

  }    

  cout<<"Factorial of " <<number<<" is: "<<fact<<endl;  

  return 0;  

}  

Output:

Enter any Number: 5  
Factorial of 5 is: 120   

 

26. Write a program to find maximum of two numbers using function overloading (read int and float data from user).

Program:

#include<iostream>
using namespace std;
 
// function prototypes
int max(int n1, int n2);
double max(double d1, double d2); 
 
int main(){
        int i1 = 100, i2 = 300;
        char c1 = 'A', c2 = 'a';
        double db1 = 34.444, db2 = 45.232;
        cout<<"Between "< n2){
               return n1;
        }else{
               return n2;
        }
}
 
double max(double d1, double d2){
        //using ternary operator
        return d1 > d2 ? d1 : d2;
}
 

 

output

Between 100 and 300 larger is :300
Between A and a larger is :a
Between 34.444 and 45.232 larger is :45.232

 

27. What is Array ?What are the advantage of it? Show how it represent in memory?

Answer : what is array : An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. 

Advantages of Arrays

  • Arrays represent multiple data items of the same type using a single name.
  • In arrays, the elements can be accessed randomly by using the index number.
  • Arrays allocate memory in contiguous memory locations for all its elements. Hence there is no chance of extra memory being allocated in case of arrays. This avoids memory overflow or shortage of memory in arrays.
array representaion in memory 

 


28. Write a program to pass array into function?

#include <iostream>
using namespace std;
 
// function declaration:
double getAverage(int arr[], int size);
 
int main () {
   // an int array with 5 elements.
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;
 
   // pass pointer to the array as an argument.
   avg = getAverage( balance, 5 ) ;
 
   // output the returned value 
   cout << "Average value is: " << avg << endl; 
    
   return 0;
}

Output :

Average value is: 214.4

 

29. Write a program of array of pointer.

1.    #include <iostream>  

2.    using namespace std;  

3.    int main()  

4.    {  

5.        int *ptr;  // integer pointer declaration  

6.        int marks[10]; // marks array declaration  

7.        std::cout << "Enter the elements of an array :" << std::endl;  

8.        for(int i=0;i<10;i++)  

9.        {  

10.         cin>>marks[i];  

11.     }  

12.     ptr=marks; // both marks and ptr pointing to the same element..  

13.     std::cout << "The value of *ptr is :" <<*ptr<< std::endl;  

14.     std::cout << "The value of *marks is :" <<*marks<<std::endl;  

15. }  

 

output

Enter the element of an array :

1

2

3

4

5

6

7

8

9

10

The value of *ptr is : 1

The value of *marks is : 1

30. What is string ? How it's procced? Write a suitable example.

a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. ... In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set called an alphabet.

#include <iostream>
 
using namespace std;
 
int main () {
 
   char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
 
   cout << "Greeting message: ";
   cout << greeting << endl;
 
   return 0;
}

 

output

Greeting message: Hello

 

31. What is dynamic Array ?Explain with suitable example.

Answer : 

dynamic array, growable array, resizable arraydynamic table, mutable array, or array list is a random access, variable-size list data structure that allows elements to be added or removed. It is supplied with standard libraries in many modern mainstream programming languages.

example of dynamic array

#include<iostream>
using namespace std;
int main() {
         int x, n;
         cout << "Enter the number of items:" << "\n";
         cin >>n;
         int *arr = new int(n);
         cout << "Enter " << n << " items" << endl;
         for (x = 0; x < n; x++) {
                 cin >> arr[x];
         }
         cout << "You entered: ";
         for (x = 0; x < n; x++) {
                 cout << arr[x] << " ";
         }
         return 0;
}

 output :

Enter the number of items:

5

Enter 5 items 

1 4 5 6 7

you enterered 

1 4 7

32. Write a program to read a matrix of 2 x 2 order and print diagonal element, sum of element and transpose of matrix.

Answer : 

transpose of matrix 

Example: Find Transpose of a Matrix

#include <iostream>
using namespace std;
 
int main() {
   int a[10][10], transpose[10][10], row, column, i, j;
 
   cout << "Enter rows and columns of matrix: ";
   cin >> row >> column;
 
   cout << "\nEnter elements of matrix: " << endl;
 
   // Storing matrix elements
   for (int i = 0; i < row; ++i) {
      for (int j = 0; j < column; ++j) {
         cout << "Enter element a" << i + 1 << j + 1 << ": ";
         cin >> a[i][j];
      }
   }
 
   // Printing the a matrix
   cout << "\nEntered Matrix: " << endl;
   for (int i = 0; i < row; ++i) {
      for (int j = 0; j < column; ++j) {
         cout << " " << a[i][j];
         if (j == column - 1)
            cout << endl << endl;
      }
   }
 
   // Computing transpose of the matrix
   for (int i = 0; i < row; ++i)
      for (int j = 0; j < column; ++j) {
         transpose[j][i] = a[i][j];
      }
 
   // Printing the transpose
   cout << "\nTranspose of Matrix: " << endl;
   for (int i = 0; i < column; ++i)
      for (int j = 0; j < row; ++j) {
         cout << " " << transpose[i][j];
         if (j == row - 1)
            cout << endl << endl;
      }
 
   return 0;
}

Output

Enter rows and columns of matrix: 2
3
 
Enter elements of matrix:
Enter element a11: 1
Enter element a12: 2
Enter element a13: 9
Enter element a21: 0
Enter element a22: 4
Enter element a23: 7
 
Entered Matrix:
1  2  9
 
0  4  7
 
 
Transpose of Matrix:
1  0
 
2  4
 
9  7

 addition of matrix 

#include <iostream>
using namespace std;
 
int main()
{
    int r, c, a[100][100], b[100][100], sum[100][100], i, j;
 
    cout << "Enter number of rows (between 1 and 100): ";
    cin >> r;
 
    cout << "Enter number of columns (between 1 and 100): ";
    cin >> c;
 
    cout << endl << "Enter elements of 1st matrix: " << endl;
 
    // Storing elements of first matrix entered by user.
    for(i = 0; i < r; ++i)
       for(j = 0; j < c; ++j)
       {
           cout << "Enter element a" << i + 1 << j + 1 << " : ";
           cin >> a[i][j];
       }
 
    // Storing elements of second matrix entered by user.
    cout << endl << "Enter elements of 2nd matrix: " << endl;
    for(i = 0; i < r; ++i)
       for(j = 0; j < c; ++j)
       {
           cout << "Enter element b" << i + 1 << j + 1 << " : ";
           cin >> b[i][j];
       }
 
    // Adding Two matrices
    for(i = 0; i < r; ++i)
        for(j = 0; j < c; ++j)
            sum[i][j] = a[i][j] + b[i][j];
 
    // Displaying the resultant sum matrix.
    cout << endl << "Sum of two matrix is: " << endl;
    for(i = 0; i < r; ++i)
        for(j = 0; j < c; ++j)
        {
            cout << sum[i][j] << "  ";
            if(j == c - 1)
                cout << endl;
        }
 
    return 0;
}

Output

Enter number of rows (between 1 and 100): 2
Enter number of columns (between 1 and 100): 2
 
Enter elements of 1st matrix:
Enter element a11: -4
Enter element a12: 5
Enter element a21: 6
Enter element a22: 8
 
Enter elements of 2nd matrix:
Enter element b11: 3
Enter element b12: -9
Enter element b21: 7
Enter element b22: 2
 
Sum of two matrix is:
-1   -4
13   10

 

33. Write a program to read 2 matrices of 2 x 2 order and print product of these matrices.

// C++ program to multiply

// two square matrices.

#include <iostream>

 

using namespace std;

 

#define N 4

 

// This function multiplies

// mat1[][] and mat2[][], and

// stores the result in res[][]

void multiply(int mat1[][N],

                                                int mat2[][N],

                                                int res[][N])

{

                int i, j, k;

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

                                for (j = 0; j < N; j++) {

                                                res[i][j] = 0;

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

                                                                res[i][j] += mat1[i][k] * mat2[k][j];

                                }

                }

}

 

// Driver Code

int main()

{

                int i, j;

                int res[N][N]; // To store result

                int mat1[N][N] = { { 1, 1, 1, 1 },

                                                                                { 2, 2, 2, 2 },

                                                                                { 3, 3, 3, 3 },

                                                                                { 4, 4, 4, 4 } };

 

                int mat2[N][N] = { { 1, 1, 1, 1 },

                                                                                { 2, 2, 2, 2 },

                                                                                { 3, 3, 3, 3 },

                                                                                { 4, 4, 4, 4 } };

 

                multiply(mat1, mat2, res);

 

                cout << "Result matrix is \n";

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

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

                                                cout << res[i][j] << " ";

                                cout << "\n";

                }

 

                return 0;

}

Examples: 

Input : mat1[][] = {{1, 2}, 
                   {3, 4}}
        mat2[][] = {{1, 1}, 
                    {1, 1}}
Output : {{3, 3}, 
          {7, 7}}
Input : mat1[][] = {{2, 4}, 
                    {3, 4}}
        mat2[][] = {{1, 2}, 
                    {1, 3}}       
Output : {{6, 16}, 
          {7, 18}}

 

34 Write a program for checking given matrix is symmetric of not.

C++ Program to Find if a Matrix is Symmetric or Skew-Symmetric.

#include<iostream>

using namespace std;

int main ()

{

    int A[10][10], i, j, m, n, x = 0, y = 0;

    cout << "Enter the number of rows and columns : ";

    cin >> m >> n;

    cout << "Enter the matrix elements : ";

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

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

            cin >> A[i][j];

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

    {

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

        {

            if (A[i][j] != A[j][i])

                x = 1;

            else if (A[i][j] == -A[j][i])

                    y = 1;

        }

    }

    if (x == 0)

        cout << "The matrix is symmetric.\n ";

    else if (y == 1)

        cout << "The matrix is skew symmetric.\n ";

    else

        cout << "It is neither symmetric nor skew-symmetric.\n ";

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

        {

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

                cout << A[i][j] << " ";

            cout << "\n ";

        }

    return 0;

}

 

output 1

Enter the number of rows and columns : 2 2
Enter the matrix elements : 10 20 20 10
The matrix is symmetric.
 10 20
 20 10

 output 2

Enter the matrix elements : 0 1 -2 -1 0 3 2 -3 0
The matrix is skew symmetric.
 0 1 -2
 -1 0 3 
 2 -3 0

 ouptput 3

Enter the number of rows and columns : 1 3
Enter the matrix elements : 1 0 1
It is neither symmetric nor skew-symmetric.
 1 0 1

 

35. Write a program to read n elements on array and print them in ascending order.

answer 

Program to sort array elements in Ascending Order in C++

#include <iostream>
using namespace std;
 
#define MAX 100
 
int main()
{
        //array declaration
        int arr[MAX];
        int n,i,j;
        int temp;
        
        //read total number of elements to read
        cout<<"Enter total number of elements to read: ";
        cin>>n;
        
        //check bound
        if(n<0 || n>MAX)
        {
               cout<<"Input valid range!!!"<<endl;
               return -1;
        }
        
        //read n elements
        for(i=0;i<n;i++)
        {
               cout<<"Enter element ["<<i+1<<"] ";
               cin>>arr[i];
        }
        
        //print input elements
        cout<<"Unsorted Array elements:"<<endl;
        for(i=0;i<n;i++)
               cout<<arr[i]<<"\t";
        cout<<endl;
        
        //sorting - ASCENDING ORDER
        for(i=0;i<n;i++)
        {              
               for(j=i+1;j<n;j++)
               {
                       if(arr[i]>arr[j])
                       {
                               temp  =arr[i];
                               arr[i]=arr[j];
                               arr[j]=temp;
                       }
               }
        }
        
        //print sorted array elements
        cout<<"Sorted (Ascending Order) Array elements:"<<endl;
        for(i=0;i<n;i++)
               cout<<arr[i]<<"\t";
        cout<<endl;    
        
        
        return 0;
        
}

Output

First run:
Enter total number of elements to read: 5
Enter element [1] 123
Enter element [2] 345
Enter element [3] 567
Enter element [4] 12
Enter element [5] 90
Unsorted Array elements:
123     345     567     12      90      
Sorted (Ascending Order) Array elements:
12      90      123     345     567     
 
Second run:
Enter total number of elements to read: 120
Input valid range!!!

 

No comments:

Post a Comment