Sunday, August 2, 2009

C++Write the prototype and definition of the function hasnegative() which accepts an integer array and its siz

I'm can't finish in time without help . Write the prototype and definition of the function hasnegative() which accepts an integer array and its size and returns true if any array element is %26lt; 0, otherwise it returns false. Test this function in a simple program with a 5-element array entered by the user.





I only got started on this, I know it's easy to most, but programming is my sworn enemy!








int x[];








for (int k=1; k%26lt;=10; k++)


{


if (x[k] %26lt; 0)


return 1;


else


return 0;


}

C++Write the prototype and definition of the function hasnegative() which accepts an integer array and its siz
When I was first learning C++, I had trouble with pointers too. Here's a working version.





PROTOTYPE = bool hasnegative( int*, int)





FUNCTION:





bool hasnegative( int* array, int size )


{


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


{


if ( *(array+i) %26lt; 0 ) return true;


else return false;


}


}





Just pass this function the array and it's size. When you pass the array, what is passed is the address of the first element of the array. When an array is declared, it allocates a contiguous number of memory cells (so everything in the array is all grouped together in the one location). Since we have the address of the first element, all we have to do is add 1 to this address to then have the address of the 2nd element. Add 2 and you will have the address of the 3rd element, and etc.





Just loop through it, and access the value at that memory address (using the *), and that's about it.
Reply:Some people have a thing for it, some people don't. Don't worry, it takes some getting use to regardless of what level you start at.





It would usually be best to pass only the array and have the function determine the size of the array. However, lets just say that you trust the user to pass the correct size for the array.





You have your if-statement wrong, you only want to return false if the number is less than 0. Remove the else statement. The else statement forces a return after checking the first position in the array, which in turn ends your loop and function.





At the end of your for-loop (outside the loop), return true. This allows your program to check all the values in the array. If it found a negative one then it would have returned false. If it didn't find one, then you'd reach the end of your function where it would return true.


Storing an array of names to check against - c programming?

Here is my code, it needs to check against a possible names on the list , but it isn't compiling . Can you please tell me what the reason to this is ?





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


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





int main() {


int name[] = {"EDDIE","BEN","DAVE"};





char guess[10];


int correct = 0;


char * p;





printf("Enter a name in uppercase: ");





while(!correct) {


fgets(guess ,10, stdin);


p = strchr(guess, '\n');


if ( p )


*p = 0;





if(strcmp(name, guess)==0) {


printf("Correct!\n");


correct = 1;


}


else {


printf("Try again: ");


}


}


}

Storing an array of names to check against - c programming?
I'm too tired right now to go through your whole program, but what stands out is the way you have declared the name[] array.


The name[] array should be 'char' or 'unsigned char' and not 'int.'





Arrays are a collection of a certain data type and each array element are of the same data length.


The line below is an array of 1 byte signed data which consists of the ASCII number equivalents of "a", "b", and "c":


char fuzz={"a","b","c"};





In the case of strings, it is possible that each string element in the array may be of a different length, so you have to be careful when you declare an array of strings. There are 2 ways to declare an array of strings.





One method is like this:


char *name[]={"Hello"," out", "there"};


Notice the * in front of name[]. This means that I'm actually declaring an array of char pointers, but each pointer is initialized to point to 3 strings. The compiler creates 2 sets of data; There are the 3 data strings and there are 3 memory address pointers which point to their respective strings. For example, the first pointer (name[0]) points to the start of the "Hello" string.


The long way of accomplishing the method above would be something like this:


char *name[3]; // an array of 3 char pointers


char ptr1[]="Hello"; // declare 3 char strings:


char ptr2[]="out";


char ptr3[]="there.";





(inside main() procedure)


name[0]=ptr1; // name[0] points to "Hello"


name[1]=ptr2; // etc.


name[2]=ptr3;








The second method forces you to specify the length of each string. You have to do this because each element in the array must be the same size.


Example:


char name[][6]={"Hello","out","there"};


or


char name[3][6]={"Hello","out","there"};





The [6] means that each string element is 6 chars long. If one of the strings is less than 6 chars long, then there will be left over data at the end of the string. C/C++ strings are always zero-terminated, so the extra bytes after "out" is no big deal. The [3] in the 2nd example means that I am specifying that there are 3 strings in the array.


As you can see, this method may waste some memory space since each string element must be the same length.
Reply:*i know C++ programming, but both r quite similar, so tryin to answer anyway*





int name[] = {"EDDIE","BEN","DAVE"};





not sure what ur doin is this line, u put strings into a int array.


im guessin thats ur prob.


change it and try again.


also if u make it a char array it has to be a 2D array, and indent the braces properly, makes it much easier to read and check.
Reply:Expanding on the previous answer, yes, remember C does not have a string data type - though C++ does. A string in C is nothing more than a char array





char* str = "EDDIE\0";





there are numerous was to initialize a char array (string) in C. Remember C strings must also be null terminated. What you are attempting to do is really a 2D ragged array - an array of char pointers.


C++: how do i sort numbers in descending order without using an array?

I have to sort 5 randomly generated numbers into descending (and ascending) order. The only problem is I havent actually learned arrays and are not really allowed to use them.


How would I make these numbers sort without the use of an array?

C++: how do i sort numbers in descending order without using an array?
If you have learned Linked list,then I can give you a solution:





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


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





typedef struct node


{


int val;


struct node *next;


}*listptr;





listptr getnode (void);





void main()


{


int i,x;


listptr a,b,c;


b = getnode();


//generate the numbers randomly and put them in the list


randomize();


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


{


x = rand();/*the function is r-a-n-d without the hyphens,don't know why it's coming as **** */


a = getnode();


a-%26gt;val = x;


a-%26gt;next = NULL;


if(i != 0) b-%26gt;next = a;


if(i == 0) c = a;


b = a;


}


b = c;


printf("\nOriginal list :-\n");


for(a = c;a != NULL;a = a-%26gt;next)


printf("%d ",a-%26gt;val);


//Now sort them


for(a = c;a-%26gt;next != NULL;a = a-%26gt;next)


for(b = a-%26gt;next;b != NULL;b = b-%26gt;next)


if(a-%26gt;val %26gt; b-%26gt;val) /*for ascending order '%26gt;',for descending order.'%26lt;' */


{


x = a-%26gt;val;


a-%26gt;val = b-%26gt;val;


b-%26gt;val = x;


}


printf("\nSorted list :-\n");


for(a = c;a != NULL;a = a-%26gt;next)


printf("%d ",a-%26gt;val);


}


listptr getnode (void)


{


listptr a;


a=(listptr)malloc(sizeof(struct node));





return(a);


}
Reply:You can use the functions that C++ has already supplied, which inherently uses arrays. You should probably let us know how you're storing them. Supposing they are just Ints being randomly generated, you can brute force it. Just compare the numbers to each other - there are only so many comparisons since you only have 5 numbers. However, I'm still not sure how you would store them since you can't use arrays.





EDIT: I am assuming you've got a unique variable for each randomly generated number.
Reply:Ooooo...


This is DIFFICULT. The best way to do this IS WITH ARRAYS. Since you don't know, you can learn:


An array is a pointer. Well, actually its name is a pointer. A declaration like:


int num[5];


Tells your compiler to reserve 5 ints in memory (consecutively, as you will see). When you say something like:


a=num[2];


It expands to:


a=*(num+2);


Which works because pointer arithmetic states that adding an unsigned value to a pointer will shift the address of that pointer by that many types (ints are usually two bytes, so the previous statement shifts the address of num by 4 bytes). The * operator (nothing to do with declaring a pointer by stating int *a) dereferences, or gets the value at the address of, its input. The first statement declares five contiguous memory locations to hold ints, which can be accessed (and assigned) by referencing:


num[0] //First


num[1] //Second


num[2] //Third


...


Sorting an array is pretty easy (remember that arrays are pointers, so saying a function accepts a pointer is the same as saying it accepts an array. Remember, also, that since pointers are addresses, modifying a pointers dereferenced value WILL CHANGE THE VALUE OF THE MEMORY IN THE CALLER):





void Sort(int *a)


