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

programming assigment 2

Uploaded by

menber988
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

programming assigment 2

Uploaded by

menber988
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

1 .

define strlen function and write the function body of strlen


The strlen() function determines the length of string excluding the enfunction ding null character.
The strlen() function calculate the length of a given string. The string()take a string as an
argument and return its length.
The strlen() function returns the length of the given string, excluding the null character('\0'). It is
defined in the cstring header file in C++. The strlen() in c++ shows undefined behaviour when
the string passed to it is not null terminated

This program demonstrates the use of strlen() function.

#include<iostream>

#include<cstring>

using namespace std;

int main() {

char str[]="hellow";
cout<<"Length of str = "<<strlen(str); return 0;

2, define the strcmp function and the strncmp function


strcmp compares two character strings( str1 and str2 ) using the standard EBCDIC collating
sequence. The return value has the same relationship to 0 as str1 has to str2 . If two strings are
equal up to the point at which one terminates (that is, contains a null character), the longer string
is considered greater.
The basic difference between these two are : strcmp compares both the strings till null- character
of either string comes whereas strncmp compares at most num characters of both strings. But if
num is equal to the length of either string than strncmp behaves similar to strcmp.
Problem with strcmp function is that if both of the strings passed in the argument is not
terminated by null-character, then comparison of characters continues till the system crashes. But
with strncmp function we can limit the comparison with num parameter.
When pass str1 and str2 as parameters to strcmp() function, it compares both the strings character
by character till null- character(‘\0’).

The strncmp()built in function compare at most of the first count characters of the string pointed
to by string1 to the string pointed to by string 2

3. Defines the trcpy function and the strncpy function


strcpy( ) function copies whole content of one string into another string. Whereas, strncpy( )
function copies portion of contents of one string into another string.
If destination string length is less than source string, entire/specified source string value won’t be
copied into destination string in both cases.strcpy() is a standard library function in C/C++ and is
used to copy one string to another.

// strcpy() function ic C/C++

#include <iostream>

using namespace std; #include<string.h>

int main () {

char str1[]="Hello Geeks!";

char str1[]="Hello Geeks!"; char str2[] = "GeeksforGeeks"; char str3[40];


char str4[40];
char str5[] = "GfG";

strcpy(str2, str1);
strcpy(str3, "Copy successful"); strcpy(str4, str5);
cout << "str1: " << str1 << "\nstr2: " << str2

<<"\nstr3: "<< str3 << "\nstr4: "<< str4; return 0

C++ strncpy() function The strncpy() function in C++ copies a specified bytes of characters
from source to destination.

strncpy() prototype

char* strncpy( char* dest, const char* src, size_t count );

The strncpy() function takes three arguments: dest, src and count. It copies a maximum of count
characters from the string pointed to by src to the memory location pointed to by dest. If count is
less than the length of src, first count characters are copied to dest and it is not null terminated.
The strncpy() function returns dest, the pointer to the destination memory block.

Example: How strncpy() function works

#include<iostream>

#include <cstring>

#include <iostream>
using namespace std;

int main()

char src[] = "It's Monday and it's raining"; char dest[40];

/* count less than length of src */ strncpy(dest,src,10);

cout << dest << endl;

/* count more than length of src */ strncpy(dest,src,strlen(src)+10); cout << dest << endl;

return 0; }

4 define strcat function and strncat function

The strcat() function takes two arguments: dest and src . This function appends a copy

of the character string pointed to by src to of the character string pointed to by src to the end of
string ...Concatenate strings Appends a copy of the source string to the destination string. The
terminating null character in destination is overwritten by the first character of source, and a null-
character is included at the end of the new string formed by the concatenation of both in
destination.

/* strcat example */

#include <stdio.h> #include <string.h>

int main () {

char str[80];
strcpy (str,"these ");
strcat (str,"strings ");
strcat (str,"are ");
strcat (str,"concatenated."); puts (str);
return 0; }

In C/C++, strncat() is a predefined function used for string handling. string.h is the header file
required for string functions. This function appends not more than n characters from the string
pointed to by src to the end of the string pointed to by dest plus a terminating Null-character. The
initial character of the string(src) overwrites the Null-character present at the end of a
string(dest). Thus, the length of the string(dest) becomes strlen(dest)+n. But, if the length of the
string(src) is less than n, only the content up to the terminating null- character is copied and the
length of the string(dest) becomes strlen(src) + strlen(dest).
// C,C++ program demonstrate functionality of strncat()

#include <cstring>

#include <iostream>

#include <iostream>

using namespace std;

int main() {

// Take any two strings char src[50] = "efghijkl"; char dest[50]= "abcd";

// Appends 5 character from src to dest strncat(dest, src, 5);

// Prints the string


cout <<"Source string : "<< src << endl; cout <<"Destination string : "<< dest;

return 0; }

5.write a program to store the age of six of your friend in a single array. store each of the six age
using the assignment operator .print the age on the screen.

#include <iostream>

using namespace std;

int main()

cout<<"My friends age are:\t";

int age[6]={20,23,15,18,19,24};

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

cout<<"\n"<<age[i];

}
}

