String msg = "place message here";
int cntr = 0;
for i = 0 to msg.size; increment i by 1
{
if msg.charAt(i) is equal to a white space or == ' ' then
increment cntr by 1;
}
System.out.print(cntr);
String msg = "place message here";
int cntr = 0;
for i = 0 to msg.size; increment i by 1
{
if msg.charAt(i) is equal to a white space or == ' ' then
increment cntr by 1;
}
System.out.print(cntr);
Read the comments.
#include<stdio.h>
#define max 10
typedef struct
{
char entry[max];
int top;
}stack;
int stackfull(stack *s) //SHOULD BE OF TYPE BOOL RETURN
{
if(s->top==max) // IF FULL
return 0; //SHOULD RETURN true
else
return 1; //ELSE RETURN false
}
int stackempty(stack *s) //BOOL RETURN TYPE?
{
// if(! (s->top == -1) // see the difference
if(!(s->top=-1)) // JUST DO RETURN top == -1.
return 0;
else
return 1;
}
void push(stack *stk,char data)
{
if(!(stackfull(stk)))
stk->entry[stk->top++]=data;/*try ++top */
/* maybe something like this :
if( ! stackfull( stk) )
{
stk->top++;
stk->entry[str->top] = data;
}
*/
}
char pop(stack *stk) //WHY IS THE RETURN TYPE CHAR ?
{ if(!(stackempty(stk)))
return(stk->entry[stk->top--]);
else
return NULL;
}
void show(stack *stk)
{
int temp=stk->top;
while(!(temp<0))
printf(" %c \n ",stk->entry[temp--]);
}
void createstack(stack *s)
{
s->top=-1;
}
char stacktop(stack *stk)
{
return (stk->entry[stk->top]);
}
void clearstack(stack *stk)
{
stk->top=-1;
}
int stacksize(stack *stk)
{
return ((stk->top)+1);
}
int main()
{
stack stk;
createstack(&stk);
int n,k;
char data;
for(k=0;k<4;++k) /* test */
{
printf("\n enter push or pop or show ,1,2,3");
scanf(" %d ",&n);
switch(n)
{
case 1:
printf("\n enter data ");
scanf(" %c ",&data);
push(&stk,data);
break;
case 2:
printf(" the data removed is %c",pop(&stk));
break;
case 3:
show(&stk);
printf(" the stack top is %c ",stacktop(&stk));
printf(" the stack size is %d ",stacksize(&stk));
clearstack(&stk);
show(&stk);
break;
default: printf("\n wrong case entered ");
}
}
return 0;
}
// AND THERE IS PROBABLY MORE PROBLEMS WITH IT, BUT IT GETS
YOU STARTED.
Yes, but change
if(c[i].GetName() = "Phil")
toif(c[i].GetName() == "Phil")
. That should solve your compile-error :)[edit]
And C has to be an array (or vector ) of classes for thiss to work!
Be sure use strcpy when comparing cStyle String,
if( strcmp( ArrayOfClasses[i].getName(), "phil") == 0 ) { cout <<" match\n"; }
what is array of pointer
Well a pointer is an array in some way, so you can think of it as
a array of arrays, or a 2d array.
//Both Similar
char *A[2] = { "hello", "world" };
char B[10][10] = { "hello", "world" };
They are both similar in some ways. Although you should be careful
when using either or.
How about you just ask your teacher since it will be easier and more straight forward.
char arrURI[1]; -- creates an array of size one
-- so there are two indexes 0 and 1
Actually there is only 1 index, which is 0 in char A[1];
A[0] = 'a'; //ok
A[1] = 'b'; //bug
iostream and cstdlib are called libraries. They contain many methods/functions that will help you from printing to screen to seeding random numbers to sorting arrays, and many more.
The #<...> is just the syntax for C++. In java the syntax is
import java.SomeLibrary. Each language has is own ways, some similar to others.
Hello.
I`ve been given to make a program for math.After checking it.. it confuses me.I`ve been searching for a solution about my program.I hope u`ll help me with this program.
So whats the program?
which part do you need the help with?
Mean = average = Sum of Total elements / Number of elements
Median is the middle number in a sorted set of numbers
Mode is the most occurring number.
To find the Mean you can sum up the total and divide by the vector size
To find the median you need to sort the vector. Then check if the vector size is even, if so then you could do the following :
int Indx = vec.size() / 2;
float median = ( vec[Indx] + vec[Indx+1] ) / 2;
if you vec size is odd then you can simply do this :
float median = vec[ vec.size()/2 ];
You can count up the frequency of each number if the array after you
are done.
Use vectors if you could, if not then something like this will work :
Although its not tested, its the general idea.
int base= 10;
int * Array = new int[base];
bool end = flase;
int i = 0;
while(!end)
{
cout <<" Enter a number : " ;
int append = 0;
cin >> append;
Array[i] = append;
i++;
if( i >= base - 1) //check if I is at its end index
{
base += 10;
int * tmp = new int[base];
//copy Array into tmp;
delete [] Array;
Array = new int [base];
//copy tmp into Array
//delete tmp;
}
cout << " Continue <1 = yes, 0 = No > ;
cin >> end;
}
A few( maybe 2) for loops could solve this problem.
Have a for loop, for variable " i" and "a". The equation is pretty forward,
unless you don't know what the sigma notation does.
What is the "X" variable represents? Is it the user's input ?
Easy way out, just put a condition to check if "i" is at .size() - 1;
if not then print or else not print.
"Save" the original content, someway, and compare it later on. There is no
other way.
Wow, this is funny. Hey, I have a lot of exams right now and I am
broke, can you just give me couple of thousands of dollars, so I don't have
to work? Just mail it to me.
The compiler just translate it into binary. You could either, get the input
as hex, or decimal or octal.
You can't get the input as a number and determine if its decimal or hex.
Just get it as hex, and the convert it into decimal if you want or need to.
you already have a non negative checker there :
if (num < 1 || num > 4)
just change it to :
while (num < 1 || num > 4){
cout<<"Invalid choice\n";
cin >> num;
}
And the rest after that, the else if(num == 1 || num < 0 { ... }
is not needed.
would this do ?
string words[3] = {"hello","olla","namesta"};
vector<string> vec(words,words+3);
for(int i = 0; i < vec.size(); i++)
cout<<words[i]<<endl;
[edit]
Oh, looks like someone already has gotten this answer
[/edit]
int Num = -1;
cin >> Num; //get input
while( Num < 0 ) //while input is less than 0 or negative
{
cout <<" Enter a positive number : ";
cin >> Num;
}
what is your definition of "trinagle in c " ?
there is a lot of logic errors, but this one is a compile time error :
cin << yesorno;
you mean cin >> yesorno , right.
atoi is standard. itoa isn't. Someone told me strtol is better than atoi, but I can't remember the reasons given and I don't know if atoi is in fact to be avoided. Generally I use strtol. Never had a problem with either, which doesn't mean there aren't drawbacks. But atoi is standard.
Oh, your right. I was thinking itoa for some reason. Anyways, here
is the reason to use strtol, Link. Its because of error checking.
int x1;
cin>>x1// x1=0x4e2aff or x1=12345
If you wan't to do this with int, and not a string, then it either has to
be a hex or a decimal, or octal.
int Num = 0;
cin >> hex; //Tell cin to prepare to take in hex
cin >> Num; //Get hex value
cout << "Decimal value : "<<(2*Num) << endl; //Its decimal equivelance
cout << hex << showbase; //Tell cout to prepare to print in hex
cout << "Hexidecimal value : "<< (2*Num) << endl; //show in hex form
1) Create a array, which represents a table.
2) use a for loop;
for(int i = 1; i != 5; i++)
myArrayTable[i] = 6*i; //say, myArrayTable is already declared.
Or just read an integer from the cin stream in the first place.
Then that would mean more probable problems.
If you then want to convert line into an integer, use atoi or strtol. These work on C-style strings, not C++ style strings, so convert line using c_str ();
Help with Code Tags
C++ Syntax (Toggle Plain Text)
getline (cin, line);
next = atoi (line.c_str ());
Disappointed to see you suggest a non-standard function.
In C++ you should use sstream for conversion from string to numbers.
#include<sstream>
//more stuff if needed
int main()
{
stringstream ss;
string strNum = "12345.56";
float num= 0.0f;
ss << strNum; //input the string into the stream
ss >> num; //output the result into num = 12345.56f;
// maybe error checking if needed.
return 0;
}
Look at your other post. And don't double post. Be patience.
Taking a input of hexadecimal number;
int s = 0;
cin >> hex; //set input to be taken as hexadecimal
cin >> s;
Printing hex;
int a = 15;
cout << hex; //set hex output
cout << a;
what exactly do you mean by distinct prime factor?
Another way using std::string;
#include<iostream>
#include<algorithm>
#include<string>
using std::string;
using std::cout;
int toChar(char c){
return c + '0';
}
string convertBase10_To(int changeToRadix, int base10Number, int paddingEveryUnits = 4)
{
string Str = "";
//Did not want to support radix greater than 10. You do it.
if(!changeToRadix || changeToRadix > 10)
return Str;
//Check if valid paddingNumber
paddingEveryUnits = paddingEveryUnits < 0 ? 1 : paddingEveryUnits;
while(base10Number){
Str += toChar(base10Number % changeToRadix);
base10Number /= changeToRadix;
}
while(Str.size() % paddingEveryUnits != 0) //Traditionally its multiple of 4
Str += '0';
std::reverse(Str.begin(),Str.end());
return Str;
}
int main()
{
cout << convertBase10_To(2,15);
return 0;
}
strcpy (i->info.c_str(), newNode->info.c_str()); // copy i's info into newNode
i->link = newNode;
strcpy takes in c style string.
Maybe this will help :
#include<iostream>
using namespace std;
int main()
{
for(int i=5;i>=1;i--)
{
for(int j=5-i;j>=1;j--)
{
cout<<"-";
}
for(int k=1;k<=i;k++)
{
cout<<"* ";
}
cout<<endl;
}
return 0;
}
Look at the output, and trace the loop from i = 5 till i = 1.
std::string str = "abcd123";
int i = 0;
while( str[i] && isalpha( str[i] ) ) { cout << str[i] <<" -- is alpha " <<endl; ++i; }
If this is what you mean.
BTW, where is the pointers.
And a rule of thumb, when you are using char *, instead of string,
you have a bug(In my opinion);
//str is the string passed. Key is the key that seperates the word
//does not use pointers.
void Strip(std::string str, char key)
{
string Temp = "";
for(int i = 0; i < str.size(); i++) //Run through the string
{
if(str[i] == key)
{
// copy str from 0 to i into temp
}
}
return Temp;
}
I won't even say anything. Just, Here :
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << "This is a template.\n";
cin.get();
return 0;
}
How about you explain this code. Tell me what each line does.
Then tell me what you think you need to do in order to duplicate a word.
void duplicateWords (nodeType*& first, nodeType*& last)
{
struct nodeType *i;
int wordCount = 0;
for (i = first; i->link != NULL; i = i->link)
{
char temporaryWord[3];
if (i->link->info == temporaryWord[i])
wordCount++;
}
}
Try this. And inline won't do anything helpful by the way.
ostream& operator << (ostream& os, FixedSizeMatrix& obj)
{
obj.print(os);
return os;
}
Make use of functions. Try something like this
import java.util.Random;
class Main
{
static Random rand = new Random();
static void Print(Object ob){
System.out.print(ob);
}
static void Print() {
System.out.println();
}
static char getLowerCaseCharacter(){
return (char)('a' + rand.nextInt(26));
}
static char getUpperCaseCharacter(){
return (char)('A' + rand.nextInt(26));
}
static String getRandLower(int len){
String tmp = "";
for(int i = 0; i < len; i++)
tmp += getLowerCaseCharacter();
return tmp;
}
static String getRandUpper(int len){
String tmp = "";
for(int i = 0; i < len; i++)
tmp += getUpperCaseCharacter();
return tmp;
}
public static void main(String[] Arg)
{
Print(getRandLower(rand.nextInt(10)));
Print();
Print(getRandUpper(rand.nextInt(10)));
Print();
}
}
It would help if you created a few function that returns either
lowercase, uppercase , number or a punctuations.
The in your randomLowercase(int len) function you can something like
for(int i = 0; i< len; i++ )
randomString += getRandLowerCaseCharacter(); //getRandLowerCaseCharacter returns a char from 'a' to 'z';
Similarly, you can have something like this for numbers and uppercase random string as well.
Then it would be easier to mix up your functions to get lowercase,uppercase and numbers all combined.
This is great, but how would I go about preventing duplicates when the array is randomized?
You could sort it and then check if the next element is the same and
work from there.
This was was not working for me.
It works for me :
import java.*;
class Main
{
static void Print(Object ob){
System.out.print(ob);
}
static void Print() {
System.out.println();
}
public static void main(String[] Arg)
{
final int ROW = 5;
final int COL = 5;
char[] fake2D = new char[ROW*COL];
for(int i = 0; i < ROW*COL; i++)
fake2D[i] = (char)('A' + i);
for(int i = 0; i < ROW; i++)
{
for(int j = 0; j < COL; j++)
{
if(i > 0 && i % ROW == 0)
Print();
Print(fake2D[j + i * ROW] + " ");
}
Print();
}
}
}
In this there is restriction that the array dimension can't be prime
Why is that again?
Figured it out. It appears
new Type
isn't quite the same asnew Type[1]
Yep, if you look closely, you would have seen that on my post.
Can you post your whole code if its not too big.
Normally with destructor and constructor,
you should do something like ,
Array(){
mainArray = new Type[0];
}
~Array(){
delete [] mainArray;
}
Here is a complete example.
#include <iostream>
#include <string>
using std::cout;
using std::string;
using std::endl;
template<typename Type>
class Array
{
typedef unsigned int uInt;
private:
uInt len;
Type * mainArray;
public:
Array(){
mainArray = new Type[0];
len = 0;
}
Array(uInt Sz, Type val){
mainArray = new Type[Sz];
len = Sz;
for(uInt i = 0; i < Sz; i++)
mainArray[i] = val;
}
~Array(){
//Its able to delete a null pointer, i.e if(len == 0);
delete [] mainArray;
}
bool isEmpty() {
return len == 0;
}
uInt Size(){
return len;
}
bool Print(int col)
{
if(!len)
return false;
for(uInt i = 0; i < len; i++) {
if(i && i % col == 0)
cout << endl;
cout<<mainArray[i]<<" ";
}
return true;
}
};
int main()
{
Array<int> Numbers;
Array<float> Numerics(12,10);
cout<<"Numbers size is : " << Numbers.Size() << endl;
cout<<"Numerics size is: "<< Numerics.Size() << endl;
if(Numbers.Print(4))
;
else cout<<"Nothing to print in Numbers\n";
cout<<endl;
if(Numerics.Print(4))
;
else cout<<"Nothing to print in Numerics\n";
cout<<"\n\n";
return 0;
}