{


int pass, num, temp;


for(pass=0; pass%26lt;(sizeof(a)/sizeof(int)); pass++)


for(num=0; num%26lt;(sizeof(a)/sizeof(int))-1; num++)


if(a[num]%26gt;a[num+1]){


temp=a[num];


a[num]=a[num+1];


a[num+1]=temp;}


}





Temp is required because of the destructive read-in principle.


Read some more, and sorry I couldn't help without arrays.





Oh, and the function doesn't return, but the passed array comes back sorted.
Reply:Well you could put them in an array:





int arr[5];


arr[0] = x; arr[1] = y; [...]





OR





You could hard-code the actual sorting, but this is very messy. It would do something like:


(let's name the variables x0, x1, ...x4)





SORTING DESCENDING:





if (x0 %26lt; x1) swap(x0, x1);


if (x0 %26lt; x2) swap(x0, x2);


if (x0 %26lt; x3) swap(x0, x3);


[...]


if (x3 %26lt; x4) swap(x3, x4);
Reply:How are you storing these 5 numbers at the moment ?
Reply:1) Use individual variables for each of the numbers,


name them Num1, Num2, ... Num5





2) Use another set of numbers to store their position in the sorted order, name them Index1, Index2, ... Index5





3)


Num1 = random();





Num2 = random();





Num3 = random();





Num4 = random();





Num5 = random();








4) Check


if (Num1 %26lt; Num2)


{


if (Num1 %26lt; Num3)


{


if (Num1 %26lt; Num4)


{


if (Num1 %26lt; Num5)


{


//Num1 is smallest


Index1 = 0;


}


}


}


}





* this is a very strange logic but can work based on your limitations.





* this is not the complete solution but just a hit so complete the rest if you have picked my point





* I am your teacher.





* Just kidding ;)
Reply:Since you cannot use an array, you can use a linked list to hold the values. Then do your sort on the list. Hey, you are not using an array.

gladiolus

C++ how do I point to an element in an existing array?

How can I create a pointer that points to a specific item in an existing array (say item 5) and will let me then use that pointer like an array?





Here is my code:


http://www.marcovitanza.com/pointerArray...

C++ how do I point to an element in an existing array?
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};


int *ptr;


ptr = array + 4;





Now ptr points to the 5th element in the array (remembering element 1 is offset 0)


Can u help me write this program in c/c++ a program which sorts an array of ten elements in ascending/descendi

ing order

Can u help me write this program in c/c++ a program which sorts an array of ten elements in ascending/descendi
When you get a job after high school, do you plan to post all your work here and ask people to do it for you?





You may want to try your hand at doing the homework yourself so you can learn it and understand what the C source code does. Who knows? You may find it interesting and fun.





There is an old saying:


Give a man a fish and he will eat for a day. But teach a man to fish, and he can eat for a lifetime.





(If you don't understand, go ask your English teacher about analogies and symbolism)
Reply:I'm going to parrot Steve's answer. If you give it a real try and you have some questions, that's fine. However, I will not do your homework for you.
Reply:int main ()


{


if (I answer this question)


then (you won't learn)


}


Pusha and Pop arrays. Need crtique on stuff I have. C programming?

Write a program that implements a stack with at most 30 integer elements with operations push and pop as defined


below:


A. Declare an integer array with a size of 30 elements.


B. Write a function called push that will insert an integer into the array.


C. Write a function called pop that removes the top-most element in the array.


D. Write a main function that takes input from the user based on integers: 1 - PUSH; 2 - POP; 3 - EXIT. Whenever


the user enters 1 (for PUSH), the integer that follows it is the element to be pushed.


E. The program prints as output the elements of the stack at the end of input and prints the maximum size to


which the stack grew during the operation.





#define value 30


void push(int value)


{


stack[i]=value;


i++;


}


int pop()


{


int temp=stack[i];


stack[i]=0;


i--;


return temp;


}

Pusha and Pop arrays. Need crtique on stuff I have. C programming?
when i=0, u need to give a print statement " underflow "
Reply:What happens when i = 0 and you pop?


C++ help...How do you store calculated values into a new array?

here's the part i'm having trouble with...i have read data from a file and stored it into 2 arrays. now i'm calc the average of the test....but i want to store the averages into a new array.





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


{





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


{


inputFile %26gt;%26gt; testScores[i][j];


cout%26lt;%26lt;testScores[i][j]%26lt;%26lt;"\t";


}


inputFile%26gt;%26gt; StudentNames[i][1];


inputFile%26gt;%26gt; StudentNames[i][2];


cout%26lt;%26lt;StudentNames[i][1]%26lt;%26lt;" "%26lt;%26lt;left%26lt;%26lt;setw(15)%26lt;%26lt;StudentNames[i][2]%26lt;%26lt;"...





}


cout%26lt;%26lt;endl;





double avg, sum;


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


{


double sum=0;


for(int tnum=0; tnum%26lt;TEST; tnum++)


sum = sum + testScores[row][tnum];





avg = sum/TEST;





now to store these averages into a new array

C++ help...How do you store calculated values into a new array?
double avg, sum;


double averages[STUDENTS];


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


{


double sum=0;


for(int tnum=0; tnum%26lt;TEST; tnum++)


sum = sum + testScores[row][tnum];





avg = sum/TEST;


averages[row] = avg;


}

narcissus

When loading a file in c++ how can i return an array of structures, from the load function to the main?

struct RecDetails LoadRecords(int %26amp;NumRecs)


{


struct RecDetails Quotes[MAX_QUOTES];





ifstream InFile;


int i = 0;





InFile.open("Test.txt");





while(!InFile.eof())


{


InFile %26gt;%26gt; Quotes[i].QuoteNum;


InFile.getline(Quotes[i].Name, BUFF_LEN);


InFile %26gt;%26gt; Quotes[i].Cost;


InFile %26gt;%26gt; Quotes[i].DeliveryCharge;


InFile %26gt;%26gt; Quotes[i].GuaranteePeriod;


i++;


}





InFile.close();





NumRecs = i;


return Quotes;


}











...








then in main::





struct RecDetails Quote;


struct RecDetails Quotes[MAX_QUOTES];





Quotes = LoadRecords(NumRecs);








keeps appearing with E2034 cannot convert 'RecDetails' to 'RecDetails' errors,





any help people?





If can help on msn or somethin, jimmyhigg@hotmail.co.uk, ill be about finishing this assignment for the next week no doubt...

When loading a file in c++ how can i return an array of structures, from the load function to the main?
don't have a clue to your question, just felt sorry for you cos no-one had answered your question and i didn't want you to feel left out.


Using C++ How can I alter the code so it will print the array of names in alphabetical order?

Below --%26gt; Program, Actual Output, and Desired Output:





Program:


int main


{


string names[3] = {"Smith, John", "Anthony, Mark", "Gibson, Mel"};





bubble_sort(names[3]);





for(index=0; index%26lt;3; index++)


cout%26lt;%26lt;names[index]%26lt;%26lt;"\n";


}





void bubble_sort(string%26amp; array)


{


int i, j, flag = 1;


char temp;


int arrayLength = array.length( );


for(i = 1; (i %26lt;= arrayLength) %26amp;%26amp; flag; i++)


{


flag = 0;


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


{


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


{


temp = array[j];


array[j] = array[j+1];


array[j+1] = temp;


flag = 1;


}


}


}


return;


}





Actual OUTPUT:


Smith, John


Anthony, Mark


Gibson, Mel








Desired OUTPUT:


Anthony, Mark


Gibson, Mel


Smith, John

Using C++ How can I alter the code so it will print the array of names in alphabetical order?
Several problems:





%26gt; bubble_sort(names[3]);





this is accessing the 4th element of the names array (first 3 elements are at indices 0, 1, and 2). this is why you're getting your output, it's not sorting anything! i'm surprised this program didn't crash. instead you simply want to pass 'names' as the parameter - this means you are passing the entire array as a parameter, not a single element of the array. proper:


bubble_sort(names);





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





this would sort the array opposite the way you want it. simple fix is using less-than instead of greater-than. BUT, if i'm not mistaken, you can't compare strings like that. you have to use strcmp, like this:


if (strcmp(array[j+1], array[j]) %26lt; 0)


otherwise, you are just comparing pointers.

statice

C++ problem involving reading a numbers from file, putting into an array, then processing?

Alright, so the problem goes like this:


Write a program that asks the user for a file name. Assume the file contains a series of numbers, each written on a separate line. The program should read the contents of the file into an array, and then displays the following data:


-The lowest number in the array.


-The highest number in the array.


-The total numbers in the array.


-The average of the numbers.

C++ problem involving reading a numbers from file, putting into an array, then processing?
[Amanda H, I just gave you a thumb up. I hate people who don't appreciate the time and effort you are spending here to help others. Thank you!!]








Here are some of your problems:





1) average must be a double NOT an integer because it could be something like 12.75





2) Always, always, always, initialize your variables once you declare them like this:





int count = 0, highest = 0, lowest = 0, total = 0;


double average = 0.0;





3) To make your program better you can use a single for loop (the one that reads from the file) to find the total, highest, and lowest. Here is how you do this (you don't need to do it, but it will make your program faster and more efficient):





for (count = 0; count %26lt; SIZE; count++)


{


inputFile %26gt;%26gt; numbers[count];


total+= numbers[count];





if(count ==0)


highest = lowest = numbers[count];


else


{


if(numbers[count] %26gt; highest)


highest = numbers[count];


if(numbers[count] %26lt; lowest)


lowest = numbers[count];


}


}





4) Now to calculate the average do the following:


average = (double) total / (double) SIZE;





5) Don't forget to include the following:





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;string%26gt;