6. write ac++ progeam that accpet 10 integer from the user and finally display the smallest
value and the largest value

#include <iostream>

using namespace std;

int main()

int arr[10],n,i,max,min;

cout<<"Enter the size of arry:";

cin>>n;

cout<<"Enter the element of the arry:";

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

cin>>arr[i];

max=arr[0];

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

if(max<arr[i])

max=arr[i];}

min=arr[0];

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

if(min>arr[i])

min=arr[i];}

cout<<"largest element:"<<max<<endl;
cout<<"smallest element:"<<min<<endl;

return 0;}

7.write a program that accepts ten different integer from the user and display
these number after sorting them incrasing order

#include <iostream>

using namespace std;

#define max 20

int main()

int arr[max];

int n,i,j;

int temp;

cout<<"Enter the number:";

cin>>n;

if(n<0||n>max)

cout<<"Invalid range:"<<endl;

return-1;

}//read n element

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

cout<<"Enter element["<<i+1<<"]";

cin>>arr[i];

}
cout<<"unsorted arry elements:"<<endl;

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

cout<<arr[i]<<"\t";

cout<<endl;

//sorting incrasing 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;}

cout<<"sorting(incrasing order)array element:"<<endl;

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

cout<<arr[i]<<"\t";

cout<<endl;

return 0;}

8 write a program to store six your friends age in a single array assign the
ages in a random order.print the the age from low to high on screem

#include <iostream>
using namespace std;

int main()

int age[6]={20,23,15,18,19,24};

cout<<"My friends age are:\t";

int temp;

cout<<"My friends age are"<<age[i];

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

for (int j=0;j<6;j++)

if(age[i]<age[j])

temp=age[i];

age[i]=age[j]

age[j]=temp;

cout<<"\n"<<age[i];

cout<<"\n"<<age[j]; }

10.write a c++ program that calculate the tetter grade of 20 students .the program shuld
accept the mid result and the final result from the students use the approprite validity

#include<iostream>
using namespace std;

int main()

int final_mark;

int mid_mark;

cout<<"Enter the final mark ";

cin>>final_mark;

while(final_mark > 60 || final_mark<0)

cout<<"Invalid final mark\n.:";

exit(0);

cout<<"Enter the mid mark. The mid mark

cout<<"Enter the mid mark. The mid mark must between 0 and 40\n";

cin>>mid_mark;

while(mid_mark > 40 || mid_mark<0)

cout<<"Invalid final mark. ";

exit(0);

int average = mid_mark + final_mark ;

if(average >=70 && average< 100)


{

cout<<"Grade is: A";

else if(average >=60 && average< 70)

cout<<"Grade is: B";

else if(average >=50 && average< 60)

cout<<"Grade is: C";

else if(average >=40 && average< 50)

cout<<"Grade is: D";

else if(average >=0 && average< 40)

cout<<"Grade is: Fail"; }

11. write a c++ program that has two functions to binary and decimal.the program should
display a menu prompting the user to enter his choice if the user selects to binary then the
function should accept the number in the base ten and display the equivalent binary
represention .the reverse should be done if the user select to decimal
#include<iostream>

#include<math.h>

using namespace std;

int BinToDec(int bin);

int main()

int binnum, decnum;

cout<<"Enter any Binary Number: ";

cin>>binnum;

