C++ isn't changing variable value - c++

I want the code to get out of the while loop when I input a number other than 66; I made it print the value of 'plz' to see if the value was changing. It is not changing, it stays at 1 even though I typed plz=o;
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
cout << "welcome to the random number generator, please enter a number\n";
int plz=1, d;
d=1;
while (plz>0)
{
d=d+1;
int g;
cin >> g;
g = 666;
if (g==666)
int j;
else
plz=0;
cout << plz << "\n";
}
srand (d);
d = rand();
cout << d << "\n";
}

You only change plz when g is not 666; since you just assigned it to be 666, that will never happen.

Related

Generate random letter array and count occurences

Hello I am trying to generate a random array of the length that the user inputs. My array should then print and display the occurences of those letters in the array. So far this only prints up to the letter g and the occurences are incorrect. If someone could tell me what I am doing wrong it would help alot. Thank you.
#include <iostream>
#include <cstring>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(0));
int i, num;
char ch;
char chars[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int freq[26]={0};
cout << "How many letters do you want in your string? ";
cin >> num;
for (i=0; i < num; i++)
{
ch = chars[rand()%26];
chars[i]=ch;
freq[i] +=1;
cout << ch;
}
for (char lower = 'a'; lower <='z'; lower++)
{
cout << "\nLetter" << lower << "is " << freq[lower] << "times";
}
}
Problem 1
The lines
chars[i]=ch;
freq[i] +=1;
are not right. You need to use:
int index = ch - 'a';
freq[index] += 1;
Problem 2
The index in the for loop for printing the data is not correct either.
You need to use:
for (char lower = 'a'; lower <='z'; lower++)
{
int index = lower - 'a';
cout << "\nLetter" << lower << "is " << freq[index] << "times";
}
Important Note
It is worth noting that the C++ standard does not guarantee that lower case letters are contiguous. (Thanks #MartinBonner). For instance, if your system uses EBCDIC encoding your program won't work.
To make your code robust, it will be better to use a std::map.
int main()
{
srand(time(0));
int i, num;
char ch;
char chars[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
std::map<char, int> freq;
// Initialize freq.
for ( ch : chars )
{
freq[ch] = 0;
}
cout << "How many letters do you want in your string? ";
cin >> num;
for (i=0; i < num; i++)
{
ch = chars[rand()%26];
freq[ch] +=1;
}
for (auto item : freq )
{
cout << "\nLetter" << item.first << "is " << item.second << "times";
}
}
You might wanna give a look to C++11 Pseudo-random number generation here is a short way of generating the range that you want using this:
#include <algorithm>
#include <array>
#include <random>
#include <vector>
using namespace std;
int main()
{
int arraySize = 35;
mt19937 engine{random_device{}()};
uniform_int_distribution<> dist{'a', 'z'};
vector<char> vec;
generate_n(back_inserter(vec), arraySize, [&]() { return static_cast<char>(dist(engine); }));
//To count occurrences
array<int, 26> freq;
for (auto c : vec) { ++freq[c-'a']; }
return 0;
}
You should not write into chars, and freq should be extended to cover the a...z range (the ASCII codes), which it does not. Also, increase at index ch, not at i.
I do not even know that range from the top of my head, but it could be modified to track all possible bytes instead (0...255), see result on https://ideone.com/xPGls7
List of changes:
int freq[256]={0}; // instead of int freq[26]={0};
// chars[i]=ch; is removed
freq[ch] +=1; // instead of freq[i] +=1;
Then it works.
Using lambda functions to do most of the work.
#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <ostream>
#include <random>
#include <string>
#include <utility>
#include <vector>
using namespace std::string_literals;
int main()
{
std::mt19937::result_type seed = std::random_device{}();
auto engine = std::mt19937(seed);
auto dist = std::uniform_int_distribution<>('a', 'z');
auto random_letter = [&engine, &dist]() { return static_cast<char>(dist(engine)); };
std::cout << "How many letters do you want to generate? "s;
int n;
if (!(std::cin >> n)) { return EXIT_FAILURE; }
auto letters = std::vector<char>();
std::generate_n(std::back_inserter(letters), n, random_letter);
auto zero = std::map<char, int>();
auto const frequencies = std::accumulate(std::cbegin(letters), std::cend(letters), zero,
[](auto& acc, auto c)
{
++acc[c];
return acc;
});
for (auto const [c, freq] : frequencies)
{
std::cout << "The letter '"s << c << "' appeared "s << freq << " times." << std::endl;
}
return 0;
}

My code will only run the main function, other functions just wont compile in C++

i am a beginner in programming in C++. In my class we were recently showed to use functions and parameters. We were left an assignment where we are supposed to work with functions, except the only problem is i can't seem to get a start. I have wrote two functions so far. My main function, which asks for input from the user. Also another function which uses this input to create a new integer i will later need. I'm sure there are several mistakes in my code, but right now i really only need to know why only my main function will execute. I have been looking for hours, and switching stuff around, just to get another function other than the main to run, but my it will only run the main function and then the program will end. After inputting data from the user, the program will end. I haven't been able to get any other function to run other than the main, since i started this assignment. I am using visual studio 2017. Sorry for the trouble.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int digits(int zip);
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
cout << "test: " << d5 << endl;
return d5;
}
You need to call the function digits
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int digits(int zip);
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
int data = digits(zip);
cout<<"test: "<<data<<endl;
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
// cout << "test: " << d5 << endl;
return d5;
}
C++ looks for the main function and executes whatever is in it. In your case, it creates a new variable 'zip', asks the user for input, then inserts that value into the zip variable. Then it returns 0 and stops running.
You must call the function digits() inside int main(). Like so:
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
digits(zip);
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
cout << "test: " << d5 << endl;
return d5;
}
Additionally, be aware that after executing the digits() function this program will simply return 0, not manipulating the 'd5' variable (returned by int digits()) in any way.
Also, it is not a good idea to cout anything inside additional functions. This makes it difficult to reuse the function. To keep the function as versatile as possible, make sure it only performs one task. In your case it should look something like this:
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
cout << "test: " << digits(zip) << endl;
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
return d5;
}
You need to call the function digits before hand otherwise the program will skip over the function entirely so the above code should actually look something like this:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int digits(int zip);
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
cout << "test: " << d5 << endl;
return d5;
}
Also on a side note in d5 = zip % 10; if your looking for it to be more accurate just define d5 as a double or a float.