6) To get the file name from the user as input do the following:





string fileName = " ";





cout %26lt;%26lt; "Enter the name of the file: ";


cin %26gt;%26gt; fileName;





// To open the file, use the following line of code:





inputFile.open(fileName.c_str());





7) You said your program won't work if you increase size to 50 but I don't see why that would happen. If you just change SIZE to 50 your program should work UNLESS the file contains LESS than 50 numbers. Make sure your data file contains at least what you set SIZE to.





// That's all I have. I hope this helps you. Let me know if you


// need anymore help. Good luck!!
Reply:The keys to this problem are:





ifstream() and array loops.





Here is some code to help you out. Note that you don't really need the array, but if this program is built on, the array will be there.





EDIT: Thanks whoever thumbs downed me. ******.So much for trying to help.





Note that there is no limit on file size since the array is dynamically allocated.





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


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





int main(void){


char filename[256];


int *numarray;


ifstream file;


int count;


int value;


int total=0;


int high=0;


int low=0;


cout%26lt;%26lt;"Enter Filename-%26gt; ";


cin%26gt;%26gt;filename;


file.open(filename,ios::in);


file.seekg (0, ios::end);


count = file.tellg();


numarray=new int[count];


file.seekg (0, ios::beg);


count=0;


while(file.good()){


file%26gt;%26gt;numarray[count];


if(count==0) {high=numarray[count]; low=numarray[count]; }


total=total + numarray[count];


if(numarray[count] %26gt; high)high = numarray[count];


if(numarray[count] %26lt; low %26amp;%26amp; numarray[count] !='\0') low=numarray[count];


count++;


}


cout%26lt;%26lt; endl %26lt;%26lt;"Low: "%26lt;%26lt; low %26lt;%26lt;endl;


cout%26lt;%26lt;"High: "%26lt;%26lt; high %26lt;%26lt;endl;


cout%26lt;%26lt;"Total Numbers: "%26lt;%26lt;count-1%26lt;%26lt;endl;


cout%26lt;%26lt;"Average: "%26lt;%26lt;total/(count-1)%26lt;%26lt;endl;


}





If you need to use the array aspart of the project, take everything in the while loop out except the file%26gt;%26gt; and the count++ lines and stick them into a for loop as such:





for (x=0;x%26lt;count;x++){


if(x==0) {high=numarray[x]; low=numarray[x]; }


total=total + numarray[x];


if(numarray[x] %26gt; high)high = numarray[x];


if(numarray[x] %26lt; low %26amp;%26amp; numarray[x] !='\0') low=numarray[x];


}
Reply:I won't do it for you, but here's some clues...





Get the filename. Open the file using fopen (and work with it using fread and fclose - look them up).





