Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
My arrray looks like
int myarray[]={6,5,2,6,7,8,6};
I want my program to say
if a user enters '6'
"your number is found 3 times at 0,3,6".
And if its not found say"not found".
Here is my effort:
#include <iostream>
using namespace std;
int main() {
bool flag=false;
int x[]={9,11,6,7,6,4,6};
int count=0;
int n,i,j,c;
cout<<"What number do you want to search : ";
cin >>n;
for(int i=0;i<7;i++){
if(x[i]==n){
count++;
flag=true;
}
}
if(flag){
cout <<n<<" is found "<<count<<" times in :";
for(int i=0;i<7;i++){
if(x[i]==n) cout <<i<<',';
}
} else {
cout <<n<<" is not found"<<endl;
}
}
Here is a starting example:
#include <iostream>
using namespace std;
int main(void) {
int myarray[7] = {6,5,2,6,7,8,6};
int value;
cin >> value;
bool not_found = true;
for(int i = 0; i < 7; ++i) {
if(myarray[i] == value) {
cout << "Found value " << value << " at position " << i << "\n";
not_found = false;
}
}
if(not_found)
cout << "Not found\n";
return 0;
}
which, when the user inputs 6, will output:
Found value 6 at position 0
Found value 6 at position 3
Found value 6 at position 6
If you want to match the exact same output as the one in your question, you could store the indices (all the is in an std::vector for example), and then print them.
this is the code to search element in array .this method is linear search
int main()
{
int myarray[100]={6,5,2,6,7,8,6};
int sch,i,count;
int flag=1;
count=sizeof( myarray )/sizeof( myarray[0] );
cout<<"enter element to search";
cin>>sch;
for(i=0;i<count;i++)
{
if(myarray[i]==sch){
cout<<"element"<<sch<<"found. it is in position of"<<i+1;
int flag=0;
}
}
if(flag==1)
cout<<"not found";
return 0;
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
i appeared for a campus placement exam few days ago. then while solving it. I found it quite difficult to solve. And atlast i unable to solve it.
the question is as follows:
suppose we input a string of n length. then we have to give second input.that is number of charecters after which space needs to put.
example input:
joebiden
3
expected output
joe bid en
i code something like this.
#include <iostream>
using namespace std;
int main()
{
string str;
int space, con1 = 0, con2 = 0, con3 = 0, i = 0;
cin >> str;
cin >> space;
con1 = str.size();
for (con2 = 0; con2 < con1; con2++) {
for (con3 = 0; con3 < space; con3++) {
cout << str[con2];
if (con3 < (space - 1)) {
con2++;
}
}
cout << " ";
}
return 0;
}
You can use modulo operator to find on which index you should put space.
#include <iostream>
using namespace std;
int main() {
string str;
cin >> str;
int space;
cin >> space;
int n = str.length();
for (int i = 0; i < n; ++i) {
if (i % space == 0) cout << " ";
cout << str[i];
}
return 0;
}
This would be a working and also a shorter approach for your problem:
#include <iostream>
#include <string>
int main()
{
std::string input; std::cin >> input; // Ask the user for input
int segment_len; std::cin >> segment_len; // Ask the user for segment_len
if (segment_len > 0)
{
for (int i = segment_len; i < input.size(); i += segment_len)
{
input.insert(i++, 1, ' ');
}
}
std::cout << input;
return 0;
}
This application firstly takes in a string, then the segment length, and then adds a space after every segment_len characters.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am new in programming and trying to solve some questions and in this question, I am trying to find prime numbers up to n digits using only 1 loop statement.
One loop, and recursion:
#include <iostream>
#include <cmath>
#define NUDIGS 3 //number of digits
bool TestPrime(int n, int ndiv)
{
if ( n == ndiv )
return true;
if ( (n % ndiv) == 0 )
return false;
return TestPrime (n, ++ndiv) ;
}
int main()
{
//calculate the max number with BUDIGITS
int max = pow(10, NUDIGS) - 1;
std::cout << "testing numbers from 2 to " << max << std::endl;
int ntot = 0;
//Loop testing every number. '1' is not considered as a prime number.
for (int i=2; i <= max; i++)
{
//call a recursive test
if ( TestPrime(i, 2) )
{
std::cout << i << " is prime " << std::endl;
ntot++;
}
}
std::cout << ntot << " prime numbers found" << std::endl;
}
//this program will print prime number from 2 to N . and break loop
without using break statment
#include <iostream>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int range;
cin>>range;
int num=2;
for(int i=2;i<=num;i++){
if(num>range){
i=num+1;
}
else{
if(i==num){
cout<<num<<" ";
i=1;
num=num+1;
}
else if(num%i==0){
i=1;
num=num+1;
}
}
}
cout<<endl;
return 0;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I would like to find the opposite letter using for loop. Also, I would like to note that I am trying to find the opposite letter. For example, replacing "a" with "z", "b" with "y"...
For example, the user inputs this: "3 feg", and the output from this program will be: "uvt". Also, my constraint is 1<=n<=100. The input format is "n input_string_of_length_n", and the output format is "encrypted_string_of_length_n". As a new beginner to programming, I am lost and I do not know how to solve this. Any help will be very much appreciated.
This is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
`int` user_input_number;
string user_input_text;
cout << "Type: ";
cin >> user_input_number;
cout << "Type: ";
cin >> user_input_text;
for(char i = 'a'; i <= 'z'; i++)
{
cout << << endl;
}
return 0;
}
Here is one solution using ASCII arithmetic:
string s = "abc";
for(int i = 0; i < s.length(); i++){
s[i] = 219 - s[i];
}
cout << s; // "zyx"
The reason it works is that all ASCII characters are between 0 and 127, and this way the values loop back around
// Example program
#include <iostream>
#include <string>
#include <map>
using namespace std;
string encrypt(int n, string s) {
map<char, int> alphabetMap = { };
string alpha = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < 26; i++){
alphabetMap.insert({alpha[i],i});
}
string coded = "";
for (int i = 0; i < n; i++) {
int index = alphabetMap[s[i]];
coded += alpha[25 - index];
}
return coded;
}
int main()
{
int n = 0;
string s = "";
cout << "Enter n and string: " ;
cin >> n >> s;
cout << encrypt(n,s) << endl;
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am writing a program that generates integers and sets the range of the user's choosing.
For example:
Enter the number of integers: 4
Range: 10
4 9 2 1 are generated
Now the user chooses 4 digits at a time until they're correct.
Program will also tell user if they are partially correct.
For example:
User input: 4 9 0 7
Console << 2 of your answers are correct.
I have three files:
Driver.cpp
#include <iostream>
#include "Game.h"
using namespace std;
int main()
{
// Declare variables.
Guess guess;
int numberOfIntegers;
int rangeOfIntegers;
int count = guess.getSum();
//Prompt user input.
while(count != numberOfIntegers) {
cout << "Enter the Number of Integers (n): " << endl;
cin >> numberOfIntegers;
cout << "Number of Each Integers from 1 to (m): " << endl;
cin >> rangeOfIntegers;
cout << "Enter your guesses for the " << numberOfIntegers << " integers in the range from 1 to " << rangeOfIntegers << " that have been selected:" << endl;
guess.beginGuessingGame(rangeOfIntegers, numberOfIntegers);
}
if (count == numberOfIntegers) {
cout << "You are correct! Play again? (y/n)";
}
else {
cout << count << " of your guesses are correct." << endl;
}
};
Game.h
// identifiers
#ifndef guessing_game
#define guessing_game
class Guess
{
private :
int * generatedSequence;
int * inputGuess;
int sum;
public :
void generateSequence(int inputRangeOfIntegers, int inputNumberOfIntegers);
void beginGuessingGame(int inputRangeOfIntegers, int inputNumberOfIntegers);
int getSum() {
return sum;
}
};
#endif
and Game.cpp
#include <iostream>
#include <iomanip>
#include "Game.h"
using namespace std;
void Guess::generateSequence(int inputRangeOfIntegers, int inputNumberOfIntegers) {
/// Initialize random number generator.
srand(time(0));
/// Declare array size for the generated sequence to be based on user input.
generatedSequence = new int[inputRangeOfIntegers];
/// Input randomly generated numbers from from 0 to input range into generatedSequence.
for (int i = 0; i < inputNumberOfIntegers; i++) {
generatedSequence[i] = rand() % inputRangeOfIntegers + 1;
cout << generatedSequence[i] << " " << endl;
}
}
void Guess::beginGuessingGame(int inputRangeOfIntegers, int inputNumberOfIntegers) {
/// Call our generateSequence function.
generateSequence(inputRangeOfIntegers, inputNumberOfIntegers);
/// Declare guess size based on user input.
inputGuess = new int[inputNumberOfIntegers];
/// Begin endless loop for user to guess integers.
for (;;) {
for (int i = 0; i < inputNumberOfIntegers; i++) {
cin >> inputGuess[i];
}
/// If the user has found the random sequence, we can make sum equal to the number of integers.
sum = 0;
for (int i = 0; i < inputNumberOfIntegers; i++) {
for (int j = 0; j < inputNumberOfIntegers; j++) {
/// If the user has entered the right guess, we can tally sum to the number of integers entered.
if (generatedSequence[i] == inputGuess[j]) {
sum++;
break;
}
}
}
}
}
My issue is: I cant retrieve that sum variable in the main class to check it against the number of integers. Because if they are equal, then the program knows the user has guessed correctly. I cant use cout after calling the beginGuessingGame function either..
Any suggestions?
Thanks.
At least this part of the program
Guess guess;
int numberOfIntegers;
int rangeOfIntegers;
int count = guess.getSum();
//Prompt user input.
while(count != numberOfIntegers) { //...
does not make sense. The program has undefined behavior.
Data members of the class object guess are not initialized So the member function getSum returns an indeterminate value of the data member sum of the object. And this indeterminate value is compared with another indeterminate value of the uninitialized variable numberOfIntegers in the while loop.
In the function generateSequence it seems there is a typo in this statement
generatedSequence = new int[inputRangeOfIntegers];
There should be
generatedSequence = new int[inputNumberOfIntegers];
Within the function beginGuessingGame there is an infinite loop
for (;;) {
for (int i = 0; i < inputNumberOfIntegers; i++) {
cin >> inputGuess[i];
}
/// If the user has found the random sequence, we can make sum equal to the number of integers.
sum = 0;
for (int i = 0; i < inputNumberOfIntegers; i++) {
for (int j = 0; j < inputNumberOfIntegers; j++) {
/// If the user has entered the right guess, we can tally sum to the number of integers entered.
if (generatedSequence[i] == inputGuess[j]) {
sum++;
break;
}
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
#include <iostream>
#include <string>
using namespace std;
bool custNum(char [], int);
int main()
{
const int size = 8;
char custmor[size];
cout << "Enter a customer number in the form ";
cout << "LLLNNNN\n";
cout << "(LLL = letters and NNNN = numbers): ";
cin.getline(custmor, size);
if(custNum(custmor, size))
cout<<"That's a valid id number"<<endl;
else
cout<<"That's not a valid id number"<<endl;
return 0;
}
bool custNum(char custNum[], int size)
{
int count;
for(count = 0; count<3; count++)
{
if(!isalpha(custNum[count]))
return false;
}
for(count = 3; count <size - 1; count++) //3<7 , 4
{
if(!isdigit(custNum[count]))
return false;
}
return true;
}
so I want to loop through a character array of 3 letters and 4 numbers like ABC1234, but I didn't get the condition of the second for loop (size - 1). How does it work every time it tests the condition?
Never use count as a loop variable. A good name for a loop variable is i.
Never declare variables away from their initialization. The above should be for( int i = 0; ... in both cases.
i < size - 1 is probably wrong. What you probably want is i < size.
Anyhow, it would help if you showed how size is declared, how it is initialized, etc. It would also help if you showed the exact text you are trying to parse. It would also help if you explained exactly what you expected to happen, and exactly what happened instead. I might amend my answer when you do that.
you read only amount of characters that size variable specify,
since then , Why custNum function would not return true for anything longer than size variable ? , Because it's not checking anything more than what size variable specify.
Below is the code you need
#include <iostream>
#include <string>
using namespace std;
bool custNum(string,unsigned int);
int main()
{
const unsigned int size = 8;
//char custmor[size];
string mystring;
cout << "Enter a customer number in the form ";
cout << "LLLNNNN\n";
cout << "(LLL = letters and NNNN = numbers): ";
cin >> mystring;
cout << mystring <<endl << " " << mystring.length() << endl;
// cin.getline(custmor, size);
if(custNum(mystring , size))
cout<<"That's a valid id number"<<endl;
else
cout<<"That's not a valid id number"<<endl;
return 0;
}
bool custNum(string s, unsigned int size)
{
unsigned int count;
if (s.length() != (size + 1))
return false;
for(count = 0; count<3; count++)
{
if(!isalpha(s[count]))
return false;
}
for(count = 3; count <size - 1; count++) //3<7 , 4
{
cout << s[count] <<endl;
if(!isdigit(s[count]))
return false;
}
return true;
}