Segmentation Fault on Recursion

I want to count the number of recursivily call that has a number in the Collatz Sequence. But for such a bigger number for example 4565458458
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int f(int value){
if(value==1) return 1;
else if(value%2 == 0) return value/2;
else return 3*value+1;
}
int g(int value){
if(value == 0) return 0;
if (f(value)==1) return 1;
return 1 + g(f(value));
}
int main(int argc, char *argv[]){
int nSteps=0;
istringstream iss(argv[1]);
int;
if(!(iss >> num).fail()){
if(num < 0) cout << "0" << endl;
else{
nSteps = g(num);
cout << "Result: " << nSteps << endl;
}
}
else{
cout << "Incorrect line paramaters: ./g n" << endl;
}
return 0;
}
Your program will use a lot of stack-memory for large inputs.
In addition f should have the same input and output type (originally it had "unsigned long long" as input and int as output), or the result will be wrong.
I would advise you to first rewrite g without recursion, and if that works try to investigate how to get g to be efficient with tail-recursion (the current variant does probably not support it).
Using a debugger as others suggested is also good, especially if it crashes before calling 'g'.
Finally 'num<0' does not make sense for an unsigned 'num'.

Reference to ' ' is ambiguous

I am sorry but i don't know why this algorithm is not working.
The error at compiling is : "Reference to 'function' is ambiguous " and is on y = function() line, where I am calling the function
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define PI 3.141
float function(int g, int m, int s, float z)
{
using namespace std;
z = (g + m/60.0 + s/3600.0)*PI/180.0;
return z;
}
int main()
{
using namespace std;
float y;
int g,m,s;
cout << "g = ";
cin >> g;
cout <<"m = ";
cin >> m;
cout<<"s= ";
cin >>s;
y = function();
cout << "y= " << y << endl;
//cout<< (g + m/60.0 + s/3600.0)*PI/180.0 << endl;
return 0;
}
Vers2 - updated:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define PI 3.141
float function(int g, int m, int s)
{
//using namespace std;
float z = (g + m/60.0 + s/3600.0)*PI/180.0;
//std::cout << z <<std::endl;
return z;
}
int main()
{
// using namespace std;
float y;
int g,m,s;
std::cout << "g = ";
std::cin >> g;
std::cout <<"m = ";
std::cin >> m;
std::cout<<"s= ";
std::cin >>s;
function();
// std::cout << "y= " << y << std::endl;
//cout<< (g + m/60.0 + s/3600.0)*PI/180.0 << endl;
return 0;
}
There is a member function in std and you inserted it into your namespace. Avoid using using namespace std;; you can import what you need this way:
using std::cout;
using std::cin;
I am getting a similar type of error while I used "prev" as a global variable of Node* type. Just renaming it with "prevv" solved issue in my case.
It is mostly due to the name of a "variable or function" is present in some library you used.
I can't reproduce your error message (for any of your versions with 3 different compilers), but the basic problem with your code is that you apparently assume the g,m,s-variables in your main functions are automatically used as parameters when you call function() just because they happen to have the same name.
This is NOT the case!
The variables inside your main and in the parameter list of function() are completely independent entities. The proper way to call the function and passing the right values is this:
y=function(g,m,s);
This basically copies the values stored inside the main g,m,s variables into the g,m,s parameters, which are accessed inside the function and after the function has completed, it then copies the value stored inside the variable you "return" from the function (here z) into the variable y.
This should work whether you are using using namespace std; or not, as your function has a completely different signature, But I'd still highly recommend to choose another name for your function.
I hope this doesn't sound like an insult, but I highly recommend that you read a introductory book about c++ programming, as it seems you are missing out on basic concepts of the language.