Technically you don't even need an array - you can set a variable for the lowest number (set it high, and if it's lower than the high variable, set the high variable to it), and the opposite to find the highest (set it to zero, unless you're using negatives, and if it's greater, set the lowest to it), count up the numbers (for total numbers) and add up the numbers so you can give the average at the end (total / #numbers).





If you read them in as strings you may have to convert them with atoi function (ascii to integer).





Good luck!


In C++, how do I get the size of an integer array that was dynamically allocated by the user?

In addition, after I determine the size, I need to expand the array to a certain length based on user input by placing 0's in FRONT of the preexisting values.


for example if the array orginally contained a[0]=4, a[1]=5, a[2]=6, a[3]=7 , the user can input a length of 7 that will make a[0]=0, a[1]=0, a[2]=0, a[3]=4, a[4]=5, a[5]=6, a[6]=7

In C++, how do I get the size of an integer array that was dynamically allocated by the user?
You can not find out the size of a dynamic array (i.e. pointer)- you need to store it in a variable somewhere. To extend the buffer create a new one and copy over the old elements. There might be cases where you actually want to do this in general however, it is a much better idea to use std::list or std::vector !





int myArraySize=100;


int* myArray= new int[myArraySize]; // create


for (int i=0; i%26lt;myArraySize; ++i) // fill it up with data


myArray[i]=i;


int* newArray= new int[myArraySize*2];


memcpy(newArray+myArraySize, myArray, myArraySize*sizeof(int) ); // copy old array into tail of new array


delete[] myArray; // get rid of previous elements


// now update pointer and size info


myArray= newArray;


myArraySize= myArraySize*2;
Reply:I would create a data structure such that values can be put in on either right or left side, and taken out by index, relative to start. Store size as a data field, and create a method for expanding the data structure. Store it in a circular manner.
Reply:I don't think this is a good idea because it would be inefficient. You should instanciate class List instead. If you still insist on array, you can do it only by defining your own class in which you have to define a veriable to keep track of length allocated. To append more elements you will have to define a new array of the size existing_length+no_of_elements_to_append... then copy previous array and inserting 0s to the rest. Can you imagine how unprofessional approach this will be?


In C I have a data structure that has a character array. How do I pass the array to another function?

If my array in the structure is: char word[20];


how do I pass this to this function?





pointer NewListNode(char n) {


pointer p;


p = (pointer) malloc(sizeof(list));


p-%26gt;word = n;


p-%26gt;ptr = NULL;


return p;


}





This is wrong...the compiler said "incompatible types in assignment" where it says "p-%26gt;word=n. What is the correct syntax?

In C I have a data structure that has a character array. How do I pass the array to another function?
Well, your variable "n" is a character (char), and not a character array. So, something more appropriate would be:





"p-%26gt;word[3] = n;"





This would make the 4th character in the array equal to whatever "n" is. If you want "n" to be an array, the function should be like:





"pointer NewListNode(char* n) {"





Where the "char*" means that "n" would be a pointer to the array of characters.
Reply:use inheritanceand make sure that the class is public


How do I modify this simple C++ program to use a vector instead of an array?

The textbook I am using very briefly explains vectors and I don't fully understand it. One of the problems in the book wants me to modify an exercise program completed earlier to use a vector instead of an array. Can you help? Here's the code using an array:





#include %26lt;iostream%26gt;


#include %26lt;ctime%26gt;


using namespace std;





int rollDice();





int main()


{





int a[11];





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


a[i]=0;





srand(time(0));





for(int counter = 1; counter%26lt;=36000; counter++){


a[rollDice()]++;


}





for (int j = 2; j %26lt;= 12; j++)


cout %26lt;%26lt; "The number of " %26lt;%26lt; j %26lt;%26lt; "'s rolled: " %26lt;%26lt; a[j] %26lt;%26lt; endl;





cout %26lt;%26lt; endl;


system("PAUSE");


return 0;


}





int rollDice()


{


int die1 = 1 + rand() % 6;


int die2 = 1 + rand() % 6;





int sum = die1 + die2;


return (die1 + die2);


}





The above program rolls 2 dice and outputs the # of times each possible total is rolled (2-12).

How do I modify this simple C++ program to use a vector instead of an array?
#include %26lt;vector%26gt;





vector%26lt;int%26gt; myVector;





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


myVector.insert(i);





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


cout %26lt;%26lt; myVector[i];








you can also use an iterator like this:





vector%26lt;int%26gt;::iterator myVectorIterator = myVector.begin();


while(myVectorIterator != myVector.end()){


cout %26lt;%26lt; *myVectorIterator;


myVectorIterator++;


}
Reply:How about a vector of vectors instead of using an array...
Reply:My advice: Read the book, learn about vectors, and do it yourself.





This is not me trying to prevent you from getting the answer you need, but rather, telling you the best way I know of (from experience) to learn something and REMEMBER it better.

clematis

Can anyone tell me in C language, the difference between character array and string array?

A character array consists of single characters. A string array consists of groups of characters.

Can anyone tell me in C language, the difference between character array and string array?
you are a real curious boy.





character array= a line of characters. note there is always a null char in every char array.





null char= a "bank" space/char==no actual use =p








string array is a actually the same.


string= line of "something"


array= a specific line of string





hope that helped you =p
Reply:The Character array is group of characters (in their ASCII codes).


They are generally one dimensional.





There is no termination symbol for this.





BUt the string array is group of strings (which is again group of characters)


It is mandatory to have two dimensional array for a string array.





String array is terminated with '\0'
Reply:In C a charachter array is a array storing charachters. A string is a charachter array ending with '\0' character which marks end of string. A charachter array containing 'a', 'b', 'c', 'd', '\0', 'e', 'f', 'g' is a charachter array with 8 charachters, but is a string with 4 charachters as fifth element '\0' marks the end of string.





When you say string array, it can mean a array of pointers each pointing to a string.
Reply:A character array consist of single characters while string array consist of s group of characters.
Reply:A string is a character array.


A string array is an array of strings.


Does anybody know how to send data (or an array) to USB port using C++ programming language?!?

I'm working with graphic user interface (GUI) that prompt the user to choose a command. This command (data) will be send a set of data to the USB port which is conected with bluetooth dongle. I have finished creating the GUI. My problem is, how to send the data to the USB port so that it can be transmitted using the bluetooth dongle?! Please help..

Does anybody know how to send data (or an array) to USB port using C++ programming language?!?
Well to be honest I have no real idea, you will have to access the driver through some API, not that that helps you much, but you might try here: http://msdn2.microsoft.com/en-us/library...


Looks like this could be what you need. Oh, I am assuming you are using Windows.
Reply:We have to study about the hardware interface with C++. And the we can send data to USB port. In pointer concepts we can control whole system.


With pointers only the device interface are created.
Reply:copy to....whatever the drive letter is.


Question for C programming Dynamically allocate an integer array things with 10 elements.?

main()


{


int a[],n;


clrscr();


printf("Enter the array Length:");


scanf("%d",%26amp;n);





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


{


prinf("Enter the values a %d",i);


scanf("%d",%26amp;a[i]);


}


printf("The Array Vales are:");





int a[],l;


clrscr();


printf("Enter the array Length:");


scanf("%d",%26amp;l);





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


{


prinf("Enter the values a %d",a[i]);


}





getch();


}








compile and run it :

Question for C programming Dynamically allocate an integer array things with 10 elements.?
to allocate the dynamically memory for 10 integer number by using malloac()and calloc() function
Reply:// The easiest way is right here





void DynmaicAllocOfIntegerArray()


{


const int ArraySize = 10;


int *myArray = malloc(sizeof(int) * ArraySize);





// Do something with your array


myArray[0] = 0;


myArray[1] = 1;


myArray[2] = 2;


myArray[3] = 3;


myArray[4] = 4;


myArray[5] = 5;


myArray[6] = 6;


myArray[7] = 7;


myArray[8] = 8;


myArray[9] = 9;





free(myArray); // Frees your array


}





// Have fun,


// S. B.


Program in c++ to remove duplicates from an array. e.g.if 2 occurs more then once , it should occur only once.

One way to do this, not taking advantage of what C++ gives you, is to simply use an array, e.g. int a[N], sort it, then search for adjacent values that are equal, and remove the duplicates. This is a fairly crude approach, and involves a lot of copying to compress the array when you remove an element. For example:


if a[i] == a[i+1], for j = i+2 to N-1, set a[i+1] = a[j]


When you're done packing the array, adjust the length to account for the deleted values. Of course, if a value is duplicated more than once, with a little extra logic you can delete all the duplicates in one shot, saving some iterations in your loop.





Sorting can be a pain, and using a plain old data array is primitive when you can use C++'s vector%26lt; %26gt; instead. In the example below, I keep the list sorted as it's created, saving the trouble of sorting it later. The way I did that isn't particularly clever, so maybe you can think of a more efficient solution there. After the "array" has been filled, I let vector do the tedious maintenance as I remove duplicate elements. If efficiency isn't your main concern, using vector%26lt; %26gt; is the way to go. If you need to optimize, you may use a plain old data array and do the work yourself. But there's no guarantee your solution would be more efficient than what vector%26lt; %26gt; does for you.





#include %26lt;iostream%26gt;


#include %26lt;vector%26gt;


#include %26lt;cstdio%26gt;





using namespace std;





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


vector%26lt;int%26gt; intVec;


bool done = false;


int x;





cout %26lt;%26lt; "Enter integers for array, 'x' to end :" %26lt;%26lt; endl;


while (!done) {


if (scanf("%d",%26amp;x) == 1) {


// Insert, keeping vector sorted


vector%26lt;int%26gt;::iterator loc = intVec.begin();


while ((loc != intVec.end()) %26amp;%26amp; (*loc %26lt; x)) ++loc;


intVec.insert(loc,x);


} else {


done = true;


}


}





// Remove duplicates


vector%26lt;int%26gt;::iterator iter = intVec.begin();


while (iter != intVec.end()) {


while ((iter+1 != intVec.end()) %26amp;%26amp;


(*iter == *(iter+1))) {


intVec.erase(iter+1);


}


++iter;


}





// Print array


for (vector%26lt;int%26gt;::iterator iter = intVec.begin();


iter != intVec.end(); ++iter) {


cout %26lt;%26lt; *iter %26lt;%26lt; endl;


}


return 0;


}

columbine

How do i find the index of particular element in an array without using loop in c/c++?

You need to look for each element manualy or you have to use recursive function.


Manually as follows


i=0;


if(a[i]==5)


cout%26lt;%26lt;i;


else


i++;


if(a[i]==5)


cout%26lt;%26lt;i;


i++;





and so on


Otherwise you can see example of recursive function at my blog


http://codesbyshariq.blogspot.com

How do i find the index of particular element in an array without using loop in c/c++?
void main()


{


int num[5]={5,4,3,2,1};


int n,i;


cout%26lt;%26lt;"Enter the number whose index is to be found:"


cin%26gt;%26gt;n;


if(num[i]==n)


cout%26lt;%26lt;"The index is:"%26lt;%26lt;i;


else


cout%26lt;%26lt;"Number not in array!"





getch();


}
Reply:if condition..


thats looping right? LOL
Reply:If the size of the array is small, then you can use this type of checking. Pseudo C code.


if a[0] == elem then index = 0


else if a[1] == elem then index = 1


else if a[2] == elem then index = 2


else if a[3] == elem then index = 3


else if a[4] == elem then index = 4


else if a[5] == elem then index = 5


else if a[6] == elem then index = 6


else if a[7] == elem then index = 7


else if a[8] == elem then index = 8


else if a[9] == elem then index = 9


else output "element not found"


For larger arrays, you need a loop to detect when you found the element and store the index of the found element.


Hope this answers your question.


Does anybody know how to dynamically create an array of 1000 doubles in C language?

please help im confused on how to get started