decnum = BinToDec(binnum);

cout<<"\nEquivalent Decimal Value ="<<decnum;

cout<<endl;

return 0;

int BinToDec(int bin) {

int dec=0, i=0, rem;

while(bin!=0)

while(bin!=0) {

rem = bin%10;

dec = dec + rem*pow(2,i); i++;

bin = bin/10;

return dec;}
//12.develop a c++ program that accept a word from the user and then checks
whetherthewordispalindrome ornot.a word is palindrome if it is readble from
left to write as wellas aright to left

#include <iostream>

#include <string>

using namespace std;

int main()

{// www .j a va 2 s.com string word; // Empty string char key = 'y';

while (key =='y' || key == 'y')

cout << "\n Enter a word: ";

cin >> word;

int i = 0,j = word.length() - 1;

for(;i<=j;++i,--j)

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

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

break;

if (i > j) // All characters equal? cout<<"\nTheword"<<word<<"isa

Palindrome !" << endl;

else

cout << "\nThe word " << word << " is not a palindrome" << endl;

cout << "\nRepeat? (y/n) ";

do
cin.get(key);

while (key != 'y' && key != 'Y' && key != 'n'

&& key != 'N');

cin.sync();

return 0;

13.write a C++program that accepts a word from the user and then display
the word after the reversing it.

#include <iostream>

using namespace std;

int main()

string s;

int begin,end,i,j=0,len,temp,count=0;

cout<<"ENTER STRING: ";

getline(cin,s);

//To find the length of string len=s.length();

//To reverse whole string

for(i=0;i<(len/2);i++)

for(i=0;i<(len/2);i++) {

temp=s[i]; s[i]=s[len-1-i]; s[len-1-i]=temp;

//To reverse each word seperately for(i=0;i<len;i++)


{

if(s[i]==' ' || s[i]=='\0')

for(begin=j,end=i-1 ; begin<(i +j)/2 ;

begin++,end--)

temp=s[begin];

s[begin]=s[end];

s[end]=temp; }

j=i+1; }

} cout<<s<<" ";

return 0;

14.develop a c++ program that accept the name of person and the counts how many vowel the
person name have

#include <iostream>

using namespace std;

int main() {

string line;

int vowels, consonants, digits, spaces;

vowels = consonants = digits = spaces = 0;

cout << "Enter a line of string: ";


getline(cin, line);

for(int i = 0; i < line.length(); ++i){

if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' || line[i]=='E' ||


line[i]=='I' || line[i]=='O' ||line[i]=='U')

++vowels;

else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))

++consonants;

else if(line[i]>='0' && line[i]<='9') {

++digits; }

else if (line[i]==' ') {

++spaces; }

cout << "Vowels: " << vowels << endl; cout << "Consonants: " << consonants <<endl;

cout << "Digits: " << digits << endl; cout << "White spaces: " << spaces <<endl;

return 0; }

15.Modeify the question in 14 in such a way that is should replaced vowel character with *in the
person name.

#include <iostream>

using namespace std;

int main()
{ char c;

bool isLowercaseVowel, isUppercaseVowel;

cout << "Enter an alphabet: ";

cin >> c;

// evaluates to 1 (true) if c is a lowercase vowel

isLowercaseVowel = (c == 'a' || c == 'e' || c =='i'||c=='o'||c=='u');

// evaluates to 1 (true) if c is an uppercase vowel

isUppercaseVowel = (c == 'A' || c == 'E' || c=='I'||c=='O'||c=='U');

// show error message if c is not an alphabet

if (!isalpha(c))

printf("Error! Non-alphabetic character.");

else if (isLowercaseVowel || isUppercaseVowel)

cout<<c<<"isavowel."; else

cout << c << " is a consonant.";

return 0; }

//16.write a program in c++ which reads a three digit number and generate all the possible
permutation of numbers using the above digits.for example n=123 then the permutations are -
123,213,312,132,231,321 // C++ implementation to print all the

#include <iostream>

using namespace std;

// Function to print all the permutation // which are greater than N itself
void printPermutation(int N)

int temp =N,count=0;

// Iterate and count the // number of digits in N

while (temp > 0)

count++;

temp /= 10;

// vector to print the

