Sunday, August 2, 2009

I need to create a C++ program which will analyze a sentence written in the code and print the longest words?

Say the sentence was "There's the spoons pass me one" I would like the program to print both "There's" as its the longest word with an " ' " and "spoons" because its the longest word.





I am trying to work it out using strings and arrays.





Im using Visuall Studio 2005 c++.





Also how can I get the program to tell me how many of 1 letter is in the whole sentence.

I need to create a C++ program which will analyze a sentence written in the code and print the longest words?
Here is a gift.





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


#include %26lt;vector%26gt;





using namespace std;





int findLetter(const string%26amp; str, const char letter)


{


size_t pos = 0;


int count = 0;





do


{


pos = str.find(letter, pos);


if (pos != string::npos)


{


count++;


pos++;


}





} while (pos != string::npos);





return(count);


}








void parseWords(vector%26lt;string%26gt; %26amp;a, string str)


{


size_t pos = 0;


size_t start = 0;


string tempStr;





do


{


pos = str.find(' ', start);


if (pos != string::npos)


{


tempStr = str.substr(start, pos - start);


pos++;


start = pos;


}


else


{


if (start != string::npos)


{


tempStr = str.substr(start);


}


}





a.push_back(tempStr);





} while (pos != string::npos);





}














int main(int argc, char *argv[])


{


const string sentence("There's the spoons pass me one");





char letter;





//find requested letter





cout %26lt;%26lt; "Enter letter to find in sentence: ";


cin %26gt;%26gt; letter;


cout %26lt;%26lt; letter %26lt;%26lt; " occurs: " %26lt;%26lt; findLetter(sentence, letter) %26lt;%26lt; " times." %26lt;%26lt; endl;





//load array of words in sentence





vector%26lt;string%26gt; array;





parseWords(array, sentence);





//find longest word





int largestSize = 0;


string largestStr;





vector%26lt;string%26gt;::iterator pos = array.begin();


vector%26lt;string%26gt;::iterator end = array.end();





for (; pos != end; ++pos)


{


if (pos-%26gt;length() %26gt; largestSize)


{


largestSize = pos-%26gt;length();


largestStr = *pos;


}


}





cout %26lt;%26lt; "Largest word was \"" %26lt;%26lt; largestStr %26lt;%26lt; "\" with a size of " %26lt;%26lt; largestSize %26lt;%26lt; endl;


}
Reply:the one letter of each is easy store the string in an array and go through it letter by letter until you reach the end, have a switch set up example





get the letter put in x





switch (x)





case (a) :





case (b) :








for the first part count letters until white space, store location thats longest somewhere, index through whole sentense if longer replace if not stay the same at the end have a pointer pointing to the beginning of the longest word and print it out or whatever








should get you started think correctly


Turbo c "ARRAY" statement?

Write a program using one dimensional array that calculates the sum and average of the five input values from the keyboard and prints the calculated sum and average.





This is what i've done the problem is i dont know how to combo it with a loop that will say "would you like you try for another one answer yes or no" can you help me..thanks in advance.





#include %26lt;stdio.h%26gt;


main()


{


int i, sum, n[5];


float ave;


sum = 0;


clrscr();


prinf(“\n Enter five numbers: \n”);


for (i=0; i%26lt;5; i++)


{


scanf (“%d”, %26amp;n[i]);


}


ave=sum/5;


printf(“\n The sum is : %d “, sum);


printf(“\n The ave is : %0.2f”, ave);


getch();


}

Turbo c "ARRAY" statement?
Not sure what you want to achieve, exactly, but I'm assuming that you need to invite the user to go for another set of 5 numbers?





This being the case, you need to make a while loop that contains the code that is to be repeated : i.e. everything except the initialization of the program itself.





The while loop should test for the user entering 'yes' or 'no' using scanf to retrieve their answer, and probably converting from lower to upper case, just in case they're feeling sneaky, and type in 'YeS', for example. Either that, or use stricmp from the string.h library (it is the case insensitive version of strcmp).





I've put a few pointers to some relevant articles for you, in the sources below.





Have fun, and good luck!

plants

How can i create dynamic array in C and VB?

so that the memory create itself its space for an array when required

How can i create dynamic array in C and VB?
Since you mentioned VB, I'll guess that you mean Visual C++?





If so, there's a CArray template object that you can use, and there are already sub-classes of it, such as CByteArray, CDWordArray, CObArray, CPtrArray, CStringArray, CUIntArray, and CWordArray,





You can do something like this:


CStringArray myStrArray;


myStrArray.Add("A new string");


myStrArray.Add("Another new string");


printf("%d", myStrArray.GetSize()); // This would print 2 at this point


printf("%s", (char *)myStrArray[1]); // This would print "Another new String" without the quotes


myStrArray.RemoveAll(); // This empties the array
Reply:You cannot create a dynamic array in C but you can write code to enlarge and shrink one as needed or you could just use linked lists which would be quicker.





for instatance





int *myarray = NULL;


mycount = 0;





increase (%26amp;myarray, %26amp;mycount);


myarray[0] = 5;


decrease(myarray, %26amp;mycount);





The routines are


void increase(int **myarray, int *mycount) {


int n;


*mycount++;


int *newarray = malloc(*mycount, sizeof(int));


for (n=0; n%26lt;(*mycount - 1); n++) {


newarray[n] = *myarray[n];


}


free(*myarray);


*myarray = newarray;


}





(something like that anyway)


Not tested!


The other routine would be something similar.
Reply:IN VB you declare a dynamic array by naming a variable with parenthesis. A static array, one with a fixed number of elements is declared by placing an integer within the parenthesis.





dim myStaticArray(50) as string


dim myDynamicArray() as string





to use the dynamic array you my dimension it prior to using it in code, The computer still needs to allocate memory for it, with a dynamic array you are performing the allocation at run time vs design time.





Use the REDIM command to allocate memory and size the number of elements





REDIM myDynamicArray(25)





Depending on how you use the array in your program you may need to resize the array. You may simply REDIM the array again to what ever size you need. However in doing so the contents of the array will be erased.





If you need to resize the array and Key any data already assigned to it you use the PRESERVE modifier.





REDIM PRESERVE myDynamicArray(50)


How to delste an empty slot in an array in c++?

Arrays are predominantly statically assigned. For dynamically assigning slots, use a pointer instead, and when done with use the %26lt;b%26gt;delete%26lt;/b%26gt; option afterwards.


Simple C++ Array Question?

I have a question regarding having a user inputting data into an integer array.





I need a user to enter a series of 0's and 1's (don't worry, i have the defensive programming set up to make sure they don't enter anything else). I need that data to be placed into an array called 'data'.





The way it's set up now, I ask for 10 pieces of data, and the user enters them one at a time and hits enter in between every one. It then stops asking and going through the loop because counter %26gt; 10. I don't want 10 to be hardcoded, and I don't want thte user to have to enter them one at a time.





CIN%26gt;%26gt; takes one character at a time, what code would take them all? Also, I need every bit to be put in a different index. For instance, if the entry is 101, I don't want 101 in position 0, i want 1 in position 0, 0 in position 1, and then 1 at position 2.





Can anyone help?

Simple C++ Array Question?
you could try to read as many words as the user gives you, and whenever the user prints enter, and cin%26gt;%26gt; returns, you can parse the string.





int received=0;


// repeat till we have 10 items


while (received%26lt;10) {


cin %26gt;%26gt; word;


// now parse the word manually - this is a bit of work


// then add the number of valid "pieces of data" to "received"


// i.e. if the user enters "1": fill your array with a "1" and add 1 to received (received+=1);


// if the user enters "101": fill your array with "1", "0", "1", and add 3 to received (received+=3);


}
Reply:// HELP.cpp : Defines the entry point for the console application.





#include %26lt;conio.h%26gt;


#include %26lt;iostream%26gt;





using namespace std;





#define ESC 27


#define ENTER 13