Does anybody know how to dynamically create an array of 1000 doubles in C language?
You can create a pointer of doubles. Another way is to use malloc and calloc.
Reply:double *da = calloc(1000, sizeof(double));


How many solar panels does it take to run an A/C unit? Also, How many batteries in an array?

I was wondering how many 700 W solar panels it would take to run a household A/C unit. Also curious how many batteries it would take to keep A/C running in inhospitable environments. Would a 3500 W inverter be enough if it were to run 220 AC?

How many solar panels does it take to run an A/C unit? Also, How many batteries in an array?
Here we are doing the math of two facts to multiply or divide, to find the third, and you don't give enough to make up the equation!





My 2.5 ton unit needs 220 VAC at 5 KW for the heater coils, and 3.5 KW for the cooling and fans, but, in electricity, we are always having to discriminate between inductive loads (transformers, oven coils, heater coils) and other uses, like lncandescent lighting.





To run my HVAC unit, in my 1,000 square foot home, would demand a10KW unit, and the 5200 watt (5500 watt Surge rated)


would not work. A generator simply stalls out under load, possibly smokes the generator electrics, while a solar unit and batteries can reverse potential under severe load, and explode!


The surge rating for my HVAC unit is 3X higher, (the Switching Load), for either heating or cooling. When figuring out the generator load for an emergency generator, for warranty purposes, they demand we install a generator with a 'surge' power rating triple the start-up load of our equipment, and that is the way to try to load your Solar panel, also!





Now, go to the hardware store, and get a booklet or pamphlet about emergency power generation, and look at the descriptions of the generator start up power capabilities for the 'switching loads'!
Reply:GEE! WHAT KIND OF HVAC WE TALKING ABOUT? 3PHASES--SINGLE PHASE? HOW MANY BTU'S? GAS OR ELECTRIC


VALUES? 3500 WATT INVERTER AT 220VAC? GET A MOTOR-GENERATOR SET! WE NEED MORE INFO FROM YOU TO GET AN ANSWER----BATTERIES IN AN ARRAY? ARRAY FOR WHAT? WHAT VOLTAGE NEEDED? WHAT AMPERAGE NEED TO POWER DEVICE?


In C++ how can I make an array named X which holds MAXSIZE strings?

Another person has asked a similar question, it is answered, with input from me, here:


http://answers.yahoo.com/question/;_ylt=...

carnation

In C language we can write in array like b=3[a]?

No you can't. Because you can't have variable names as numbers but you could have b=a[3] which is the 3rd element of the array a

In C language we can write in array like b=3[a]?
No, variable names cannot be numbers...
Reply:Yes , u can.
Reply:Sure you can write this... You will get the value of a[3] in the variable b. a[3] can be alternatively written as 3[a]. Note that this is valid only for one dimensional arrays. Even it may be compiler specific.
Reply:Surely no because here the variable should be used to store the base address of the array


C: How to parse floats and chars from character array?

I have to take a string in the format "124124N63224E" or "7324S78781W" and put the two numbers into separate floats and the two characters into separate chars using the C programming language. The numbers can be of variable length. How can I do this?

C: How to parse floats and chars from character array?
Look at the sscanf() family of functions in the standard C library.
Reply:http://cppreference.com/stdio/sscanf.htm...


http://www.cplusplus.com/reference/clibr...





Google searching on "man sscanf" also works.


How to convert byte array to string without using any loop ? .net c#?

I alreay did using loop as below





for ( int i =0; i%26lt; mybytearray.Length ; i++)


message = message + (char)mybytearray[i];


in which mybytearray is byte array


and message is string;


but dut to this spead is slows down.





plz help me.

How to convert byte array to string without using any loop ? .net c#?
Try The following Code:


byte [] arrBytes = new byte[10];


System.Text.Encoding.ASCII.GetString(a...





Also you can visit the Link:


http://geekswithblogs.net/timh/archive/2...





I hope this solves your Problem and is Good enough for being the Best Answer ;)
Reply:Thanks Report It

Reply:Thank s a lot. Report It

Reply:Will this help





' VB.NET to convert a string to a byte array


Public Shared Function StrToByteArray(str As String) As Byte()


Dim encoding As New System.Text.ASCIIEncoding()


Return encoding.GetBytes(str)


End Function 'StrToByteArray





// C# to convert a string to a byte array.


public static byte[] StrToByteArray(string str)


{


System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();


return encoding.GetBytes(str);


}





' VB.NET to convert a byte array to a string:


Dim dBytes As Byte() = ...


Dim str As String


Dim enc As New System.Text.ASCIIEncoding()


str = enc.GetString(dBytes)





// C# to convert a byte array to a string.


byte [] dBytes = ...


string str;


System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();


str = enc.GetString(dBytes);


How to declare and define an array in one statement in C#?

In the book I read, it says you can do it like this:





int[] intArray


intArray = int[5]





Isn't there a way to make this in one go, maybe like:





int[5] = intArray











Thanks!

How to declare and define an array in one statement in C#?
int[] intArray


intArray = int[5]





is incorrect. The book says





int[] intArray;


intArray = new int[5];





so to do it in one line:





int [] intArray = new int [5];
Reply:I am really sad to announce that arrays could be used the way he stated please take a look at


http://www.c-sharpcorner.com/U...


http://msdn.microsoft.com/libr... Report It


pansy

How do I return a 2D array from a function in C?

do i need to use pointers/struct in order to make it easier? If possible, a straightforward and simple way would do... thanks!

How do I return a 2D array from a function in C?
You cannot pass an array to a function by value. A pointer is always passed. You can get the same result as pass-by-value by declaring the array as const. Then the called function cannot change any values in the array.





A contrived by hopefully instructive example.





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








void cannotChange1(const int arr[], const int size)


{


int i;





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


{


printf("%d\t", arr[i]);


}





printf("\n");


}








void cannotChange2(const int *arr, const int size)


{


int i;





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


{


printf("%d\t", arr[i]);


}





printf("\n");


}








void canChange1(int arr[], const int size)


{


int i;





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


{


arr[i] = arr[i] * 2;


printf("%d\t", arr[i]);


}





printf("\n");


}





void canChange2(int *arr, const int size)


{


int i;





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


{


arr[i] = arr[i] * 2;


printf("%d\t", arr[i]);


}





printf("\n");


}








int* viaReturn(int *arr, const int size)


{


int i;





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


{


arr[i] = arr[i] * 2;


printf("%d\t", arr[i]);


}





printf("\n");








return(arr);


}








int main(int, char **)


{


int a[3] = {1, 2, 3};


int *b;





cannotChange1(a, sizeof(a) / sizeof(int));


cannotChange2(a, sizeof(a) / sizeof(int));





canChange1(a, sizeof(a) / sizeof(int));


canChange2(a, sizeof(a) / sizeof(int));





b = viaReturn(a, sizeof(a) / sizeof(int));





int i;





for (i = 0; i %26lt; sizeof(a) / sizeof(int); ++i)


{


printf("%d\t", b[i]);


}





printf("\n");


}
Reply:You can always create the 2D array off the heap and then pass the address back to the caller and then have the caller use it for whatever but not to forget to free the space when you are done...





Another alternative is to pass in the 2D array as a parameter into the function (by reference) and then filll it and then just leave the function which would maintain the array's content.





You mentioned you are using "C" and not C++ so unfortunately you dont have the luxury of alias nor the new/delete keywords....





I hope i didn't confuse you....because i am not sure you level of what i am talking about maybe i should explain s'more?





It's been a while since i've looked at C but for your 2D array you can pass it back by allocating memory off the systems heap space by using malloc(..) ... my appologies if C uses a different function for this....it's been a while....C++ is more elegant....so in this example:





int *my2DArray;


malloc(my2DArray,sizeof(int)*10);





This will create a 2D Array that can hold 10 integer values.





so here is what your function would look like:





int* MyFunction(void)


{


int *my2DArray = NULL;


malloc(my2DArray,sizeof(int)*10);





/* Do stuff Here */





return my2DArray;


}








void main()


{


int *myArray=NULL;


myArray = MyFunction();





/* Do whatever here */





free(myArray);





}