C++ function overloading cannot identify char

When I input two integers, the output is correctly their difference. However when I enter a string and a char, instead of returning how many times the char appears in the string, it returns -1, which is the out put for error. Could anyone please help me? It's just my second day learing c++...
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void mycount(int a, int b)
{
std::cout<< a - b <<std::endl;
}
void mycount(char str[], char s[])
{
int len,i;
int sum=0;
len = strlen(str);
for (i=0;i<len;i++){
if (strncmp(&str[i],&s[0],1) == 0){
sum = sum + 1;
};
};
printf("results: %d times\n",sum);
}
int main()
{
int a,b;
char c[200],d;
if(std::cin>> a >> b){
mycount(a,b);
}
if(std::cin>> c[200] >> d){
mycount(a,b);
}
else{
std::cout<< "-1" <<std::endl;
}
std::cin.clear();
std::cin.sync();
}
Hint - what will this program print?
#include <iostream>
using namespace std;
int main()
{
char c[200],d;
cout << sizeof(c) << endl;
cout << sizeof(d) << endl;
return 0;
}
Answer:
200
1
That declaration does not do what you think it does - c is an array of 200 chars, d is a single char. It's a feature of the C declaration syntax, same as:
int *c, d;
c is a pointer to int, d is an int.
Since you are doing C++, why not make your life easier and use std::string instead?
A few changes should fix your problems. First when inputting an array with cin use getline and call ignore right before hand. I find it easier to pass s as a char instead of an array of size one make sure your call your second my count with c and d instead of a and b.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void mycount(int a, int b)
{
std::cout<< a - b <<std::endl;
}
void mycount(char str[], char s)
{
int len,i;
int sum=0;
len = strlen(str);
for (i=0;i<len;i++){
if (strncmp(&str[i],&s,1) == 0){
sum = sum + 1;
};
};
printf("results: %d times\n",sum);
}
int main()
{
int a,b;
char c[200],d;
if(std::cin>> a >> b){
mycount(a,b);
}
std::cin.ignore();
if(std::cin.getline (c,200) && std::cin >> d){
mycount(c,d);
}
else{
std::cout<< "-1" <<std::endl;
}
std::cin.clear();
std::cin.sync();
}
These changes should fix it.