//------------------------------------


//


// binary_gets()


//


// get user input into buffer...


//------------------------------------


int binary_gets(char *buff, int max)


{


char ch=0;


int iii=0, done = 0;





while(iii %26lt; max %26amp;%26amp; !done )


{


ch=getch();





switch(ch)


{





//test for 'One' or 'Zero' ...the only characters permitted


case '0':


case '1':


putch(ch); //display OK





//Note, this code can be modified to store


//as integers by subtracting '0' from 'ch' right


//here ( pls see usage in main() )


buff[iii++] = ch; //store it


break;





case ESC: // user wants out


iii=0; //cancel all





//fall thru....





case ENTER: //user signaled done, keep all


done = 1;


break;





default:


break;


}





}





buff[iii] = '\0'; //cap it or kill it, depending iii


return (iii %26gt; 0); //return True if any data captured





}





int main()


{


char buff[20];


int iii, pow, num;





cout %26lt;%26lt; "Enter your binary number: ";


if(binary_gets(buff, 10))


{


cout %26lt;%26lt; endl %26lt;%26lt; "Seems you entered: " %26lt;%26lt; buff %26lt;%26lt; endl;





///Now, convert and display in decimal


iii=strlen(buff);


pow = 1;


num = 0;


while(iii--)


{





// Next: we say [ buff[iii] - '0' ] because this is


// character array in a numeric application...


num += (pow * (buff[iii] - '0' ));


pow *= 2;


}


cout %26lt;%26lt; "In decimal, that's " %26lt;%26lt; num %26lt;%26lt; endl;


}


else


cout %26lt;%26lt; endl %26lt;%26lt; "User quit early" %26lt;%26lt; endl;





return 0;


}
Reply:hmm... a tricky workaround, but try this:


create a string variable, then use [scanf("%s",%26lt;varname%26gt;)] or similar to get the user input. Then cast the string into ints, implementing a do-while loop to ensure that the "string" was actually 1's and 0's. before casting the string to int, get the separate "characters" from within the string, then cast the individual characters to ints to be used in the array. This seems like an excessive workaround(and be prepared for compiler errors), but try it, then fine tune it if need be.





EDIT: call the size method of String itself to set whatever size limits you want, placing them into the do-while "verification" loop, or you could set the size limit on the post-cast chars or ints.


Please help with C++ Array?

For some reason what ever value (1-12) I enter for the month I have a return of “Jan” It builds fine … with no errors…but my array subscripts are not matching





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


using std::cout;


using std::cin;


using std::endl;


using std::string;











int main()





{


int days[12] = {31, 28, 31, 30, 31, 30 , 31, 31 , 30, 31, 30, 31};


string month [12]= {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};


string searchForMonth = "";





cout %26lt;%26lt; "Enter Month ID: ";


getline(cin, searchForMonth);





while (searchForMonth != "12")


{


int y = 0; //keeps track of array subscripts


while (y %26lt; 12 %26amp;%26amp; month[y] %26lt; searchForMonth)


y = y + 1;





if (y %26lt;= 12)





cout %26lt;%26lt; "Month: " %26lt;%26lt; month[y] %26lt;%26lt; endl;


cout %26lt;%26lt; "Enter Month ID: ";


getline (cin, searchForMonth);





}











return 0;


} //end of main function

Please help with C++ Array?
The reason you're getting "Jan" all the time is due to the second while loop condition. The string month[0] ("Jan") will always be greater than searchForMonth (assuming you're entering a number for searchForMonth).





So the second loop condition will always be false, and y will stay at 0.
Reply:I see a couple of problems.





string searchForMonth = "";





cout %26lt;%26lt; "Enter Month ID: ";


They are entering a STRING HERE


getline(cin, searchForMonth);





I understand "12" but why not use a compare method?


Its a string, not the ascii value of 12.


what happens if they enter a -1??


I think this is your reason right here.





while (searchForMonth != "12")


{


int y = 0; //keeps track of array subscripts








while (y %26lt; 12 %26amp;%26amp; month[y] %26lt; searchForMonth)


y = y + 1;





The IF below is not part of WHile


if (y %26lt;= 12)


cout %26lt;%26lt; "Month: " %26lt;%26lt; month[y] %26lt;%26lt; endl;





The statement below are not part of above IF


cout %26lt;%26lt; "Enter Month ID: ";


getline (cin, searchForMonth);





}//beginning while ends





I didnt get a chance to run it, so I just did this by sight
Reply:the man above me took the words right out of my mouth !
Reply:It could be these lines:





if (y %26lt;= 12)





cout %26lt;%26lt; "Month: " %26lt;%26lt; month[y] %26lt;%26lt; endl;





In your condition, you are accepting 12 as a valid value. So what is happening is you are getting





cout %26lt;%26lt; "Month: " %26lt;%26lt; month[12] %26lt;%26lt; endl; That's an overflow problem because the array subscript should only be between 0 and 11.





***********


You could try this in your loop:





int monthSearch;





cin%26gt;%26gt;monthSearch;





int index=monthSearch-1;


cout%26lt;%26lt;month[index] %26lt;%26lt; " " %26lt;%26lt; days[index]%26lt;%26lt;endl;





output of 3 entered into program:





Mar 31

id cards

C++ programing, this is my study guide can you help me get the right answers?

1. Making a variable behave like a variable of a different data type is known as


a.typecasting


b.brute force


c.intimidation


d.variable casting


2. To redirect the input for a C++ program (theprog.exe) to come from a file rather than the keyboard you would:


a.theprog %26lt; infile.txt


b.theprog %26lt;%26lt; infile.txt


c.theprog %26gt; infile.txt


d.theprog %26gt;%26gt; infile.txt


3. if a do/while structure is used,


a) an infinite loop will not take place


b) counter controlled repetition is not possible


c) the body of the loop will execute at least once


d) an off-by-one error will not occur


4. A function prototype does not have to


a)include parameter names


b)terminate with a semicolon


c)agree with the function definition


d)match with all calls to the function


5. A function prototype does not have to


a)include parameter names


b)terminate with a semicolon


c)agree with the function definition


d)match with all calls to the function


6. For command line arguments you write your main function:


int main(int argc, char *argv[])


The argc refers to:


a.the count of the arguments passed


b.an array of pointers to strings


c.the number of people using the program


d.the size in bytes of the program

C++ programing, this is my study guide can you help me get the right answers?
1. a.


2. d.


3. c.


4. d.


5. isn't this #4?


6. a.
Reply:1. a


2. a -- I think


3. c


4.a - i think


5. same as 4 ?


6. a





Number 4 - example of prototype


void function(int number) will work if you do this as well


void function(int) I don't think poster above said it right








I know this will work.





Man whoever gave you the study guide -- really likes a answers :)





number 2 - site below answers the question. And thats what I thought before I went and looked, so I am right


Help with C++ array program?!?!?

Have a function fill an array with random numbers in the range 1-99.


Have it done with a function called Fill.


The array will contain 50 numbers.


Print the list.


Ask for the number to be searched for in the list.


Send the array and the “target” value into another function called Find.


Print out if the number was found in the list.





Hints: have randomize() at start of the program. And #include%26lt;stdlib.h%26gt;


In a loop use num[x]=random(99)+1;


You must have an #include%26lt;stdlib.h%26gt; for random.


In your Find function send in the array and target.


Have local variable, call it flag, set to –1. If the target is found, change flag to 1.


Return flag. If the return is –1, cout “Not found”, else, cout “Found”





If you are clever have it print WHERE it found target; the number location (you will need a reference parameter.)

Help with C++ array program?!?!?
Sounds like a fun homework assignment! What exactly are you having problems with? Have you tried anything yourself yet?
Reply:what is your question?
Reply:What exactly do you want to know?


How do you crack the Rail Fence Cypher? (While programming in C?)?

OK, to fill you in on what the Rail Fence Cypher does, it goes like this