Need help in Sorting One Dimensional Array in Ascending Order... TURBO C?

Help please...

Need help in Sorting One Dimensional Array in Ascending Order... TURBO C?
Or else you may contact a C expert live at website like http://askexpert.info/ .
Reply:Um, check the same question you posted maybe ~12 items below this one. 3 Answers so far.


In code C, How can I erase special characters from a char array?

I have this code:





int readConfig(char *IP, int *p, char Myfile[]){


char dir[32];


char pto[32];


char c='a';


FILE *fp;


int i=0;





if((fp=fopen(Myfile,"r"))==NULL){


return -1;


}


while(c!=EOF %26amp;%26amp; c!='\n'){


c=getc(fp);


if(c!=EOF %26amp;%26amp; c!='\n'){


dir[i++]=c;





}


}





i=0;


c='a';





while(c!=EOF %26amp;%26amp; c!='\n'){


c=getc(fp);


if(c!=EOF %26amp;%26amp; c!='\n'){


pto[i++]=c;


}


}





*puerto=atoi(pto);


strcpy(IP, dir);


return 0;


}





and the file contains this information: 255.255.255.255


5555





Well, when I print the IP value, this is the result


IP: 255.255.255.255fhv���





How can I do for fix it??? I want that only print: IP: 255.255.255.255





Thanks!!!!

In code C, How can I erase special characters from a char array?
Cap the string (nul terminate) like so:





while(c!=EOF %26amp;%26amp; c!='\n')


{


c=getc(fp);


if(c!=EOF %26amp;%26amp; c!='\n'){


pto[i++]=c;


}





pto[i]='\0'; //cap it now!





That bad print out you've got is a classic/common result of printing a non nul-terminated string...
Reply:You need to null terminate your strings or write by count (ie. string length)
Reply:memset your variable before filling it


How can we pass a multidimensional array to a function in C?

You pass a pointer to it.


void doStuff(char **pJunk) {


...


}





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


char junk[3][4];





... fill it in





doStuff(junk);





}

How can we pass a multidimensional array to a function in C?
Toadaly's solution doesn't tell how the function would know the array's dimensions...
Reply:#define COLUMN 3





void Dump(int buffer[][COLUMN])


{


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


for(col = 0; col %26lt; COLUMN; col++)


printf ("row: %d\tcol: %d\t%d\n", x, y, buffer[row][col]);


}





int main()


{


int g[5][COLUMN];





/* fill g up */





Dump(g);





return(1);


}

floral centerpieces

In C++ how do you convert an integer to an array of integers?

For example, if the user inputs the value 4637 for "int n", how do i convert that into an array of integers "int * a", where a[0] = 4, a[1] = 6, a[2] = 3, and a[3] = 7 ?





(you can assume "int * a" has been declared a "new int", i realize the length of the array is not known at compile time)

In C++ how do you convert an integer to an array of integers?
its so easy:-


// scan the number


scanf("%d",%26amp;n);


//initialize the array


int a[10];


// i assume the number shouldnt be a large value


k=0;


//for loop


for(int i=1;(n%i)!=0;i=i*10)


{ a[k++]=(n%i);


}


for example if your no is n=4637


then for first pass, n%1 =7 therefore a[o]=7


for second pass, n%10 =3 therefoe a[1]=3


for third pass, n%100 =6 therefoe a[2]=6


for fourth pass, n%1000 =4 therefoe a[3]=4


after this, the for loop ends.
Reply:%26lt;outdated text have been removed%26gt;


Ok, scanf here has nothing with the actual algorythm - it is used only to receive input from user. Just replace it with "cin %26gt;%26gt; n;" or whatever way to receive user input into "n" you like and everything will work as perfect as it was with "scanf".





BTW, as "scanf" itself is not very useful for modern application, its memory version "sscanf" can be a very good choice when you need to parse a string: it allows developer to precisely specify what should be read from the string and in what format. I think that you will not regret if you learn this function and its format strings (at least the most basic ones).


GL.


How can I use list array with no pointer in c++ programming?

please I need help apace


thanks for every one can help me

How can I use list array with no pointer in c++ programming?
u have to ponit it or use





these are the 2 way's:





#include %26lt;iostream%26gt;


using namespcae std;


int main()


{


int num[8];


int index;





num[0] = 42;


num[1] = 2001;


num[2] = 7;


num[3] = 180;


num[4] = 99;


num[5] = 1993;





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


{


std::cout%26lt;%26lt; index[num] %26lt;%26lt; endl;


}


system("pause");


return 0;


}





or





#include %26lt;iostream%26gt;


#define MAX 20


using namespcae std;





int main()


{





int a[MAX] = {23,43,4,5,34,343,12,14};


int b;





cout.setf(ios::right);





for(b = 0; b %26lt; MAX; b++){





cout %26lt;%26lt; endl %26lt;%26lt; endl;





cout %26lt;%26lt; "The Elemnt in ";





cout.width(2);





cout %26lt;%26lt; (b +1) %26lt;%26lt; " is ";





cout.width(2);





std::cout %26lt;%26lt; b[a];


}


return 0;


}
Reply:I dont quite understand the question either. But from what I think your asking...





1) Declare the array





datatype arrayname[listSize];





example





int array1[16]





2) Fill the array with values





either use a for loop, or manually assign values.
Reply:It wouldn't be a list anymore since everything you'll store in it will be static allocated... I don't quite understand your question.
Reply:use the vector class





#include %26lt;vector%26gt;


How do you declare an array in a structure in C?

Is this right?





typedef struct listStruct


{


char word[20];


int counter;





pointer ptr;


} list;

How do you declare an array in a structure in C?
That works. If you don't know how large the array will be, you could also use "char*" (a pointer), and then later use malloc() to get memory for the array (as in "word = (char*)malloc(NumOfCharacters*sizeof(cha... As you have it written, you just need to make sure never to try to put 21 characters in the array. :)
Reply:yes its right 10/10


How do you check if a spot in a char array has a character there or not (C++)?

I'm having problems couting a character array. It couts the list of characters, plus a bunch of junk after it. So then I need to set up a while statement...





bool notChar = false;


int count = 0;


while(notChar = false) {


cout temp[count];


count++;


if(temp[count] == ???) { notChar = true; }


}





...Any ideas?

How do you check if a spot in a char array has a character there or not (C++)?
char* or char[ ] types typically use a char value of 0 to mark the end of the string.





however, "cout" will stop at this 0 automatically, so you obviously do not have a 0 at the end of the string.





the best bet would be to not use a char* or char[ ] type at all, but use a STL::string type. research the C++ standard tempalte libraries. it has a string type with everything built in.





if you must use char* or char[ ], initialize your array to all 0's and never use the final size'd spot. this is clumsy C programming though, not C++. Use the STL in C++, it prevents many bugs.
Reply:look up isalpha





something like