// permutations of N vector<int> num(count);

// Store digits of N // in the vector num while(N>0){

num[count-- - 1] = N % 10;

N=N/10;

// Iterate over every permutation of N // which is greater than N

while (next_permutation(

num.begin(), num.end()))

// Print the current permutation of N

// Print the current permutation of N for (int i = 0; i < num.size(); i++)

cout <<num[i];
cout << "\n"; }

// Driver Code int main()

int N=123;

printPermutation(N);

return 0;}

17.write a program which read a set of lines until you enter #


#include <iostream>

#include <bits/stdc++.h>

using namespace std;

//macro definitions

#define MAX_NAME_LEN 60 // Maximum len of your name can't be more than 60 #define
MAX_ADDRESS_LEN 120 // Maximum len of your address can't be more than 120

#define MAX_ABOUT_LEN 250 // Maximum len of your profession can't be more than 250

int main ()

char
y_name[MAX_NAME_LEN],y_address[MAX_ADDRESS_LEN],y_address[MAX_ADDRESS
_LEN], about_y[MAX_ABOUT_LEN];

cout << "Enter your name: ";

cin.getline (y_name, MAX_NAME_LEN);

cout << "Enter your City: ";

cin.getline (y_address, MAX_ADDRESS_LEN);

cout << "Enter your profession (press $ to complete): ";


cin.getline (about_y, MAX_ABOUT_LEN, '$'); //$ is a delimiter

cout << "\nEntered details are:\n"<<'\n';

cout << "Name: " << y_name << endl;

cout << "Address: " << y_address << endl;

cout << "Profession is: " << about_y << endl;}

18.write a program which read two matrixes and the print matrix which is addation of these two
matrixes.
#include <iostream>

using namespace std;

#define N 4

// This function adds A[][] and B[][], and stores

// the result in C[][]

void add (int A[][N], int B[][N], int C[][N])

int i, j; for(i=0;i<N;i++)

for(j=0;j<N;j++) C[i][j] = A[i][j] + B[i][j];

// Driver code int main()

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

{2,2,2,2}, {3,3,3,3}, {4,4,4,4}};

int B[N][N]={{1,1,1,1}, {2,2,2,2},

{3,3,3,3}, {4,4,4,4}};
int C[N][N]; // To store result int i, j;

// Function Call add(A, B, C);

cout << "Result matrix is " << endl;

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

for(j=0;j<N;j++) cout << C[i][j] << " ";

cout << endl;

return 0;

19.write a program which reads two matrix and multiply them if possible
#include <iostream>

using namespace std;

int main() {

int a[10][10], b[10][10], mult[10][10], r1, c1, r2,c2,i,j,k;

cout << "Enter rows and columns for first matrix: ";

cin>>r1>>c1;

cout << "Enter rows and columns for second matrix: ";

cin>>r2>>c2;

// If column of first matrix in not equal to row of second matrix,

// ask the user to enter the size of matrix

// ask the user to enter the size of matrix again.

while (c1!=r2) {

cout << "Error! column of first matrix not equal to row of second.";

cout << "Enter rows and columns for first matrix: ";
cin>>r1>>c1;

cout << "Enter rows and columns for second matrix: ";

cin>>r2>>c2; }

// Storing elements of first matrix.

cout << endl << "Enter elements of matrix 1:" << endl;

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

cout << "Enter element a" << i + 1 << j +

1<<":";

cin >> a[i][j];

// Storing elements of second matrix.

cout << endl << "Enter elements of matrix 2:" << endl;

for(i=0;i<r2;++i) for(j=0;j<c2;++j) {

cout<<"Enterelementb"<<i+1<<j +1<<":";

cin >> b[i][j]; }

// Initializing elements of matrix mult to 0. for(i=0;i<r1;++i)

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

mult[i][j]=0;

mult[i][j]=0; }
// Multiplying matrix a and b and storing in array mult.

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

for(k=0;k<c1;++k) {

mult[i][j] += a[i][k] * b[k][j]; }

// Displaying the multiplication of two matrix.

cout << endl << "Output Matrix: " << endl; for(i=0;i<r1;++i)

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

cout << " " << mult[i][j]; if(j == c2-1)

cout << endl;}

return 0; }

You might also like