Take the plain text message





ABCDEFGHIJKL





Then put it in to a table, thus,





A D G J


B E H J


C F I L





Then read the rows to get the encrypted message





A D G J B E H J C F I L





I'm programming in C, so any C solutions, hints, tips, would be brilliant





Mine uses a fixed three rows, so you could have





A B C D E F G H I J L K M N O P Q R S T U V W X Y Z





A D G J M P S V Y


B E H K N Q T W Z


C F I L O R U X





Final Encrypted message:





A D G J M P S V Y B E H K N Q T W Z C F I L O R U X





And anything in between.





The alphabet is used for example purposes.





More letters can be used.





My arrays in C are set to 3 rows by 25 columns for encrypting the message, and 75 elements for getting the plain text message.





My code is available at http://docs.google.com/Doc?id=ddzf6sz8_9...

How do you crack the Rail Fence Cypher? (While programming in C?)?
Hi


I have attach a snippet of code that may help.


It is not concise but may help with the logic.


A couple of tips:


Try not to use 'goto'.


In the 'menu' procedure have a look at using 'switch' and 'case' rather than 'if' statements


Compact the code a bit, there is a lot of empty space.


Do you need to find out what OS the user is using I would suggest that they would know that otherwise they would not be able to compile it in the first place!


Enjoy!!!!


Graham





#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;ctype.h%26gt;





char BinputMSG[75];


char Message2encode[3][25];


char DinputMSG[75];





main()


{


int C;


int R;


static int x = 0;


int NofCols, strlg;


static div_t q;


char s[1];


printf("Input a string. Up to 75 characters...");


scanf("%s",BinputMSG);


printf("Input was %s\n",BinputMSG);


strlg = strlen(BinputMSG);


q = div(strlg,3);


NofCols = q.quot; // Calculate number of columns


for(C = 0 ; C %26lt;= NofCols ; C++)


{


for ( R = 0 ; R %26lt;= 2 ; R++)


{


Message2encode[R][C] = BinputMSG[x];


x++;


}





}


x = 0;


for ( R = 0 ; R %26lt;= 2 ; R++)


{


for ( C = 0 ; C %26lt;= NofCols ; C++)


{


s[0] = Message2encode[R][C];


if (s[0] != 0) // Allow for blanks in the array


{


DinputMSG[x] = Message2encode[R][C];


x++;


}


}


}


printf("Encoded string is %s\n",DinputMSG);


}


C++ Array HELP!?

Here's what I'm trying to do...


I have an array with 50 lines and I want to grab every ten lines and throw them into a few functions.


Here are my prototypes


void BubbleSort(int [],int);


void ShowArray(int [],int);





my array:


int Unsorted[50];


int A[10];





Here's my for loop


inFile.open("input.txt");


if (inFile.fail())


cout %26lt;%26lt; "Unable to read from file...";


else


{





//ShowArray(Unsorted,AllData);


//input data from array...all of it...


for (int count = 0; count %26lt; 50; count++)


{


inFile %26gt;%26gt; Unsorted[count];





cout %26lt;%26lt; Unsorted[count] %26lt;%26lt; endl;


}


}


}


How can I create a for loop that will capture ten lines of numbers from the [50], pass them into a function that will sort them and then toss them into another function that will print out the sorted list, and then repeat the process another four times? A[10] will hold the ten lines.


Any ideas...please help


thanks...

C++ Array HELP!?
for(int i = 0; i %26lt; 5; i++)


{


int arraytemp[10];


for(int j = 0; j %26lt; 10; j++)


{


//move values into a new array


arraytemp[j] = Unsorted[i*10+j];


}


//sort the array


sort(arraytemp);


//print the array


print(arraytemp);


}





below is links to how to bubble sort (with code, c++)
Reply:use a nested for loop.








for(int i = 0; i %26lt; 4; i++)


{


for(int j = 0 + 10*i; j %26lt; 10*i + 10; j++)


//add Array[j] to A[j - 10*i]





//now sort and output the current A[].


}
Reply:Just hardcode every multiple of 10 into the for loop, like this.





for(init;test;iter)


{


if(line==10 || line==20...etc)


//add it in here


}

flowers online

C++ array help 4 class?

how do i write a program that computes and outputs the mean and the standard deviation of a set of integer values that are stored in an input file. The number of integer values, n, is stored as the first data item in the file then the actual data values follow. The program will read the data items from the file and store them in an integer array defined to hold these numbers. The program will access the elements of that array in order to compute the standard deviation. In addition, your program must find the largest and smallest values in the read data items and display them on the screen.





This is what i have so far:


#include%26lt;iostream%26gt;


#include%26lt;fstream%26gt;


#include%26lt;cmath%26gt;


#include%26lt;string%26gt;





using namespace std;





int main()