if (!isalpha(int(temp[count])) notChar = true;





can't recall what header file.

wedding florist

How to sort an array of characters (alphabatically) in c++??

use ascii value to perform the sort


the logic is 'a' has lowest ascii value than others

How to sort an array of characters (alphabatically) in c++??
If all the characters are the same case, then I don't believe you have to use the ascii values. You can do a comparison a %26lt; b and it will evaluate to true or false. Then do a bubble sort or whichever sort you prefer.





Here's an example I just did.





#include %26lt;iostream%26gt;


#include %26lt;cstdlib%26gt;


using namespace std;





int main()


{


char chars[] = {'a','d','b','g','e','c','f'};


int size = 7;


char temp;





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


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


{


if(chars[j+1] %26lt; chars[j])


{


temp = chars[j];


chars[j] = chars[j+1];


chars[j+1] = temp;


}


}





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


cout%26lt;%26lt;chars[i] %26lt;%26lt;" ";





return 0;


}
Reply:Read the value from an array and find its ASCII (which is easy try to read a character as integer and it will return an integer vakue which is the character's ASCII value) value and sort it using any Sorting algorithms like Bubble sort, quick sort , Radix Sort , ETC. Once the array is sorted according to the ASCII value - You now just need to read the array as a character array coz the whole array has been automatically alphabetically sorted .


In c++,why should be the size of char array(to store a string) should be one larger than the no of characters?

in c++,why is it necessary to include the null character while storing a string and in c it is not necessary..why..???

In c++,why should be the size of char array(to store a string) should be one larger than the no of characters?
The NULL character is the defined string terminator in C and C++ as used by all string functions in C and the string types in the Standard Template Library (STL) and the Microsoft Foundation Classes (MFC). If you do not account for the NULL character, which practically all string functions expect you to do, you can end up with a lot of problems.





In short, it is a language characteristic that has been around since the very beginning, so it's not something to really question but just do.
Reply:The null character must be accounted for because most of the output functions using character string will stop output on detecting a null character and also string copy functions will stop copying characters upon detecting a null character.


If there was no null character, there is no way to stop the output or copy function.--deepak
Reply:The null character must be accounted for because most of the output functions using character string will stop output on detecting a null character and also string copy functions will stop copying characters upon detecting a null character.


If there was no null character, there is no way to stop the output or copy function.


C++, How do you input into a char array from the keyboard?

i want to input char array using keyboard,and what is the number of char unknown.. can i

C++, How do you input into a char array from the keyboard?
#include %26lt;string%26gt;


#include %26lt;iostream%26gt;





int main()


{


string myStr;


cin %26gt;%26gt; myStr; // use this if you want one word


cin.getline(myStr); //use this if you want one line don't use both


char myCharArray{}=myStr.c_str();


}





/* myCharArray now contains a character array of either one word or one line */


Where i can find an example of turbo c program with the combination of looping,array and conditional?

a turbo c program project

Where i can find an example of turbo c program with the combination of looping,array and conditional?
One of my C programs:





http://freespace.virgin.net/roy.longbott...

local florist

/C++/ How do I use constructors in an array of objects?

Basic question. I have a class Song that has a constructor which defines the instance variables of it (title, artist, size). I want to make an array of Song objects with different constructor parameters for each; how would I do this?





Code snippets:





class Song


{


private:


string title;


string artist;


int size;





public:


Song(string aTitle, string aArtist, int aSize)


{


title = aTitle;


artist = aArtist;


size = aSize;


}











};





And I'm trying to make an array like so : Song songs[9];

/C++/ How do I use constructors in an array of objects?
I thinks in C++, if you need to make an array of objects.. you'll have to do OPERATOR OVERLOADING, which means that you'll have to define the meaning of using "[" and "]" with your new defined class.





This is an explanation of overloading "[]":


http://www.devarticles.com/c/a/Cplusplus...





*If you use C#, it's much easier... if you just wrote:





Song[9] = new Song();





it'll create an array of songs...
Reply:You could try rewriting Song. Add another parameter which is the index of the "songs" array you want to access. And instead of putting just "title = aTitle" you could replace that with " songs[index].title = aTitle ". Same goes for the artist and size. To be more specific:





Song(int index, string aTitle, string aArtist, int aSize)


{


songs[index].title = aTitle;


songs[index].artist = aArtist;


songs[index].size = aSize;


}





The code I did is basically the same. However, I used char instead of string.
Reply:Try this





Song SongArray[9] = { Song("Title One", "Artist One", 1), Song("Title Two", "Artist Two", 2), Song("Title Three", "Artist Three" 3), ...};





Normally, in defining an array the default constructor gets called.





You could also consider using a vector%26lt;Song%26gt;.





Then your code would look like


vector%26lt;Song%26gt; vecSong;





vecSong.push_back(Song("Title One", "Artist One", 1));


vecSong.push_back( Song("Title Two", "Artist Two", 2));


vecSong.push_back(Song("Title Three", "Artist Three" 3));


...


How Could i end my array of char or my strings in c++?

i have a array like this code


for (k=Start ;k%26lt;Start+3;k++)


{ ProcessingCode[k-Start]=FinalMe...


}


ProcessingCode[Start+3]="\n";


And my FinalMessage is so much bigger than Processigcode and i didnt introduce processingcode in dynamic array and i introduce it with processingcode[100] and i want to end of array up to what i fill with data...


but it return me error ,how could i make it? thank you:)

How Could i end my array of char or my strings in c++?
You need to make the final element "NULL" -- and process until you reach the NULL pointer. Let's take for example processing until the end of a char array:





//Create our array


char *aChars;





//Now allocate our array


aChars = new char[25];





//Put values in slots 0, 1 and 2


aChars[0] = 'a';


aChars[1] = 'b';


aChars[2] = 'c';





//Now terminate our array with the special '\0' character


aChars[3] = '\0';





//Now iterate through the array until the end:


int i=0;


while( aChars[i] != '\0' ) {


ProcessData( aChars[i] );


}





-------------





Now, we can apply the exact same logic to an array of character arrays (i.e. an array of strings):





//Create our array pointer


char ** aStrings;





//Now allocate our array of character arrays pointers


aStrings = new char[25]; //up to 25 strings





//Populate as many as we want to -- let's go ahead and only do 3 for testing.


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


aStrings[i] = new char[20]; //Each String is 20 long


}





//Put values in the 3 slots we allocated


strcpy( aStrings[0], "zero" );


strcpy( aStrings[1], "one" );


strcpy( aStrings[2], "two" );





//Now terminate our array with a NULL value


aStrings[3] = NULL;





//Now iterate through the array until the end:


int i=0;


while( aStrings[i] != NULL ) {


//This will process until we hit that null terminator.


ProcessData( aStrings[i] );


}





------





When you are all done processing free the memory you allocated with a call to delete. i.e.:





delete aChars;





In the first example.





Same logic as the examples above work if you use stack allocation and just use aChars[25] instead of allocating the memory on the heap. In that case, just skip the "new" and the "delete" commands.
Reply:do processingcode[3]='/n';


in place of


ProcessingCode[Start+3]="\n";
Reply:Your question is difficult to understand , what error are you getting what is your array size ? You need to give all info. C code is pretty difficult and a small mistake can cause major issues.


Please help me create this program in c++, it requires only the use of array,plz check out the details,tnx?

write a program that will ask for a number it doesn't matter how long its digit, and it will be converted into strings,using array of strings..


something like this


enter number: 1298


string: one thousand two hundred ninety eight


plzz help me with this one,hope u can answer this question,tnx a lot, it will help me alot!

Please help me create this program in c++, it requires only the use of array,plz check out the details,tnx?
To convert the number into a string you should probably use sprintf(). After that I'd used to individual digits to write out the English words. In order to get the denominations (thousand, hundred, million, etc) I'd count the digits. Good luck


How to pass an array(by reference and by address)in C/C++?

Give a program code illustrating the difference between passing an array by reference and by address..

How to pass an array(by reference and by address)in C/C++?
1. In C you pass arrays by reference by default. You pass everything else by value by default.


Passing by reference and passing by address are the same thing. In C, to explicitly pass by reference, when it isn't an array you declare it with:





int Myfunc(int *MyVar);





then in the main() function you call it with:





Success=Myfunc(%26amp;MyVar);





In other words, Myfunc takes a pointer to or address of MyVar (*MyVar) and you actually send it the address (%26amp;) when you call it.





With C++ all you need is that address operator. You declare:





int Myfunc(int %26amp;MyVar);





then in main() you call it with:





Success=Myfunc(MyVar);





But arrays are always passed by references, and that means passed by addresses: They are the same thing.





I'm not citing Kernighan and Ritchie's the C programming language in this answer, our Stroustrup's the C++ programming language but if you don't have them GET THEM.
Reply:Don't listen to Rowell A, Visual Basic is a crap language compared to C++, but enough of the jibber jabber about which language is best.





Array's in C++ are pretty easy to understand once you get the basics down.





For a full explanation of how to pass an array to a function via reference, go to this website: http://www.cplusplus.com/doc/tutorial/ar...





Once you are on that site, scroll down to the section that reads: "Arrays as parameters".








In basis, passing an array to a function is practically the same as passing a variable to a function, but you add the elements of the array (the number inside the brackets ([ ])).








EDIT__________________________________


Very well said jplatt39, i gave you a thumbs up :) I haven't fully gotten up to pointers in my self education of c++, I just got up to building basic structs and dealing with vectors. I haven't gotten passing and whatnot down completely (pointers haven't been learned yet). I will learn them soon though :)
Reply:gudluck with that one. array in c++ that so hard. it's easier on visual basic and other languages but c++ is so old.

floral deliveries

C++ help, urgent please! Use a one dimensional array to solve the following problem. Read in 20 numbers, each?

Use a one dimensional array to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, validate it and store it in the array only if it is not a duplicate of a number already read. After reading all the values, display only the unique values that the user entered. Provide for the worst case in which all 20 numbers are different. Use the smallest possible array to solve this problem.

C++ help, urgent please! Use a one dimensional array to solve the following problem. Read in 20 numbers, each?
int array[20], input, a_pos, b_pos;





a_pos = 0; // Array position


b_pos = 0;





do{


cin%26gt;%26gt; input; // Take the user input





/*if input is greater than 10 %26amp; less than 100*/


if(input!%26gt;10%26amp;%26amp;!%26lt;100){


array[a_pos] = input;


a_pos +=1;


}





}while(a_pos!=19);





/*


If you can't figure it out from here .... go away


Just put in the duplicate number checking!!!


Which will be another loop that loops n times, n being a_pos+1.


*/
Reply:It would help if you rephrased in the form of a question. What are you having difficulty with? This is not a place to have you homework done for you, but you will get help if you try doing it, get stuck and then ask about what your stuck on.
Reply:/* This is the only time I will do your homework for you. In the future, in order to get a response from me, you must first provide your own attempt at the source code and ask specific questions about where you are stuck. I wrote this entirely in the main function and did not provide any comments. OK? */








#include %26lt;iostream%26gt;


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





void main()


{


int x[20];


int i, j, k, temp;


char match = 'F';





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


{


cout %26lt;%26lt; "Enter an integer between 10 %26amp; 100: ";


cin %26gt;%26gt; temp;


while (temp%26lt;10 || temp%26gt;100)


{


cout %26lt;%26lt; "Re-enter an integer between 10 %26amp; 100: ";


cin %26gt;%26gt; temp;


}





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


if (temp == x[j]) match = 'T';





if (match == 'F') x[i] = temp;


else x[i] = -1;





match = 'F';


}





cout %26lt;%26lt; '\n';


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


if (x[k] != -1) cout %26lt;%26lt; x[k] %26lt;%26lt; ' ';





getche();


}
Reply:int a[20],i,j,x,flag=0,store=0;


// to get value


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


{


cin%26gt;%26gt;x;


if(x%26gt;=10 %26amp;%26amp; x%26lt;=100)


{


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


{ if(x==a[j])


{ flag=1;break;}


}


if(flag!=1)


{


a[i]=x;


store=i; /*contains latest postion in the array which contains some value*/


}


}


else


{ cout%26lt;%26lt;"number should b b/w 10 %26amp; 100,...enter again";


i--;


}


}


//print d values of array a which contyains only d unique values


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


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


Plze give me the code of a game in C/C++ in which structures or array are used....plze send me code...!!!!!!!

WaW dude. You need to pay more attention in class.





Data Structures


http://www.cplusplus.com/doc/tutorial/st...





Arrays


http://www.cplusplus.com/doc/tutorial/ar...





Read to understand.


And learn.





- Hex A.k.a. Void

Plze give me the code of a game in C/C++ in which structures or array are used....plze send me code...!!!!!!!
visit planet-source-code.com, they will provide you thousands of C/C++ n VB6.0/Vb.net 's source codez.. but keep in mind that u can only download 5 from da site (then u might need 2 register which is free)...


C program to record stored information from an array, and print out stored information.?

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





struct tele { // Struct with 2 fields for phone numbers.


char home [20]; // Holds phone numbers in an array of characters.


char mobile [20];


};





typedef struct student { //Typedef struct to hold- names [characters]


char firstname [20]; // - id and average [intergers]


char lastname [20];


int id;


float avg;


struct tele phone; //Nested struct. The struct 'tele' is called 'phone'


// and its holds both home and mobile numbers.


} data; // New type





void main ()


{


int j; //Declared interger 'j'.


data rec [10]; //Typedef struct data- decleared array 'rec' that can hold 10 'student'.


data stdinfo;


struct tele call; //'call' declared as a struct.





for(j=0;j%26lt;2;j++){ //For loop used to get infomation for array -loops twice-.





printf("Enter First Name\n"); //Scans for First Name and it is put


scanf("%s", stdinfo.firstname); //into 'fname' in struct 'person'.





printf("\nEnter Last Name\n"); //Scans for Last Name and it is put


scanf("%s", stdinfo.lastname); //into 'lname' in struct 'person'.





printf("\nEnter Home Phone Number\n"); //Scans for Home Phone Number and it is put


scanf("%s", call.home); //into 'home' in struct 'call'.





printf("\nEnter Mobile Phone Number\n"); //Scans for Mobile Phone Number and it is put


scanf("%s", call.mobile); //into 'mobile' in struct 'call'.





printf("\nEnter ID Number\n"); //Scans for ID Number and it is put


scanf("%d", %26amp;stdinfo.id); //into 'id' in struct 'person'.





printf("\nEnter Average\n"); //Scans for average and it is put


scanf("%f", %26amp;stdinfo.avg); //into 'avg' in struct 'person'.





stdinfo.phone=call; //All information in struct 'comm' is put into 'ph' field in 'person'





printf("\n\nName- %s %s\n",stdinfo.fname,stdinfo.lname); //Pr... collected information


printf("ID # %d\n",stdinfo.id); //from structs.


printf("Average %.2f\n",stdinfo.avg);


printf("Home Phone # %s\n",stdinfo.phone.home);


printf("Mobile Phone # %s\n\n\n",stdinfo.phone.mobile);





rec [j] = stdinfo;//all information is put into the array of records





} //For loop ends








j=0;


for (j=0;j%26lt;2;j++){ //For loop used for printing information.





printf("\n\n**************************...


//Printing directly from the array of records


printf("Information at array location %d is:\n\n",j);


printf("Name- %s %s\n",rec[j].fname,rec[j].lname);


printf("ID # %d\n",rec[j].id);


printf("Average %.2f\n",rec[j].avg);


printf("Home Phone # %s\n",rec[j].phone.home);


printf("Mobile Phone # %s\n\n",rec[j].phone.mobile);





} //For loop ends





} //END

C program to record stored information from an array, and print out stored information.?
hey ur code looks fine. .wats ur ques?


jj


Creating an array of structures within another strucure in C.?

i have an assignment that involves creating a Graph ADT. within this i need to have an array of Lists.





my List ADT is basically a doubly linked list with certain functionality. to create a new you call the function:





ListRef newList();





NOTE: ListRef is defined as "typedef struct List* ListRef". i.e., its just a handle/pointer to a List structure.





the problem is that you don't know the size of the graph until run time since you create a new one with the function:





GraphRef newGraph( int n );





where n is the number of vertexes in the graph (and thus the size of the array of List ADTs) and a GraphRef is just a pointer to a Graph structure.





i'm trying to do something like this:





struct Graph{


.


.


ListRef* list_array;


.


.


}





GraphRef newGraph( int n ){


GraphRef G = malloc(sizeof(Graph));


ListRef L[n];


.


.


for( i=0; i%26lt;n; ++i){


L[i] = newList();


}


G-%26gt;list_array = L;


.


.


}





But this results in no Lists being created (they are NULL) and then a core dump. what is wrong?

Creating an array of structures within another strucure in C.?
I think that the problem is that your ListRef array is being defined on the stack in the function newGraph(int n).





Once the function scope is over, G-%26gt;list_array will be pointing to a location that it doesn't own, and the first operation that it performs on it will cause a core dump.





What you need to do instead is to create your G-%26gt;list_array using malloc:





G-%26gt;list_array = (ListRef)malloc(n*sizeof(ListRef));





and then continue as before.





Hope this helps.





P.S. Interesting problem by the way :).

buy flowers