{


ifstream input;


int number;


double mean;


int count;


int total;


double standd;





input.open("inputFile-1.txt");








I am not sure where to take it from here. Can some one please show an example of how to read the data items from the file and store them in an array

C++ array help 4 class?
the following is a suggestion but the file must be sequential to work:





ifstream ClientFile ( "Clients.txt", ios::in)


if ( !ClientFile ) {


cerr%26lt;%26lt;"File Corrupted.\n";


exit(1);


}








int x;


int counter=0;


while ( ClientFile %26gt;%26gt; x )


{


counter++;//this will give you the number of values in file


}





//there is an error here but i don't know why try it on the compiler


const int y = counter;


int array [ y ];


while ( ClientFile %26gt;%26gt; x )


{


for ( int i=0; i%26lt;=counter; i++)


array [ i ] = x;


};


i hope i help you.....and i'll figure out the full solution


C++ Array question.... what is wrong with this code?

This program is supposed to prompt the user to enter the age of the youngest family member and ask the user if there are any more family members. after that it tells the user to enter the age of the next youngest family member and then asks again if there are any more family members. If the answer is yes, the user is prompted to enter the next youngest family members age. this continues till the user hits N for no, at which point the message"Thank you...." is printed , followed by the ages(the user entered) in reverse order. What I am doing wrong? Is it the specifying of the size of the array? I thought all arays types must have a size indicated.





Your help would be much appreciated. I will later add an ERROR message for a non-int value and exit the code and if the input is a valid int but outside of say 150 yrs(1%26lt;=ageValue%26amp;%26amp;ageValue%26lt;=150)an ERROR message shd be displayed and the user reprompted. Appropriate error messages as well as help with coding would be greatly appreciated.

C++ Array question.... what is wrong with this code?
You have a huge design problem here, unfortunately. What happens if the user enters more than 10 values? You'll need some way to keep the user from entering in more values, such as display and error message, or use a std::vector class that's part of the Standard Template Library. (Which should be part of C++). (But let's not worry about that now)





Here is a better implementation, and i also commented it so you can see what's going on (and possibly find out what's wrong with your code:





#include %26lt;iostream%26gt;





using namespace std;





//Define how many members can the user enter.


#define MEMBERS_MAX 10





int main()


{


int ageValue[MEMBERS_MAX];


char choice;





//Notify the user they can only enter up to MEMBERS_MAX family members


cout %26lt;%26lt; "You can enter up to "%26lt;%26lt;MEMBERS_MAX%26lt;%26lt;" family members."%26lt;%26lt;endl;





//This i variable is used to determine how many actual values


//have been entered (so we don't go out of bounds when we read


//the age values back.


int i;


//We wouldn't use an endless loop if we can only ask for MEMBERS_MAX members.


for(i = 0; i %26lt; MEMBERS_MAX; i++)


{


//If this is the first question, ask for youngest first


if(i == 0)


{


cout%26lt;%26lt;"Enter the age of the youngest family member:"%26lt;%26lt;endl;


}


//Otherwise, ask for next youngest.


else


{


cout%26lt;%26lt;"Enter the age of the next youngest family member:"%26lt;%26lt;endl;


}


//Query for age value of the next youngest family member


cin%26gt;%26gt;ageValue[i];





//Ask if they have anymore unless this is the last question


//(We can only accept up to MEMBERS_MAX family members)


if(i != MEMBERS_MAX-1)


{


cout%26lt;%26lt;"Are there any more family members? (Y/N)"%26lt;%26lt;endl;


cin%26gt;%26gt;choice;





if(choice == 'n' || choice == 'N')


{


//If there isn't anymore, stop asking more questins


//by breaking this loop.


break;


}


}


}





//Now, start going backwards (using the variable i)


//What was wrong in your previous code was that you have i %26gt; 10, but


//i keeps going up every iteration (you have i++), so you had an


//infinite loop.


cout%26lt;%26lt;"Thank you. The ages of your family in reverse order are:"%26lt;%26lt;endl;


for(i--; i %26gt;= 0; i--)


{


cout%26lt;%26lt;ageValue[i]%26lt;%26lt;endl;


}





return 0;


}





A better design approach is to ask the user how many family members he/she has, then dynamically allocate an array to that size, so this is not limited to only 10 family members. But I leave that up to you.





Hope this helps
Reply:For starters, your last (output) loop starts at 0 and counts DOWN... It'll NEVER end!
Reply:I am guessing you dont get any output at the end of the programm?





take a moment and reread that line of yours


for(count=0; count%26lt;10; count--)





unless it was a typo in your question - how is that suppossed to work???
Reply:N2FC...good catch on the line:


for(count=0; count%26lt;10; count--)


...I didn't see that 'till you pointed it out, so you get the tip of the hat for that.





But actually, the loop will break at at approx (256 ^ sizeof(int))/2 iterations. That's probably why our trooper didn't complain that the code hung at execution time.





Of course, the array contents won't display, because the counter will never get in range of integers 1 - 10. Should display lots of garbage in memory, tho.





jdegbor


in answer to your question about flexible array size, I'd suggest a linked list. Then you can virtually keep adding 'indexes' indefinitely. It's complex, however....tough stuff for a beginner (link for you below)





If the linked list seems too hard, you could always just create a very large array...one that's so big that 99% of users would never fill it....like


int array[5000];





This will work 99% of the time. But you should know some user, someday, may enter 5001 entries, so it's considered bad practice. Industry mistakes due to assumptions like "5000 will always be enough" have been the bane of programmers for decades.





Good luck...


C++ aRRay problem?

How would I make a program that prints out the odd positioned elements in an array of 10 integers.

C++ aRRay problem?
Its simple, see code below:





#include%26lt;iostream%26gt;





using namespace std;





int main()


{


int ar[10]; //populate the array yourself


int i = 1;


while(i%26lt;10)


{


cout%26lt;%26lt;ar[i]%26lt;%26lt;endl;


i = i+2;


}





return 0;


}





Hope this helps!
Reply:#include%26lt;iostream%26gt;





using namespace std;





int main()


{


int ar[10];





for(int i=0; i%26lt;10;i+=2)


cout %26lt;%26lt; ar[i] %26lt;%26lt; endl;





}





return 0;


}
Reply:int main()


{


int num[10];





for(int i=0; i%26lt;10;i++)


{


cin%26gt;%26gt; num[i] %26lt;%26lt; endl;


}





cout%26lt;%26lt;"Odd numbers in an array";





for(int a=0; a%26lt;10;a++)


{


if(num[a]%2==1)


{


cout%26lt;%26lt;num[a];


}


}





return 0;





}


Simple C++ Array Question?

I'm having a lot of trouble populating a very simple, 2 dimensional array. What I want this program to output is:





xx


bb





However, what I get when I compile and execute it is





xx


bbb





I don't understand it. Here's my program:





char smile2[2][2] = {{'x', 'x'},


{'b', 'b'}};





for (int row = 0; row %26lt;3; ++row)


for (int column=0; column%26lt;3; ++column)


{


if (column ==2)


cout%26lt;%26lt;endl;


cout%26lt;%26lt;smile2[row][column];





}





As you can see, it's very simple. Also, I hardcoded the array, and there are two b's in there, not three. I don't understand how the third one gets in there.





Any ideas?

Simple C++ Array Question?
The problem is in how you set up your for loops. Remember that arrays begin their indexes at 0 so you only have elements in the 0 and 1 positions. The problem is, you are outputting the smile2[0][2] position after the first endl.





Here's a more efficient way to write this process (the only changes are to the for loops):





for (int row = 0; row %26lt; 2; row++)


{


for (int column = 0; column %26lt; 2; column++)


{


cout %26lt;%26lt; smile2[row][column];


}


cout %26lt;%26lt; endl;


}





Basically the problem was that when you were accessing members of the array it was going beyond where the actual array was. When memory was allocated for your array, the positions for the second row were right after the positions for the first. So, in memory it kindof looked like this:


(some junk here) x x b b (more junk)








Hopoe that helps!
Reply:Try this





for (int row = 0; row %26lt;2; row++)


{


for (int column=0; column%26lt;2; column++)


{


cout%26lt;%26lt;smile2[row][column];


if (column == 1) cout%26lt;%26lt;endl;


}


}





The Data Analyst - http://www.squidoo.com/thedataanalyst
Reply:I think you have missed out something in this... I also cannot seem to get the answer right.
Reply:Bad indexing. You array in both dimensions has a limit of 2. Hence, you can only refer to the indices 0 and 1.





Look at your for loops. row=0 is valid, row= 1 is valid, and row=2 is valid (row %26lt; 3). The same is true of column. It's only dumb luck (and that the array was allocated contiguously) that you have three bs printing out. You could end up with a segfault because you are accessing invalid memory locations.





Also, there is no need for if (column == 2). Look, you have two for loops. Everytime you finish printing out a column, you output a newline. Hence all you need is





for (....) //loop for row


{





for (...)


{


// column stuff


}








std::cout %26lt;%26lt; "\n";





}

flower seeds

How much knowledge of the C programming language do you need to right "pong"?

I know a little about array's, know how to call different functions, and know about all the different types of loops. Is it possible to write a version of "pong" with this knowledge? Or am I just wasting time

How much knowledge of the C programming language do you need to right "pong"?
With that little knowledge you have no hope.





U need to interface with graphics etc etc etc


also controller functions


animations


. . . .


. . . .


. . . .
Reply:I didn't know pong was wrong to begin with.


How would i split a string into a char array in c++ ?

so i have asked the used to enter a word. Let's say they type in "baby"..how would I split it so that I can get an array with array1[b], array1[a], array2[b], array3[y]..thanx in advance

How would i split a string into a char array in c++ ?
string str = "baby";


string arr [str.length];


for(int i=0; i %26lt; str.lenght; i++)


{


arr[i] = str[i];


}
Reply:http://en.allexperts.com/q/C-1040/Explod...


Applying an amplitude envelope to array data in C++??

I have the raw data for a sound file in an array and I need to apply an amplitude envelope (attack - decay - sustain - release) to it using C++. Preferably I'd like the user to be able to adjust the times for each part of the envelope but this is not essential. I have 44100 samples in the array. I know I need to use a separate for loop to apply each part of the envelope to the necessary samples, and I've pretty much got my head around doing the attack part, but I'm having difficulty working out how to do the rest. I know the sample rate and everything, so the length of the sound can be calculated easily, it's just that when it comes down to actually applying the envelope I get confused!


I'm only making a console application, none of this visual stuff, so I just want the source code really.


Any suggestions for code, or even just ideas as to what processes I need to go through, would be much appreciated!


Many thanks!

Applying an amplitude envelope to array data in C++??
Suppose you had separate arrays for your A, D, S, R data, comprising floating point numbers, multiplication factors, between 0 and 1 inclusive.





Now allocate a floating point array equal in length to your sound sample data. Call this the "envelope array." Since you're a C++ guy, use new and remember to use delete after you're done with it.





Figure out how many samples long your attack, for example, should be. Then copy from your attack array into the floating point array you allocated... using linear extrapolation if you need more attack values, or skipping some if you need fewer.


Do the same for your decay, sustain, release. Then multiply your sample values by your envelope array values.


C++ Array help!?

I have an input file of fifteen lines, followed by a space, and 6 more lines...


1


2


3


4


...


15


%26lt;space%26gt;


1


2


...


6


I can load my array with the entire data of the input file, that's not the problem. However, I want to load the last six lines (after the space) into a completely different array for passing. How can I do that?


Thank you...

C++ Array help!?
I would write a method to wrap this. Just read in the file one line at a time and exit the method when you see a space or EOF. The method would look something like this:





void get_stuff(file_in_buffer, array)


{


Read in a line


if the line is blank or reached EOF - return


else push the line into your array


}





call it like this





open file


get_stuff(file_read_buffer, array_one);


get_stuff(file_read_buffer, array_two);


close file





That work for you?





Cheers!
Reply:Once you load the 1st 15 lines and hit the space, switch out the arrays and read the others into the next array.

anther

C++ Help..... Can an array contain values of different data types?

C++ Help..... Can an array contain values of different data types?

C++ Help..... Can an array contain values of different data types?
Technically no, however, you have the option of using the pointer data type so that each pointer in the array points to a different object that's been instantiated.





You would somehow need to know ahead of time what data types are associated with each index position.





Another option is to polymorphism if the objects are similar and can be derived from the same superclass or perhaps they simply have the same interface.





Another option is to use a variant data type that can represent these objects.
Reply:Definition of array is "holding any number of data in the same data type with consecutive memory. So, we can't create an array with different number of data types. Because each element should have the equal memory size.





There are two to do like that


1) Create void pointer array with number of elements as you need. And we can give the address of the any type of variable to each element of array, Even we can user defined data type and user defined class variable


void *poin[10];


int a=1;


float b=2.56;


chat *c="yahoo answers";


poin[0]=%26amp;a;


poin[1]=%26amp;b;


poin[2]=c;


cout%26lt;%26lt;*(int*)poin[0]; //type casting and printing


cout%26lt;%26lt;*(float*)poin[1]; //type casting and printing


cout%26lt;%26lt;(char*)poin[2]; //type casting and printing


Length can be applied by user need


2) create a struct variable with different variable


struct exam


{


int rno;


char *name;


float avg;


}


struct exam e;


e.rno=10;


e.name="yahoo answers";


e.avg=68.52;


//in this way number of variable can be changed after allocating the struct variable





Try this if you have a doubt mail me. I will be with you regarding this.
Reply:not in c++, someother languages do allow it though
Reply:no an array cannot contain values of different data types.since an array is a collection of elements of homogeneous data type.


C++ Help..... Can an array contain values of different data types?

C++ Help..... Can an array contain values of different data types?

C++ Help..... Can an array contain values of different data types?
Technically no, however, you have the option of using the pointer data type so that each pointer in the array points to a different object that's been instantiated.





You would somehow need to know ahead of time what data types are associated with each index position.





Another option is to polymorphism if the objects are similar and can be derived from the same superclass or perhaps they simply have the same interface.





Another option is to use a variant data type that can represent these objects.
Reply:Definition of array is "holding any number of data in the same data type with consecutive memory. So, we can't create an array with different number of data types. Because each element should have the equal memory size.





There are two to do like that


1) Create void pointer array with number of elements as you need. And we can give the address of the any type of variable to each element of array, Even we can user defined data type and user defined class variable


void *poin[10];


int a=1;


float b=2.56;


chat *c="yahoo answers";


poin[0]=%26amp;a;


poin[1]=%26amp;b;


poin[2]=c;


cout%26lt;%26lt;*(int*)poin[0]; //type casting and printing


cout%26lt;%26lt;*(float*)poin[1]; //type casting and printing


cout%26lt;%26lt;(char*)poin[2]; //type casting and printing


Length can be applied by user need


2) create a struct variable with different variable


struct exam


{


int rno;


char *name;


float avg;


}


struct exam e;


e.rno=10;


e.name="yahoo answers";


e.avg=68.52;


//in this way number of variable can be changed after allocating the struct variable





Try this if you have a doubt mail me. I will be with you regarding this.
Reply:not in c++, someother languages do allow it though
Reply:no an array cannot contain values of different data types.since an array is a collection of elements of homogeneous data type.


Generic C array sorting help.?

can some provide me with code to sort a array, that is not type dependent.

Generic C array sorting help.?
http://www.softpanorama.org/Algorithms/s...





Check out the link...





Everythingyou wanted to know about sorting
Reply:Have you tried a qsort or bubble sort?


How d you compare two rows of a multidimensional array in c++?

What are you comparing (characters, numbers, ...)?


How do you want to compare it (greater than, less than, equal to, ...)?





The basic structure is,


if ([Object1] opperator [Object2])


{


//code to be executed if true


}





Object1 and Object2 are the elements of the array you want to compare. The opperator is how you want to compare them, for example, == or %26gt; or %26lt; or != or %26lt;= and so on.

How d you compare two rows of a multidimensional array in c++?
template %26lt;class T%26gt;


bool RowCompare( int row1, int row2, const std::vector%26lt; std::vector%26lt; T %26gt; %26gt;%26amp; myarray )


{


return myarray[row1] == myarray[row2];


}

tomato plants

How to make tic-tac-toe using in c++ progamming?

uisng 2-dimentional array or array in c++

How to make tic-tac-toe using in c++ progamming?
which version are you using?


C++, array letter?

how do i find the index of the smallest and largest character in an array letters of 20 characters?

C++, array letter?
What do you mean, the smallest/largest letter? You mean find the one with the smallest/largest decimal value? If so, it's the same as you would do it with an array of numeric data types.





char letters[20];


/* fill it with some data */


int smallestLocation = 0, largestLocation = 0;


for (int i = 1; i %26lt; 20; i++)


{


if (letters[i] %26lt; letters[smallestLocation]) smallestLocation = i;


if (letters[i] %26gt; letters[largestLocation]) largestLocation = i;


}


cout %26lt;%26lt; "Smallest letter is at index " %26lt;%26lt; smallestLocation %26lt;%26lt; endl;


cout %26lt;%26lt; "Largest letter is at index " %26lt;%26lt; largestLocation;


Antoher C array question...?

Write a function that reverses the elements of an arry so that the last element becomes the first, the second from the last becomes the second, and so forth. the function is to reverse the elements in place w/o using another array, but u can use a variable to hold an element temporarily. then write a test driver(idk wat that is?) to test ur function. test it twice, once with an even # of elemnts in the array and once with an odd # of elemnts in the array.

Antoher C array question...?
#include "stdio.h"


#include "malloc.h"


int main(void){


int *a; /* The array */


int i, j, l = 10; /* Start, End and Length */


do{


a = (int *)malloc(sizeof(int)*l); /* Allocate space on the heap */


printf("sizeof(a)==%d which is equal to %d ints.\n", sizeof(int)*l, l);


j=l-1;


for(i=j;i%26gt;=0;a[i]=i--){}


i=0;


for(;i%26lt;l/2;i++, j--){ /* While we have elements left to swap */


printf("a[%d]==%d, a[%d]==%d -%26gt; ", i, a[i], j, a[j]);


a[i] ^= a[j]; /* No other variable used to swap elements */


a[j] ^= a[i];


a[i] ^= a[j];


printf("a[%d]==%d, a[%d]==%d.\n", i, a[i], j, a[j]); /* Show that we swapped the elements */


}


free(a); /* Release the array back to the heap*/


l++; /* Increment the length of the array */


} while(l%26amp;2); /* Until the length of the array is even again */


printf("All done.\n");


return 0;


}





Good luck with your coding (0;
Reply:Again...enough to get you off to a fast start...








int array[10]={0,1,2,3,4,5,6,7,8,9};





reverse()


{


int k,j;


for(k=0; k%26lt;10; k++)


{


//swap....


j = array[k];


array[k] =array[9-k];


array[9-k] =j;


}


}





testfunc()


{


puts("Numbers should appear in descending order");


for(k=0; k%26lt;10; k++)


printf("%d\n", array[k]);





}





/* A shame...lokal2b (answer just below this) presented a very clever solution using exclusive or, but even he got a thumbs down and no thanks. Tough crowd. :-) */


How can we store strings in an array in c?

that is, getting 3 names like john,david and deny using "for" loop then storing these names into an array using the same "for" loop.


simply getting and storing names will be done in the same "for" loop in any method like without using pointers.i've a doubt is there any method to getting and storing names in "for" loop without using pointers?if so please explain me........

How can we store strings in an array in c?
You may want to buy K%26amp;R's "The C Programming Language" which is the standard book for C programmers. They cover C strings. I'll point you to an online tutorial (http://www.cprogramming.com/tutorial/c/l... ).





There's two ways you can have a string. You can either have a pointer to a string literal, or have an array (either a pointer to one or the array object itself).





You may want to lookup the C standard library to see what you can use for input. (http://cppreference.com/stdio/index.html... The fgets function is particularly useful for this. If you look at the tutorial I pointed you to, they mention how to use it.
Reply:You can do it with a fixed-size array of char* s:





char* MyArray[ 3 ];





But no, there have to be pointers involved.

petal

C++ array question?

I'm trying to figure out how to store cards in a deck...the only thing I can think of is to store the cards in an array, with each card having a form (value)(suit) such as 6c for six of clubs, and 12h for queen of hearts.





So anyway, if I were to make a header function to shuffle the cards, could I do this:





void shuffle(array deck);





Can you use deck of type array as the parameter for the function, or will that not work?

C++ array question?
Absolutely.





Just use the [] delimeter to let the compiler know you're expecting an array pointer:





void shuffle(string[] deck);





Or whatever data type you're using to represent a card.





===





From a design standpoint, I think that using the "6c" format would be kind of problematic, because you then have to parse that token to get the pieces out. What I would suggest is using parallel arrays (there are more complicated structures such as structs, classes, and multidimensional arrays--but I'm assuming this is a beginning programming course so parallel arrays is what you're after).





In other words, keep two arrays of the same size, one that holds the number and one that holds the suit as an integer (1-4).





Consider this:





const int DECK_SIZE = 52;





int value[DECK_SIZE];


int suit[DECK_SIZE];





// function prototype


void shuffle(int[], int[]);





// store card 0 in the deck


value[0] = 12;


suit[0] = 3;





// function invocation:


shuffle(value, suit);





// function definition


void shuffle(int[] value, int[] suit) {


// shuffle here


}





Now you could store a value (1-13) in the value array, and a suit (1-4) in the suit array. If you want to be really fancy you could make an enumeration for the suit array, but that's up to you.
Reply:%26gt; I'm trying to figure out how to store cards in a deck...the only thing I can think of is to store the cards in an array,





Whatever data structures you use, somewhere one or more arrays will be involved.





%26gt; So anyway, if I were to make a header function to shuffle the cards, could I do this:





I'm going to pick on your terminology here (this isn't a minor point either). Functions are functions. What you put in a header file is called a declaration. What you put in source files is a definition. That's why you #include header files. You want all the declarations at the top of your source file, so you can use the functions.





%26gt; void shuffle(array deck);





What's the problem with that declaration there? See array deck? Well, we have int someint. char somechar. float somefloat. Now, what's array someArray? If you don't know how to use arrays: http://www.cplusplus.com/doc/tutorial/ar... and http://www.cprogramming.com/tutorial/les... .





What is the datatype of deck? There's no array datatype. It's a complex structure. So either Deck is a class, or you have an array of cards (which might be structures).





Also worth asking, are you familiar with the C++ STL? Have you heard of C++ Strings, vectors, map, and so on?





Finally, ask for help on either http://forums.devshed.com/ or http://cboard.cprogramming.com/ as there are actual professional programmers there who can give you technical accurate advice.
Reply:yes, it can work this way


and shuffle() will use call-by-reference to do this





your program should look like that





#include %26lt;iostream%26gt;


using namespace std;


//function prototypes


void shuffle(char *);





int main() {


//defining 4 dimensional array


char* deck[13][4][4] = {


{"Ac", "2c", "3c", "4c", "5c", "6c", "7c", "8c", "9c", "10c", "Jc", "Qc", "Kc"},


{"Ad", "2d", "3d", "4d", "5d", "6d", "7d", "8d", "9d", "10d", "Jd", "Qd", "Kd"},


{"Ah", "2h", "3h", "4h", "5h", "6h", "7h", "8h", "9h", "10h", "Jh", "Qh", "Kh"},


{"As", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "10s", "Js", "Qs", "Ks"}


};





//some lines of code


//some lines of code


//some lines of code


//some lines of code





//calling shuffe() function by ref


shuffle(deck[13][4][4]);


return 0;


}





void shuffle(char *deck) {


//some lines of code


//some lines of code


//some lines of code


//some lines of code


}





haha, copy and paste that i hope it works for you.


I'm using a 4D array, as you can see, passing it by reference to shuffle(char* )!





hope i helped!


please ask if you dont understand my prog! %26gt;.%26lt;


Easy C++ array help?

How to I set all of the values of an array (the size of the array depends on user input) to 0. I currently have (as an example):





int Array[i] = {0, 0, 0, 0};





where i is the size of the array, entered earlier.


Obviously this only works when i = 4. How could I do this so it will work whatever i.





Thanks for your help, and please try to use as simple language as possible to explain, as I have been programming for about a week :p

Easy C++ array help?
for (int j = 0; j%26lt;i; j++)


Array[j] = value;
Reply:There are as many ways as there are programmers to answer this question.





In CPP look at the new operator for an array object. Typically there is a set operator for the range of the array object. Depends on the package.





In standard C which is what you are asking:





#define MY_SIZE 20 // or any positive number


int some_array[MY_SIZE];








// first variable is the memory of the array


// second variable is the size of memory allocated


// the third variable is the value you want to initialize the array elements to





void initMyArray(int *array, int size, int InitValue)


{


int i;


for(i=0;i%26lt;size;i++)


array[i] = InitValue;


}





void main()


{


initMyArray(%26amp;some_array[0], MY_SIZE, 0);


}





Hope that helps
Reply:Check out http://www.pscode.com for great samples.
Reply:i wish i could learn c++


=(


!!!!
Reply:// use the dynamic array





int *my_array;


my_array = new int[array_size];





for(int i=0; i%26lt;array_size; i++)


the_array[i] = i;





/*where (i) is the required value for the array items it can be any formula(2i+1,-1, ... etc.) */


How to know the size of a 2D array in C ?

If the 2D array is declared explicitly, like this:


int array[16][8];


Then you can easily tell that the array is 16x8 (if you're looking for bytes, multiply that by sizeof(int)).





If the 2D array is declared as a pointer to a pointer, like this:


int **array;


Then you should find the place where the memory for it is allocated, and check what argument is given to the malloc function. It should look something like:


array = malloc(SIZE*sizeof(int));





I hope this helps.

How to know the size of a 2D array in C ?
It's been a while since I've messed with C, but:





arrayName.Length();
Reply:If you have a 2D array as a pointer, you will need to be passed the size explicitly.








Does this help?


In C, without copying out individual bytes, what's the best way to extract a 16 bit value from a byte array?

example:





unsigned char foo[5] = {0x01, 0x02, 0x03, 0x04, 0x05};





short bar;





//bar should be the 2 byte value spanning foo[1] and foo[2];





bar = (short)(foo[1] ) + (short)(foo[2] * 256); //this is correct.





I can do it this way but i was wondering if there was a casting mechanism to accomplish this without explicity addressing the two separate elements.





//Something like this...


//will only copy the 8 bit value in foo[1].





bar = (short)(*(foo + 1));








suggestions?

In C, without copying out individual bytes, what's the best way to extract a 16 bit value from a byte array?
The best way is the way you did it, accessing the two values separately ((short)(foo[1] ) + (short)(foo[2] * 256)), or you can use "%26lt;%26lt;8" instead of "*256" but the optimizer will probably produce the same code in either case. It actually will run quite efficiently. And it's the safest thing to do.





In "(short)(*(foo + 1))", the expression in parentheses beside the typecast, "*(foo + 1)", references the second character only, because foo is a char *. Casting that to a short AFTER dereferencing it doesn't cause the additional byte to get picked up.





You'd want "*((short *)(foo + 1))", I think. Add 1 to foo while it is still a char *, so that it adds only 1 byte offset. Then cast to a short * to point to 2 bytes, and then dereference.





That being said...





My recollection is that this code will not work, because foo[1..2] won't be aligned on an even byte boundary. While the C language syntax technically allows it, I wouldn't be surprised if it didn't execute. I think it will only work if you use an even-numbered offset in the character string.





For example, Microsoft Developer Network says:


"Access to data at unaligned addresses can affect correct program operation as well as processing efficiency. Some CPU architectures, such as the Itanium, cannot properly reference numeric data unless it is properly aligned in memory. When running a program on the Itanium, access to data which is not properly aligned will generate an EXCEPTION_ DATATYPE_ MISALIGNMENT exception which, if not handled, will cause the application to hang or crash."


http://msdn2.microsoft.com/en-us/library...
Reply:Arrays are contiguous memory, so if you want to bytes that are side by side, just make the short bar address = to address of the first byte from the array that you want.





If they are not contiguous, you must do by individual bytes, which is the most robust way to do it to begin with. It is fast too.
Reply:short bar = ((short)(foo[1] %26lt;%26lt; 256)) | (short)(foo[0]);





with shift and or :)

garden sheds

C++ array help?

how do you reverse the array integers like for example





3 5 6 7 8(first array) to 8 7 6 5 3(reversed array)





by the use of a definition funtion, how should i reverse the first array so it will be reversed.

C++ array help?
pass the original array into a function. then use a for loop starting wih the end of the array to fill up ur new array that will be reversed.u can find the length of the original array, and then start like this.





int size = originalarry.length;





for (int j=0,i = size-1;i%26lt;=0;i--,j++)


{


newarray[j]=originalarray[i];


}





put that into ur function, and return the newaray. try it.
Reply:int buffer;


int *p1 = array;


int *p2 = array + (array_len -1);


while (p1 %26lt; p2)


{


buffer = *p1;


*(p1++) = *p2;


*(p2--) = buffer;


}


How do I make a vector of items of a custom type in c++?

I'm getting pretty tired of using arrays, especially when the good folks who wrote the STL went to all of the trouble of providing vectors. I would like to use a vector to store items of a type that I create. For instance, if I have a type foobar that is an int, a double, a pointer, and a char, how do I make a vector of foobars and fill it?





Thanks!

How do I make a vector of items of a custom type in c++?
use vector of stl to know more go to codeproject.com


Are ints stored as bytes in an array in c#? how many bytes would an array of 5 ints be? ...help pls?

An integer is stored in four bytes in C#, not five.. it's dword/32bit


In programming (C#), why are some methods invoked different ways than others?

Example:


To invoke an array sort method, it is written


Class.Method(Instance);


or


Array.Sort(array1);





But to invoke a string split method, it is written


Instance.Method();


or


string1.Split(' ');





Why are they different and what is the key deciding factor that differentiates between the two? In other words, how will I know to write it one way or the other while coding other than trial and error?





Thanks!

In programming (C#), why are some methods invoked different ways than others?
I'm not sure about C#, but it's very similar to Java. So, they SHOULD work the same way.





//When you declare a static method, you will need to do it this way. The method will not refer to any instance variable.


//In this example, you are calling the Array class to sort array1. The Sort method dont need to refer to any instance variable to sort the array. It can just read the elements and sort it up and then return the result back to you.


Class.Method(Instance);


or


Array.Sort(array1);





//This is a non-static method. So the method is dependent on the instance variable.


//Like for this example, you are splitting the string1 variable itself.


But to invoke a string split method, it is written


Instance.Method();


or


string1.Split(' ');





You just need to understand the concept of static vs non-static methods. Do you think an Add() method needs to be static or not? Does the Add() method need to refer to any instance variable? No! All it needs is numerical values to be passed in the method then it'll just add them up and return the result. No reference to an instance variable needed.





Hope that'll help you understand the difference.
Reply:These methods are called differently because of the way they are declared in the class. Array.Sort is a static method, whereas string1.Split is a regular method. Static methods belong to the class, and are not dependent on any instance of the object to function (unless they take an instance of the object as a parameter). In other words, Array.Sort can be called even if you have not created any Array objects. Of course, if you have no Array objects to be sorted, how can you call Array.Sort when it takes an Array object as a parameter? (You can't, but the point is its AVAILABLE to be called)





So, why are some methods static (Array.Sort) and other methods are regular (string1.Split)? It's mainly a matter of practicality. Only one copy of a static method is used, no matter how many objects exist, while a copy of a regular method is created each time an object is instantiated. This can reduce the size of the compiled program dramatically, especially if there are arrays of objects. For example, consider a two-dimensional array: an Array object whose elements are all Array objects. Another reason to use static methods is style/code organization. Look at the Math class. Its a way to group all those functions together, even though you never create a Math object (infact, you cannot create a Math object).





As for knowing how to use all these methods, it is somewhat frustrating at first. You will quickly learn the commonly-used classes just from routine use; Intellisense helps me tremendously with this. I'm certain I will never know ALL of the .Net classes. I know the classes I use frequently, and when I need to use a class I'm not familiar with, I simply look it up in Visual Studio help, or go to msdn.





Hope this has been helpful, and hang in there, you'll spend less time on msdn looking up classes as you do more programming.

garden design

How do I make an array with no determined size in C++?

This is the prompt: "Write a program that asks the user to enter a series of one-digit numbers (you will need to do error checking). When they have finished (you will have to determine how the user indicates they are finished), print out how many of each number the user entered."





We are supposed to use an *array* to store the user entered numbers, but I can't figure out how to make an array of an indetermined size. (IE numarray[?] )

How do I make an array with no determined size in C++?
You don't need an undetermined-size array for this task :)


Just create an array of COUNTERS. It will be 10 counters (as there are 10 possible one-digit numbers) and each time user enters the number increase the corresponding counter. GL!





Otherwise, if you want to store all the user's input anyway, you can use the following simple class I wrote for you:





class UndeterminedArray


{


private:


int m_Count;


int * m_Data;


public:


UndeterminedArray()


{ m_Count = 0; m_Data=0; }


~UndeterminedArray()


{ delete[]m_Data; m_Count=0; m_Data=0; }


void Add ( int inNewValue )


{


int * temp = new int [ m_Count+1];


if(m_Data) memcpy(temp,m_Data,m_Count*sizeof(int));


delete [] m_Data;


m_Data = temp;


m_Data[m_Count++]=inNewValue;


}


int GetCount ( void ) const


{ return m_Count; }


int operator[] ( int inIndex )


{


if(inIndex%26lt;0 || inIndex%26gt;=m_Count) return 0;


return m_Data[inIndex];


}


};
Reply:main(int argc,char argv[])


Use the parameters, if you do not understand may be you can contact a freelance programmer to help your out. Check websites like http://getafreelnacer.com/
Reply:First you have to create a limked list class using pointer where each elememt will store a one digit number and a pointer to the next element in the list. You have to create a method to add element at the end of the list. You can create an instance of that class within the main function and use pointers for storing %26amp; retrieving digits.
Reply:If they are one digit numbers there can only be 10 elements in the array.





int array [10] ;





If you read as a characters, you need to check that the value is in the range '0' ... '9'.





If you read as integer, you need to ceck the value is in the range 0 ... 9 .
Reply:u want an array of undetermined size.


I suggest you to use dynamic array with the help of pointers.


If u really want its solution using that let me know I will post that
Reply:im not sure if you are talking about this http://www.chips.navy.mil/archives/99_ju... or not ive always use a high determing # to make it easy like 50 or 60 even but you can try list array or smart array also. sorry i cant hellp more
Reply:You cannot make an array of undetermined size. That’s another way of saying you want memory, but you won’t tell the computer how much. The computer can’t handle that.





Ideally, you should use the stl vector for this. That is one of the ideas behind using C++ anyway. If you really want to use arrays, a linked list of arrays is probably the smartest idea.





Your other option is to allocate a really really really large array. This isn’t as failsafe as the linked list of arrays (or the vector) but your homework probably isn’t testing for absolute robustness here.
Reply:Make it easy on yourself, make its size 50 or 60





then a loop and get the loop to exit once the user type end or -1 or whatever.





if you wanna go the long way, then take a look at ArrayList but I think the example is way too simple to use arraylist
Reply:Either use pointers,or store the digits individually and then add them later when the user finishes...it sounds lame,but I think it works....


How do you convert string into float c++?

If I have a character array:





char a[]={"92*43-2*2/+"};





How would I convert each number in this array to a float?





I've attempted different methods but I end up getting the decimal value for the ascii character.





For example converting 0 to a float I end up with 48.

How do you convert string into float c++?
You would have to write a function to parse the string into its numbers and operators.





Then you would have to write code to apply the operators to the numbers, making sure to use the proper prescendence.





I have no idea how to interpret that "/+" at the end of the string.
Reply:That isn't converting a string to float, it is processing a command string of calculator commands, which is much more.


This would be a string that could be converted to float by skipping the first character "$12345.65"


Questions again on c++ arraying?

question for example,





if a question asked me...do you wish to add a person to your house hold? (the house hold is the array in this case). House hold can hold a total of 10 people. If a question ask me if i want to add a person to my household, how do i write a for loop that will add that person to the first array [0] in the household? But after i added that person and i wanna add another person, how should i write a for loop that will also add the second person and store it in the household array [1] and if i want to add more people, and store them [2], [3], [4], respectively. Can you tell me how for loop works in this situation? and can u give me a example of how it should be like?

Questions again on c++ arraying?
Why dont you ask it in programming, they help a lot there, but im sorry i dont know any C++ or C as wel


I have a for loop in C# to add controls to a new form. How can I name the new controls?

So, basically I have a for loop that goes through the array of selected items from a list box. I want to then open a new form and create a new label control for each selected item. How can I create these inside the loop?

I have a for loop in C# to add controls to a new form. How can I name the new controls?
foreach(object o in listBox1.SelectedItems)


{


Label newLabel=new Label();


newLabel.Text=o.ToString();


//coordinates here





this.Controls.Add(newLabel);


}
Reply:foreach( ------ ) {


Label lbl = new Label();


lbl.Text = ""; // set Text for your label


lbl.length = .. // set other properties for your label here





//add the label to the Form:


this.Controls.Add(lbl);


}





for more info you can check:


http://support.microsoft.com/kb/319266





Hope this helps.
Reply:For my program, I used XML serialization, and had a property for the name...that seemed like the easiest way. You'll have to learn how to do this from a book or a website if you don't know how to already...kinda long to explain here.

flower pictures

Bubble sort in c programming arranges in ascending or descending order?

arrays in c language

Bubble sort in c programming arranges in ascending or descending order?
void bubble(int x[], int n)


{


int hold, j, pass;


int switched = TRUE;





for (pass=0;pass %26lt; n-1 %26amp;%26amp; switched == TRUE; pass++)


{


switches= FALSE;


for (j=0;j %26lt; n-pass-1; j++)


if(x[j] %26gt; x[j+1])


{


switched = TRUE;


hold = x[j];


x[j] = x[j+1];


x[j+1] = hold;


}


}


}
Reply:descending order i guess
Reply:Now in general It works to arrange the array in ascending order.


The code portion


/*if(a[i]%26gt;a[i+1])then


swap;*/ does the main job.If you change the %26gt; sign to %26lt; sign then it will arrange the array in descending order.
Reply:it depends on your code.


you can make it in ascending or descending order.
Reply:Its depends on how you are implementing the bubble sort. There is no fixed rule. Its up to the programmer how he wants to implement it. Both ascending and descending order are valid. This applies to all the sorting algorithms.
Reply:Both the way you can sort. It depends upon your code.


C++ array function programming. PLEASE HELP!!!?

How would you implement the following two functions?





SetData(int, double); //Sets the int-th element to the value of the passed double.





double GetData(int); //Returns value of the int-th element. If passt the array boundaries, then return the first or last element.





Please help and explain.

C++ array function programming. PLEASE HELP!!!?
May be you can post your requirements at http://homework.gionram.com/


and let many programmers bid for your project.


You can hire whoever you like.





Do not pay any money afront however.
Reply:Are we talking just an independent function or a class member function? I can only assume you mean a class member function since you did not include the array itself in the parameters.





class MyArray


{


private:


m_Array[ARRAY_INDICES]





public:


const int ARRAY_INDICES=10;





void SetData(int n, double val)


{


if ( n %26lt; 0 || n %26gt;= ARRAY_INDICES )


{


// maybe throw an exeption


return;


}


m_Array[n] = val;


}





double GetData(int n)


{


if ( n %26lt; 0 || n %26gt;= ARRAY_INDICES )


{


// maybe throw an exeption


return;


}


return m_Array[n];


}





};


How will i sort 5 numbers in an array using c language??

Your question is not clear.


How do you want to sort the 5 numbers?


Ascending or descending? or any other way?


How can we arrange all o's element to the end of the list in array in c++ programming code?

other elemtents to the left of the list.

How can we arrange all o's element to the end of the list in array in c++ programming code?
thats a tough one to ask...it would help if you could post the rest of your code here.





Edit: how about something like, if number=0, place it in end of array?

credit cards

Example of multi dimensional array in turbo c?

i dont know how to manipulate array in turbo c

Example of multi dimensional array in turbo c?
An array is a variable that has space to hold 1 or more instances of only ONE data type.


Example:


unsigned int fuzz[256];


This allocates enough memory for 256 unsigned integers, referenced by the variable name fuzz.


You can store up to 256 unsigned integer numbers in that array. Example: 4,5,7,10,etc.


If you want to write a number to the array, you would write something like: fuzz[2]=4;


In this case, the unsigned integer 4 is written to the 3rd location of array fuzz (array numbers start at 0, not 1!).





A multi-dimensional array is like a matrice.


Using my previous example, you can think of a single array as 1 row of numbers. A multi-dimensional array can be thought as having multiple rows of data.





Example:


unsigned int foo[256][256];


This is a two dimensional array.


Think of it as 1 row of numbers, with another row of numbers beneath it.


To write to the first location in the SECOND row, you could do this: foo[1,0]=4.


The first number in the bracket represents the row number (0-1 in this case) and the second number represents the location on that particular row. The number 4 is written to the second row, 1st column on that row.
Reply:yes


Can anyone help me write this in C code?

a) Declare an array of 25 integers.





b) Write a line of C code that will print out the value of the 10th item in the array you declared in a).











c) Write C code that will print out every item in the array, in its order in the array (i.e. by index number), in 5 lines of 5 items each.

Can anyone help me write this in C code?
take help from an expert


http://homework.teamtutorial.com/
Reply:#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;


void main()


{


int arr[25];


clrscr();


//assign value to 10th item as


arr[10]=25;


printf("%d",arr[10]);


getch();


}
Reply:a) int a[25];

brandon flowers