Monday, May 24, 2010

Can someone help me with writing this C program?

I need to make a program that does the following :





1) Prompt for and then accept 10 floating point values from the


user.


2) Store these values in an array.


%26lt;I completed steps 1 and 2 %26gt;


3) Pass the array to a procedure which prints out the values to


4 decimal places in a numbered fashion (i.e like line numbers).


4) Pass the array to a function which returns the maximum value.


5) The returned maximum value is printed out in scientific or


exponential format along with a suitable heading.





I haven't leanred anything on procedures or functions , so I'm stuck on step 3. Can someone please show me how to do this ?

Can someone help me with writing this C program?
hey has your teacher given you any assignment ???
Reply:I would really suggest you post questions like this on a C forum . You will most likely get a better answer there.





http://www.codeguru.com/forum/forumdispl...
Reply:Or else you may contact a C expert at websites like http://askexpert.info/ to help you code your project assignment.


C# change array of strings into one string.?

Hi, in the software I'm developing (nothing professional, just as a hobby, I'm only 16), I have an array of strings, and sometimes the array can be as large as 1 million. Each string in the array holds 10 characters. At the moment the program has to work through the array like this:


string total = null;


int x = 0;


while (x %26lt; myArray.Length)


{


total = total + myArray[x];


x++;


}





This takes upto half an hour with my processor (it's a 3.0GHz dual core, but I realise only one core is being used).





Is there a quicker way to do what I'm doing? If so, how?





Thanks, Thomas





BTW if you want to try the software, it can be found here:





www.wormalds.co.uk/ThomasWormaldEncryp...

C# change array of strings into one string.?
Well, I don't know of any shortcut method to what you're doing. Maybe this setup might run faster, but then again, maybe not.





string[] what = {"So", " what", " if", " I", " have", " this?"};





string newAns = null;





foreach(string ans in what)


newAns += ans;





If this doesn't work out to be any better, then its time to use threads. You mentioned that only one core is being used. You could break up the task and do some of the work in different threads. However, you'd have synchronize the efforts and merge everything back into once string at the end, so you'll have to wait for each thread to complete its task.
Reply:Why the hell would you have an an array of one million strings? What possible practical use does that have?


How can i make one c++ program read the virtual memory of another?

This is my problem...i need to use 2 matrixes, for fast information channels...in my algorithm. I can declare one of them in a program. If i declare both, then the program crashed (apparently due to some windows xp mem limit per program. When i declare 1 matrix in one program, but another in another program, and try to run both...i just get an error message saying that my page file is too small...so if i run this on a better computer, i'd be able to declare both matricies at once from two places. Now, i need to make the first program communicate with the second.


I want the first program to declare a matrix/array...get the memory address for the first element of the array, and length, and send that info through a text file to the other program...that would then take that number...load it into a pointer, and view the matrix without declaration. But this isn't working, why not?

How can i make one c++ program read the virtual memory of another?
There are a few ways that shared data can happen.





- create a RAM drive that has fast access. Then use both programs to open the same file. This is a GET IT DONE method.





- my second suggestion is what you have tried. But here is what might be wrong. Both programs have to be compiled, using the same compiler options. As I recall, if you use a LARGE scale object option, the pointers might work out universally. (the type of computer is not relavant).





- The other option is to install an ODBC text file or other global data structure. This could be an awesome and transportable method that would work on countless Windows computers of different flavors and environments. (Yet, I could not even begin to describe the programming details).





Good luck
Reply:I don't think you can just access shared memory on a whim, each modern program loads onto a computer in a separate memory space, the only way to communicate is through API calls, and memory addresses shouldn't be passed in them.





The other way is piping one program output into a master program but that is not going to solve your problem; in other words, without declaration is unlikely.


How can i make one c++ program read the virtual memory of another?

This is my problem...i need to use 2 matrixes, for fast information channels...in my algorithm. I can declare one of them in a program. If i declare both, then the program crashed (apparently due to some windows xp mem limit per program. When i declare 1 matrix in one program, but another in another program, and try to run both...i just get an error message saying that my page file is too small...so if i run this on a better computer, i'd be able to declare both matricies at once from two places. Now, i need to make the first program communicate with the second.


I want the first program to declare a matrix/array...get the memory address for the first element of the array, and length, and send that info through a text file to the other program...that would then take that number...load it into a pointer, and view the matrix without declaration. But this isn't working, why not?

How can i make one c++ program read the virtual memory of another?
There are a few ways that shared data can happen.





- create a RAM drive that has fast access. Then use both programs to open the same file. This is a GET IT DONE method.





- my second suggestion is what you have tried. But here is what might be wrong. Both programs have to be compiled, using the same compiler options. As I recall, if you use a LARGE scale object option, the pointers might work out universally. (the type of computer is not relavant).





- The other option is to install an ODBC text file or other global data structure. This could be an awesome and transportable method that would work on countless Windows computers of different flavors and environments. (Yet, I could not even begin to describe the programming details).





Good luck
Reply:I don't think you can just access shared memory on a whim, each modern program loads onto a computer in a separate memory space, the only way to communicate is through API calls, and memory addresses shouldn't be passed in them.





The other way is piping one program output into a master program but that is not going to solve your problem; in other words, without declaration is unlikely.

anther

How to make an array using pointers in C++?

#include "stdafx.h"


#include %26lt;iostream%26gt;


using namespace std;





void print (int* a, int* b, int arraySize) {


int* aPtr;


int* bPtr;


int i;





cout %26lt;%26lt; "The values:" %26lt;%26lt; endl;


for (i = 0, aPtr = a, bPtr = b; i %26lt; arraySize;


cout %26lt;%26lt; "A[" %26lt;%26lt; i %26lt;%26lt; "]: " %26lt;%26lt; *(aPtr++) %26lt;%26lt; endl,


cout %26lt;%26lt; "B[" %26lt;%26lt; i %26lt;%26lt; "]: " %26lt;%26lt; *(bPtr++) %26lt;%26lt; endl, i++);


}





int main() {


const int arraySize = 10;


int* a = new int[arraySize];


int* b = new int[arraySize];


int* aPtr;


int* bPtr;


int i;





// initialise


for (i = 0, aPtr = a, bPtr = b; i %26lt; arraySize; *(aPtr++) = 1, *(bPtr++) = 2, i++);





// print


print(a, b, arraySize);





// copy


for (i = 0, aPtr = a, bPtr = b; i %26lt; arraySize; *(aPtr++) = *(bPtr++), i++);





// print


print(a, b, arraySize);


}

How to make an array using pointers in C++?
void main()


{


int i;





int *ar[10];





int num[10];





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


{





ar[i]=%26amp;(num[i]);


}





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


{


cout%26lt;%26lt; *(ar[i]);


}


getch();


}
Reply:try this link





http://www.intap.net/~drw/cpp/
Reply:array a[15]


a[0]=9;


a[0]-%26gt;next=a[1]=4;


......


you have to define next before you use it as global variable


These are all true/false questions for C programming?

1. The preprocessor directive #define RING 1 tells the C preprocessor to replace each occurrence of the constant RING with 1.





2. The fourth element of an array named bob is bob[4]





3. All arrays with 10 elements require the same amount of memory.





4. A function with return type void always returns the value 0.





5. A function prototype tells the compiler nothing about the value that is returned by the function.





6. When an array is passed to a function, the address of the array is passed to the function and a copy of the elements is made for the function to manipulate.

These are all true/false questions for C programming?
Good luck doing your own homework!





(And neither of the two answerers below is 100% right, btw.)


 


 


 


 
Reply:1). true


2). false


3). true


4). false


5). true


6). false.


Ok now you won't learn anything from these true/false answers...
Reply:Why can't you do your own homework?
Reply:1 t


2 f


3 t


4 t


5 f


6 t


C#??structured array??

can you give me a sample of a structured array,, and how to access its elements?? im not sure if im doing it right but when i compile i get errors


public struct stud


{


public string fname;


public string lname;


}





my question is....where should i place the array??? need help please........

C#??structured array??
A struct doesn't stand for structured array, they're two different things. If you want to use a struct, just put it anywhere in the class alongside your methods.





@Jordan Z





An array is ALWAYS limited in memory, which is why it has such fast lookups. You must define a type and size before you allocate an array, no matter what the language. Some languages just do better than others at hiding this from you (ex. ArrayList copies the array to a new one somewhere else, then deletes the original).


How many black and how many red counters are there in a triangular array like this but with 20 rows?

A: How many black and how many red counters are there in a triangular array like this but with 20 rows?





 - Black


 -Red


 -Black


 -Red


 -Black





You should not actually need to make a diagram with 20 rows in order to answer this question.





B: Write a brief explanation of your solution to part (a).





C: Repeat part (a) but with a triangular array with 21 rows.





D: What integers are represented by the triangular arrays in parts (a) and (c)?





E: Make a table of integers represented by triangular arrays like those in parts (a) and (c), but with n rows for n=1, 2, 3, 4, 5, 6, 7, and 8.





F: Carefully considering the table of part (e), conjecture what integer is represented in a triangular array like those in parts (a) and (c), but with n rows, where n is any natural number (Suggestion: Consider n odd and n even separately.)

How many black and how many red counters are there in a triangular array like this but with 20 rows?
use arithmatic progression formula n(2a+(n-1)d)/2


where n=no. of terms. a=value of first term and d=common difference between each consecutive term


say fro your first eg. no. of black ball = 1+3+5+...


n=10 a=1 d=2


so sum = 10(2+9*2)/2 = 100


solve the rest by changing values of n, a and other variables respectively
Reply:Whoa...this is really confusing. No idea

tomato plants

C++ Programming (array and string)?

Can someone do this code for me, i apperciate if the code is complete and ready to built and execute; this are the instruction:





Write a program that asked the user to enter a string. Then the program should ask the user to enter a letter. The program should serach for that letter in the string the user entered and REMOVE it from the string.





For example if the user enter: This is the string test


The enters the letter T


The program should print out: his is he sring es





Make the input/output "Friendly" Tell the user what the program will do and so on...





A few important things:


-Declare the array for the string at least 50 chars long


-Use #define for the array sizes


-USE FUNCTIONS, use at least one function. I used one funstion that took the string the user entered, an array to store the new string and the char. The prototype loked like this :


void remove_char ( char * string, char * newstr, char ltr);

C++ Programming (array and string)?
its a suggestion


never order other to do sth


better request or ask politely


and be happy with wat they give ya
Reply:Are you testing us or asking for help??
Reply:please do it when you get strunded then let me know


Please help me to write a c program accept n-input " thoes No is an array elements "?

Write C program which has a function that compute the sum of n number


Note: the n number is the values of array elements.

Please help me to write a c program accept n-input " thoes No is an array elements "?
use for(i=0;i%26lt;n;i++) sum=sum+i;


How to display a 2 dimensional array in columns using C?

To display a table, simply use column and row variables, display each column, and then issue a printf("\n");





To make your columns a fixed length, for example 4, instead of doing a "%d" in the format string do a %4d". If you are doing floats and want say 5 figures of whole numbers and 2 decimal places, "%5.2f".





In other words this is very straightforward.

How to display a 2 dimensional array in columns using C?
for(i=0;i%26lt;rows;i++)


{


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


{


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


}


printf("\n");


}


C struct array question?

I have an array of structures:


struct city cities[100];





I want to place two "instances" of that struct array into a method that computes a distance:





double compute_distance(city cities[] x, city cities[] y) {





/* some code here */





}








This method is wrong. How do I get it to work?

C struct array question?
If you want to pass two arrays to the function, then change the following line:


double compute_distance(city cities[] x, city cities[] y)





To:


double compute_distance(struct city x[ ], struct city y[ ])








If you want to pass two instanses to the function change the previous line to:





double compute_distance(struct city x, struct city y)





To call the function within main, all you have to do is the following:





double distance = 0.0;


int a = 0; // change this to the index of the 1st. city


int b = 0; // change this to the index of the 2nd city


distance = compute_distance(cities[ a ], cities[ b ]);
Reply:Hi,





You have one array, with 100 "instances" of the city struct in it, so I think you mean that you want to call the compute_distance function with two cities from the array. You could do this just making the parameters of type "struct city", but that would make a copy of each city for the procedure - with two side effects:


1) If you make changes to either city inside the function, they're not made to the copies in the array, and


2) It takes time and memory to make copies.





So I recommend using pointers as the parameters, like this:





double compute_distance(struct city * x, struct city * y)


{


/* some code here */


}





Then you use x-%26gt;some_field style syntax inside the function.





Call the function using the %26amp; operator to get a pointer to a certain city. For example, to call compute_distance with the 5th and 8th cities:





distance = compute_distance(%26amp;cities[4], %26amp;cities[7]);





Good luck!

petal

What is the dev c++ formula that declares an array of 20 integers. Accept a number to determine the.........?

what is the dev c++ formula that declares an array of 20 integers. Accept a number to determine the number of 0 or 1 inputs(binary digits). Display decimal value using the output format:





Enter size: 4


1


0


1


1


Equivalent: 11


1x8=8


0x4=0


1x2=2


1x1=1

What is the dev c++ formula that declares an array of 20 integers. Accept a number to determine the.........?
Hello Edrew !!





Here is your solution:








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


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


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





void main()


{


int num[20]={0};


int total,i;


double sum=0;


clrscr();


cout%26lt;%26lt;"How many digits do you wish to Enter : ";


cin%26gt;%26gt;total;





if(total%26gt;0 %26amp;%26amp; total%26lt;=20)


{


cout%26lt;%26lt;endl%26lt;%26lt;"Please Enter "%26lt;%26lt;total%26lt;%26lt;" digits : "%26lt;%26lt;endl;


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


{


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


}








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


{


sum=sum + num[i]*pow(2,total-i-1);


cout%26lt;%26lt;endl%26lt;%26lt;num[i] %26lt;%26lt;"*"%26lt;%26lt;pow(2,total-i-1)%26lt;%26lt;"="%26lt;%26lt;num[i]*pow...


}


cout%26lt;%26lt;endl%26lt;%26lt;endl%26lt;%26lt;"Equivalent is : "%26lt;%26lt;sum;


}


else


cout%26lt;%26lt;"Please Enter value between 0 and 20..";





getch();


}
Reply:Try searching the net for C++ tutorials and resources
Reply:Try searching the net for C++ tutorials and resources. It's worth bearing in mind that Dev C++ is an editor, not a language - the languages it edits are C or C++.


C program to delete duplicate elements in an array?

i want a simple c code to delete duplicate elements in an array

C program to delete duplicate elements in an array?
http://www.google.com/codesearch?q=array...
Reply:assuming your array is x with n elements.





i=0;


while (i%26lt;n-1)


{


j=i+1;


while(j%26lt;n)


{


if (x[i]==x[j])


{


for (int k=j; k%26lt;n-1; k++)


x[k]=x[k+1];





n--


}


j++;


}


i++;


}


How do I remove multiple spaces from a cstring (character string) in c++?

For example


If I have a two dimmensional character array string: songdata[x][y]. and it contains the characters "the great escape". How do I manipulate it to make it look like:


"the great escape"





I just want to remove spaces where there are multiple spaces, but not remove all of the spaces.

How do I remove multiple spaces from a cstring (character string) in c++?
Seasoned programmers will want to howl at me on this code because we're building the replacement string into the same buffer (songlist[x][y]) as the source buffer--(not using a temporary buffer)....generally a bad practice.





However, this code works (and is extremely efficient) because--in this instance--the resulting string is guaranteed to be the same len, or shorter, than the source string. A little thought on this will prove it out.





Best wishes,





_g








void strip_excess_space(int songlist_count)


{


int x=0, y=0, z=0;


int done=0;


int ch, lastCh=' ';





while(!done)


{


ch = songdata[x][y++];


switch(ch)


{


case ' ': //a space?


if(lastCh != ch) //if last character wasn't a space...


songdata[x][z++] = ch; //permit it.


break;





case '\0': //end of string


songdata[x][z++] = ch;


x++; //go to next name in songlist


z=y=0; //...and beginning of buffers


//check for end


if(x %26gt;= songlist_count)


done = 1;


break;





default:


songdata[x][z++] = ch;


break;


}


lastCh =ch;


}


}


C++ dynamic array function help?

Write a program that will keep track of the enrollment of one class. Use a dynamic array to keep track of the enrollment. When enrolling a new student, the dynamic array will increase by one. You must use a function call to add student. I have been working on this problem all day and my code just does not work. My teacher said we do not need to use vector to increase the array size so any tips on how to solve this problem would be great because I just keep hitting a dead end.

C++ dynamic array function help?
C++ does not have any native "dynamic array" capability. The closest thing would be the use of the ANSI realloc() function, but that's a C thing, and not special to C++.


Now you *could* write your own class that manages an array. Let's say your class is something like this:





class Array {


a_class *m_array;


size_t m_nCurrentArraySize;


void Resize(size_t nNewSize);


...


};





Then your implementation might looks like this





void Array::Resize(size_t nNewSize) {


a_class *pNewArray = new a_class[nNewSize];


for (size_t i = 0; i %26lt; m_nCurrentArraySize; i++)


pNewArray[i] = m_array[i];


m_nCurrentArraySize = nNewSize;


delete [] m_array;


m_array = pNewArray;


}
Reply:You can use a linked list for this type of operation but your teacher wanted you to use 'dynamic' arrays. Nothing like making things more difficult.





one_student is assumed to be a structure.


student_class is assumed to be a dynamic array of one_student.





class MyClassArray


{


public:


MyClassArray() {student_enrol = NULL; student_count = 0;}


void AddStudent(one_student %26amp;student);


private:


typedef one_student *student_array;


student_array student_enrol;


int student_count;


...


};





MyClassArray::AddStudent(one_student %26amp;student)


{


student_class temp = new one_student[student_count+1];


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


temp[i] = student_enrol[i];


temp[student_count++] = student;


delete student_enrol;


student_enrol = temp;


}
Reply:It might be useful for you to paste the code you've got, and tell us specifically what error you're seeing.

garden sheds

Char array to string???? c#?

is there a method that does this?





'c','a','t'


i want to be be cat

Char array to string???? c#?
char[] cArray = { 'c', 'a', 't' };


string sCat = new string(cArray);
Reply:try this:





string cat=new string(yourCharArrayHere);


Can anyone help me write this program in C?

You are given two int variables j and k , an int array zipcodeList that has been declared and initialized, an int variable nZips that contains the number of elements in zipcodeList , and an int variable duplicates .





Write some code that assigns 1 to duplicates if any two elements in the array have the same value, and that assigns 0 to duplicates otherwise.


Use only j , k , zipcodeList , nZips , and duplicates .

Can anyone help me write this program in C?
Here you go:








duplicates = 0;





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


{





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


{


if(zipcodeList[j] == zipcodeList[k])


{


duplicates = 1;


break;


}


}





if(duplicates == 1)


break;


}


}
Reply:you need to create a loop that will go from 0 to nZips-1(the reason is that stacks start with 0). For this loop use varable i.


Then make another loop inside it(nested loop) similar to the first one. For this second loop use variable j. Then use the following if statement:


if(zipcodeList[i] == zipcodeList[j]){duplicates = 1;}





That should do it.


Dynamic Array Question in C++?

Write a program using dynamic arrays that asks the user for the number of candidates in a local election, and then creates the appropriate ar rays to hold the data. The program then asks the user to enter the last name of each candidate and the number of votes received by her/him. The program then outputs each candidate’s last name, the number of votes received and the percentage of the total votes received by the candidate. Finally, it also outputs the winner of the election.

Dynamic Array Question in C++?
class CCandidate


{


private:


char * m_szLastName;


int m_iNumVotes;


double m_dPercentVotes;





public:


CCandidate()


{


m_szLastName = NULL;


m_iNumVotes = 0;


m_dPercentVotes = 0;


};





CCandidate( char * szName, int iVotes )


{


setValues( szName, iVotes );


};





void setValues( char * szName, int iVotes )


{


m_szLastName = new char[ strlen( szName ) + 1 ];


strcpy( m_szLastName, szName );


m_iNumVotes = iVotes;


m_dPercentVotes= 0;


};





void setPercent( int iTotalVotes )


{


m_dPercentVotes = ( double ) ( m_iNumVotes * 100 ) / ( double ) iTotalVotes;


}





void printDetails()


{


printf( "Candidate %s: Total Votes Received is %d, percent votes received is %.02f\n\n", m_szLastName, m_iNumVotes, m_dPercentVotes );


}





void printWinnerMessage()


{


printf( "Candidate %s, with %.02f percent votes, wins!\n\n", m_szLastName, m_dPercentVotes );


}





~CCandidate()


{


if( m_szLastName != NULL )


{


delete [] m_szLastName;


m_szLastName = NULL;


}


};


};





int _tmain(int argc, _TCHAR* argv[])


{


char szTemp[ 256 ];


int iNumCandidates = 0, iVote = 0, iTotalVotes = 0, iWinnerIndex = 0, iMaxVotes = 0;


printf( "Please enter the number of candidates: " );


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


printf( "\n" );





CCandidate * arrayCandidates = new CCandidate[ iNumCandidates ];


for( int iCnt = 0; iCnt %26lt; iNumCandidates; iCnt++ )


{


printf( "For Candidate Number %d, type last Name:\n", iCnt + 1 );


scanf( "%s", szTemp );


printf( "How many votes did %s get?\n", szTemp );


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


iTotalVotes += iVote;


if( iVote %26gt; iMaxVotes )


{


iMaxVotes = iVote;


iWinnerIndex = iCnt;


}





arrayCandidates[ iCnt ].setValues( szTemp, iVote );


}





for( int iCnt = 0; iCnt %26lt; iNumCandidates; iCnt++ )


arrayCandidates[ iCnt ].setPercent( iTotalVotes );





printf( "\n\nNow for the results:\n\n" );


for( int iCnt = 0; iCnt %26lt; iNumCandidates; iCnt++ )


arrayCandidates[ iCnt ].printDetails();





printf( "And the winner is...\n" );


arrayCandidates[ iWinnerIndex ].printWinnerMessage();





delete [] arrayCandidates;


arrayCandidates = NULL;





printf( "\nPress a few enters to quit!" );


getc( stdin );


getc( stdin );


return 0;


}





======================================...


DISCLAIMERS:


(a) Code does not handle the case where user enters multiple winners, i.e., more than one candidate has the highest number of votes - do it yourself.





(b) Code does not handle the case where multiple candidates have same last names. Right now, they are undistinguishable. To resolve this, you have to add a "number" feature being printed - do it yourself.





(c) Code will need some #include headers to compile. stdio.h, stdlib.h, iostream.h etc basic ones I can think of. The getc() at the end I think needs ctype.h. Resolve such errors youself.
Reply:If you pay me 50 dollars.


How to use modulus division % in a C program??????

thr is a program given to me, where the user have to first enter a five digit number then its output will be the sum of those five digit number e.g. 12345 =15(o/p)


using modular division (%),,,,,,,,,,,


pls tell me the code in C..........


iam confused b'coz using array is not permitable...........

How to use modulus division % in a C program??????
#include %26lt;stdio.h%26gt;


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


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





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


{


// Add your method for inputting a value here.


int some_number = 12345;


//


int total = 0;


int index = 0;





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


total += some_number % 10;


some_number = floor( some_number/10);


}





printf( "The sum is %d", total);


}

garden design

Array in Turbo C?

pls help me how to get this output in turbo C...





ull be able to input a number for ex. 5 its output is


5 4 3 2 1


4 3 2 1


3 2 1


2 1


1


tnx in advance...

Array in Turbo C?
Pseudo-code that might get you going:





Set x to entered value.


for i = x downto 1 {


for j = i downto 1 {


print j


}


print newline.


}


Write a simple C/C++ program which defines an array of five elements, then using pointer to display the addres

Write a simple C/C++ program which defines an array of five elements, then using pointer to display the addresses of all elements of the array.

Write a simple C/C++ program which defines an array of five elements, then using pointer to display the addres
#include %26lt;iostream%26gt;





using namespace std;





int main()


{


int array[5];


int* pointer = NULL;





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


{


pointer = %26amp;array[i];


cout %26lt;%26lt; "The address of element (" %26lt;%26lt; i + 1 %26lt;%26lt; ") is: ";


cout %26lt;%26lt; %26amp;(*pointer);


}


return 0;


}





// you can also do it without using a pointer as follows:





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


{


cout %26lt;%26lt; "The address of element (" %26lt;%26lt; i + 1 %26lt;%26lt; ") is: ";


cout %26lt;%26lt; %26amp;array[i];


}
Reply://C//or//C++


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


Start


Define: /Array


Elements: /5


Now use:


What?


pointer to address the F* display


what for?


elements of the display?


how many?


5!!!


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


end
Reply:Any other help me to solve that Question
Reply:/* Tolga's C code */





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


int main(){


int i=0, arr[5];





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


printf("Address of the element #%d is %p\n",i,(arr+i));


return 0;}
Reply:dude, that's not even a program. that's like 5 lines of code, if even.
Reply:#include%26lt;iostream.h%26gt;


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





int main(){


int *p;


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





p = a; //simple assignment





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


cout%26lt;%26lt;(p+i);





return 0;


}
Reply:Do your own homework
Reply:Why dont you try your own Mind to Answer your Assignments, you are just sitting in your Campus to ask people to do Assignments for you, hmmmm








Very Bad Hafsa, Very Bad
Reply:/*-------hi dude: try this :its 100% right---------*/


/*-------it really takes something to learn pointers in c---*/


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


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


void main()


{


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


int *i;


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


{


printf("\t%d",*(a+i));


}


getch();


}


How do you implement an array class in c++ that solves the index out of bounds problem?

There are a few ways to do this, depending on the behavior you want. You can make a class that contains the array (constructor will take the size of the array). Then you implement/overload all the operators you are interested in. In these operators, you can overload [] to cause the index to wrap (if the size of the array was 10 and you did [10] you would get the 0'th element. Or you could have [10] return [9] element all the time. With templates:





template%26lt;class T, int n%26gt; class Array{





public:


T%26amp; operator[](int i) {


int j = i;


if(i %26lt; 0){


j = 0;


}


if(i %26gt; n - 1){


j = n - 1;


}





return data[j];}





private:


T data[n];


};





or something like that.

How do you implement an array class in c++ that solves the index out of bounds problem?
RTFM
Reply:search for RTFM at http://www.searchdub.com
Reply:The short answer, implement the operator[] operator. The long answer, get a good book on C++.





I think a better question is why does odysseus2i have the exact same avatar as you?
Reply:Chaeck in the sources class from MFC and you can find the sources of CArray.


it is very powerfull and reusable; just copy and paste and make little modification to use it in standard C++ (I used it in Borland C++ 3.1 for DOS)


C programming array question?

Here's a sample of a program:





char cur[6][20]={"Euro ", "YEN ", "Franc", "ZWD", "DOP", "Exit"}; //five currencies types plus exit option (6)


float rates[5] ={1.3859, 114.9750, 0.8424, 0.00003333, 0.02988}; // five (5)exchange rates








What would the (20) relate to if we are doing currency conversion? Why should the number (20) be used in this example if the conversion is hard-coded why not any other number?

C programming array question?
The cur[6] relate to the five currency options (+Exit) in the array, and [20] is the size of the string in each of the arrays, so the longest currency /option name is "Franc" that is at cur[2]. So there is a 'wasted space' for minimum 14 bytes (1 byte required for string terminating null character \x0) for each array from [0] to [6].


Therefore your declaration may be like char cur[6][6] = {"Euro".......};
Reply:u can use 6 in place of 20 try it


20 is used for length of maximun characters in char variable
Reply:Hi,


Of course, 20 is the maximum length of the string that can be stored in cur[6][20] array. But there is wastage of space. Only "Franc" is using max space, i.e., 5 charachter. Still there is wastage of 15 characters.





Instead of above u could declare a character array of pointers that would save space without writing any fixed size (in this case 20). Still u can save string of any length.





Alternative code of ur code is:


char *cur[6]={"Euro","Yen","Franc","ZWD","DOP...


u can access any of the elements by writing cur[4], cur[0] etc.
Reply:Hi,


I am no expert but i think it's the "Text String Length" in the array,

flower pictures

How do I write multiple lines of string to an output file in C?

I have an array of strings (history) that I need to write to an output file.


When I use the following code, the output file contains the contents but without the newlines even when I specified it to write a new line after every entry.


FILE *ofp;


ofp = fopen("history.list", "w");


int temp = cmdnum;


while(temp!=0)


{


fprintf(ofp, "%s\n", history[temp-1]);


temp--;


}





For example if history contains:


a


b


c





The output file that results is:


abc





Thanks for your

How do I write multiple lines of string to an output file in C?
Try opening the file in text-mode: "wt" that should convert all \n to \r\n which is required on some systems to display line breaks.


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 */


A program in c language to find all positions of a number in a sorted array?

heres the code


the method is linear search and the values of n and the array elements are taken as input from the user ina separt functn. I can always help if u want the entire prog.


specify the array length.


complete the prog before complin.








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


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


void main()


{int A[], data, n,ch=0,i;





while((i%26lt;n)%26amp;%26amp;(ch==0))


{if (data==A[i])


ch++;


else i++;


}


if (ch)


cout%26lt;%26lt;"position of the element is"%26lt;%26lt;(i+1);


else


cout%26lt;%26lt;"data not present"%26lt;%26lt;endl;





getch();


}


Can someone write some C code that scrolls an image?

I have no idea how to do this . Please help , ( assuming that the image is stored in a 2d array of pixels ) .

Can someone write some C code that scrolls an image?
I am not too sure, if C alone would be quite helpful, but you may try using the MFC libraries. Of course the assumption here is that you can use VC++ tool, otherwise you would not get MFC.





On a broader side, may I ask why are you trying to write this in C only. The contemporary lanugages like Java and C# have this feature built-in, and in case you are not shackled by the language, I would recommend to try these languages.
Reply:i would love 2 help..but i dont even know what a c-code is..sorry:(

credit cards

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));


Help in deleting names in 2d array in C.?

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





char main ()


{


char name [24] ;


char list [6] [24];


char dname [24];


char temp;


printf("\n----------------------------...


printf("\nHello!, Please Enter Six Names of Your Choice");


printf("\nUse a space to separate each name\n");


printf("------------------------------...


for(int val = 0; val %26lt; 6; val++)


{


/* read the name */


scanf("%s", name);


/* copy the read name into the list of names */


for(int val2 = 0; val2 %26lt; 24; val2++)


list[val][val2] = name[val2];


}


printf("\n----------------------------...


printf("\n The names that you entered are:\n");


printf("------------------------------...


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


{


printf ( "%s\n", list[i] );


}


/*delete name*/


printf("\nEnter the name you want deleted\n");


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


{


scanf("%s",%26amp; dname);


if (dname != list[count])


{


printf("\n This name has been deleted: ""%s",dname);


}


}


return 0;


}

Help in deleting names in 2d array in C.?
The following code performs as you describe. I hope you find it useful.





Note: this code was compiled under a C++ compiler. You can use it in C with minor changes (like changing the comment syntax from dowble dash (//) to dash-star star-dash (/* */)).





//------------------------------------...





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


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





//------------------------------------...





#define MAX_NAMES6





char sName[MAX_NAMES][32];





//------------------------------------...





void PrintNames()


{


int i;





/* deleted names are treated as empty strings; the output code will ignore the empty strings thus showing as they were deleted */





printf("\nNames:\n");


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


if (sName[i][0] != '\0')


printf("%s\n", sName[i]);





printf("\n");


}





//------------------------------------...





int main()


{


char sTmpName[32];


int i;





// read the names


printf("Please, enter %d names.\n", MAX_NAMES);


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


{


printf("Enter name %d: ", i + 1);


scanf("%s", sName[i]);


} // end for





// print the list of names


PrintNames();





printf("Enter a name to delete: ");


scanf("%s", sTmpName);


i = 0;


while (i %26lt; MAX_NAMES %26amp;%26amp; strcmp(sTmpName, sName[i]) != 0)


i++;





if (i %26lt; MAX_NAMES)


{


// Name found





/* deleted names are treated as empty strings; so make this string empty (empty strings are diferent from NULL strings: empty strings are "", while NULL strings are those that point to no char array) */


sName[i][0] = '\0';


} // end if


else


printf("\nName \"%s\" NOT found\n", sTmpName);





// print the list of names


PrintNames();





return 0;


}


//------------------------------------...
Reply:Hi,


in the /* delete name*/ part of ur programme.


U have put scanf() in for(;;) loop. Scanf() should be just after the statement:


printf("\nEnter the name you want deleted\n");


then comes ur if() condition, it should check


if (dname == list[count])


then list[count]=" "; i.e., put a null string in place of the name to be deleted.


Then simply print ur array.


for checking string u could use


strcmp(dname,list[count]); function. It is in string.h header file. so include it #include%26lt;string.h%26gt;


if both the strings are equal it will return 0.





if (!strcmp(dname,list[count])


list[count]=" ";


i.e., put a null string in place of
Reply:Two things:





1. You're not actually deleting the entry from your array.





2. In C, use strcmp(dname, list[count]) for comparing strings. The "==" and "!=" operators don't work on strings (or at least not in the way you'd expect)





Several other things:


1. You can replace for(int val2 = 0; ...) list[val][val2] = name[val2] with:





strcpy( list[val], name );





Strcpy does that work for you.





2. You have the scanf() INSIDE your 0..4 loop so the user will have the enter a name 5 times. Put it outside the loop.

brandon flowers

What is the dev c++ solution, that has an array max of 40 elements......?

What is the dev c++ solution, that has an array max of 40 elements......?


what is the dev c++ solution, that has an array max of 40 elements..the input should be from 0 to 9 only....and output the number according to its place value,, it shoud have a comma for each of the proper place value, the input should be outputed from up to down,,,,





here is the output:





Enter size: 4


4


0


9


6


Result: 4,096 (it should contain the comma (","),if it is greater than hundreds that pertains to its proper place value)





another example:


Enter size: 3


1


2


3


result: 123





another ex. hehehe:


Enter size:7


1


2


3


4


5


6


7


result: 1,234,567

What is the dev c++ solution, that has an array max of 40 elements......?
Hello Edrew, here is your solution :





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


main()


{


int a[40];


int i,r,c,n;


printf("Enter total elements to be entered (1-40) : ");


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


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


{


printf("Enter element a[ %d ]=",i);


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


}


printf("\n\n");


if(n%26lt;=3)


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


printf("%d",a[i]);


else


{


r=n % 3;


if (r != 0) {


for (i=1;i%26lt;=r;i++)


{


printf("%d",a[i]);


}


printf(",");


}


c=n/3;


for(i=1;i%26lt;=c;i++)


{printf("%d%d%d",a[r+1],a[r+2],a[r+3])...


r=r+3;


if(i!=c)


printf(",");


}


}


}
Reply:Use the modulus operator(%). It takes two values and returns the remainder.





eg.


7 % 3 = 1


6 % 3 = 0


5 % 3 = 2


4 %3 = 1


3 % 3 = 0





I assume you store the inputted array size into an INT variable. Use that variable minus the array index modulus 3 to determine if it needs a comma.





eg.


for( int index = 0; index %26lt; arraySize; index++) {


if( (index %26gt; 0) %26amp;%26amp; ((arraySize - index) % 3 == 0)) {


cout %26lt;%26lt; ",";


}


cout %26lt;%26lt; arrayOfNumbers[ index];


}


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.


Data stucture in C with Array Implementation of Stack?

#define __TEST__





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





#ifdef __TEST__


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


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


#endif


#define STACKSIZE 64








int stack[STACKSIZE];


static int stack_ptr=0;





void overflow_test( int pos )


{


if( pos %26gt;= STACKSIZE )


{


puts( "Stack overflow!\n" );


exit(1);


}


}





void underflow_test( int pos )


{


if( pos %26lt; 0 )


{


puts( "Stack underflow!\n" );


exit(1);


}


}





void push( int value )


{


overflow_test( stack_ptr+1 );


stack[stack_ptr++] = value;


}





int pop( void )


{


underflow_test( --stack_ptr );


return stack[stack_ptr];


}





#ifdef __TEST__





void wait4keypress( void )


{


while( !kbhit())


;


}





int main( void )


{


atexit(wait4keypress);


push(1);


push(2);


push(3);


printf( "%d\n", pop());


printf( "%d\n", pop());


printf( "%d\n", pop());


/* must cause stack underflow */


printf( "%d\n", pop());


return 0;


}





#endif /* __TEST__ */


Data stucture in C with Array Implementation of Stack?

#define __TEST__





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





#ifdef __TEST__


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


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


#endif


#define STACKSIZE 64








int stack[STACKSIZE];


static int stack_ptr=0;





void overflow_test( int pos )


{


if( pos %26gt;= STACKSIZE )


{


puts( "Stack overflow!\n" );


exit(1);


}


}





void underflow_test( int pos )


{


if( pos %26lt; 0 )


{


puts( "Stack underflow!\n" );


exit(1);


}


}





void push( int value )


{


overflow_test( stack_ptr+1 );


stack[stack_ptr++] = value;


}





int pop( void )


{


underflow_test( --stack_ptr );


return stack[stack_ptr];


}





#ifdef __TEST__





void wait4keypress( void )


{


while( !kbhit())


;


}





int main( void )


{


atexit(wait4keypress);


push(1);


push(2);


push(3);


printf( "%d\n", pop());


printf( "%d\n", pop());


printf( "%d\n", pop());


/* must cause stack underflow */


printf( "%d\n", pop());


return 0;


}





#endif /* __TEST__ */

video cards

What is an array in C?

Array = multi-element box, a bit like a filing cabinet, and uses an indexing system to find each variable stored within it.





The following link gives more info abt using Arrays in C.





http://gd.tuwien.ac.at/languages/c/progr...

What is an array in C?
An array is an organized sequential collection of similar data types.


For ex:


int marks[3];





declares three integer variables named 'marks' and indexed from 0 through 2 (i.e. marks[0], marks[1] and marks[2]).


Generally all the variables of the array are stored sequentially in the contiguous memory space.
Reply:ARRAY:


In row-major storage, a multidimensional array in linear memory is accessed such that rows are stored one after the other. It is the approach used by the C programming language as well as many other languages, with the notable exception of Fortran.





When using row-major order, the difference between addresses of array cells in increasing rows is larger than addresses of cells in increasing columns. For example, consider this 2×3 array:





1 2 3


4 5 6


Declaring this array in C as





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


would find the array laid-out in linear memory as:





1 2 3 4 5 6


The difference in offset from one column to the next is 1 and from one row to the next is 3. The linear offset from the beginning of the array to any given element A[row][column] can then be computed as:





offset = row + column*NUMROWS


where NUMROWS represents the number of rows in the array—in this case, 2.





[edit]


Column-major order


Column-major order is a similar method of flattening arrays onto linear memory, but the columns are listed in sequence. The programming language Fortran uses column-major ordering. The array





1 2 3


4 5 6


if stored in memory with column-major order would look like the following:





1 4 2 5 3 6


With columns listed first. The memory offset could then be computed as:





offset = row*NUMCOLS + column


Where NUMCOLS is the number of columns in the array.





It is possible to generalize both of these concepts to arrays with greater than two dimensions. For higher dimension arrays, the ordering determines which dimension of the array is listed off first. Any of the dimensions could be listed first, just the same way that a two-dimensional array could be listed column-first or row-first. The difference in offset between listings of that dimension would then be determined by a product of other dimensions. It is uncommon to have any variation except ordering dimensions first to last or last to first--equating to row-major and column-major respectively.





Treating a row-major array as a column-major array is the same as transposing it.
Reply:Arrays and Strings


In principle arrays in C are similar to those found in other languages. As we shall shortly see arrays are defined slightly differently and there are many subtle differences due the close link between array and pointers. We will look more closely at the link between pointer and arrays later in Chapter 9.





Single and Multi-dimensional Arrays


Let us first look at how we define arrays in C:








int listofnumbers[50];





BEWARE: In C Array subscripts start at 0 and end one less than the array size. For example, in the above case valid subscripts range from 0 to 49. This is a BIG difference between C and other languages and does require a bit of practice to get in the right frame of mind.





Elements can be accessed in the following ways:-











thirdnumber=listofnumbers[2];


listofnumbers[5]=100;





Multi-dimensional arrays can be defined as follows:











int tableofnumbers[50][50];





for two dimensions.





For further dimensions simply add more [ ]:











int bigD[50][50][40][30]......[50];





Elements can be accessed in the following ways:











anumber=tableofnumbers[2][3];


tableofnumbers[25][16]=100;
Reply:Array is a group of elements where all the elements that are stored are same type. In simple Array is a way to store Homogeneous Elements. Memories are allocated conquetively
Reply:Arrays in C act to store related data under a single variable name with an index, also known as a subscript. It is easiest to think of an array as simply a list or ordered grouping of variables. As such, arrays often help a programmer organize collections of data efficiently and intuitively.
Reply:int a[100];


This is an array declaration in C.


This instructs the compiler to find and allocate a contiguos area of the size 100 * sizeof (int).


You can access each element of the array using a subscript (or index). e.g. : a[5] or a[i] (where i is an integral type: (unsigned) int / long / char).


The catch with subscripts is that it must reside in the range [0, 99] in this case. If you declare a larger or smaller array, the subscript must be in the range [0, SIZE - 1]. If you don't respect this rule, the compiler WILL NOT give you any warning, it'll accept any (positive?) index as valid, but at runtime you'll get a 'nice' crash if you try to write that area (e.g. write in a[100] in our case).


The downside of using arrays is that you WILL need a CONTIGUOS area, and if that area is too big, it will fail big time. So my advice is use pointers if you are unsure how big is the area you need. In C, you have *alloc (...) and free (...).


Usage of arrays and pointers are somehow interchangeable, but you need to read some materials in order to understand that.


All you need to remeber when working with arrays is double-checking the index and not using too big of a value for the size.


Also, you can use another type for the values in the array (double, float, unsigned long, you name it, even pointers: void* a[256]).


Another catch is: the size of the array must be constant. Not as in const int SIZE = 100, but as in an actual number. Because consts are not actually consts, they're read - only variables. A #define SIZE 100 would do the job, but use #defines only in C code, not C++.


Remember to always think twice if you really need arrays . If the size of the data stored varies at runtime, then you need to take a journey down The Pointer Path. It'll be bumpy, but VERY useful.


I also recommend using C++ instead of C if you have the choice ('cause it has the wonderful two instructions, new and delete to use instead of *alloc (...) and free (...), respectively)


How to find the product of 2d array matrices in c?

Is this a homework assignment?





MultMatrix(firstM, secondM, outM, firstrows, cols, secondcols)


Matrix firstM, secondM, outM;


int firstrows, cols, secondcols;


{


int i,j,k;


double sum;





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


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


{


sum = 0.0;


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


sum += firstM[j][k] * secondM[k][i];


outM[j][i] = sum;


}


}


Why is an array in C++ called a derived data type please explain in detail?

Here you go


http://www.verhoef.com/outlines/CPlus2C....


///

Why is an array in C++ called a derived data type please explain in detail?
A derived data type is a user defined definition of logical construct to be used as an abstraction in the software.


Since we can define an array of user defined datatypes it is called an derived data type in C++


How to declare and use 2d dynamic array in c language?

/*code functions in static case but got to use dynamic array*/


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


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


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


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





{


FILE *fp;


int i,j=0;


float n,x1,y1,x2,y2,cross,result,area=0,p[5][5...


clrscr();


fp=fopen(argv[1],"r");


if(fp==NULL)


{


printf("Cannot open file");


exit(0);


}








while(!feof(fp)) {


/* fread(%26amp;p[j][0],sizeof(p[j][0]),1,fp); */





fscanf(fp, "%f %f", %26amp;p[j][0],%26amp;p[j][1]);


printf("%f\n,%f\n",p[j][0],p[j][1]);


j++;





}





j=j-1;


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


{


x1 = p[i][0] - p[0][0];


y1 = p[i][1] - p[0][1];


x2 = p[i+1][0] - p[0][0];


y2 = p[i+1][1] - p[0][1];


printf("x1 is %f\ny1 is %f\nx2 is %f\ny2 is %f\n",x1,y1,x2,y2);


cross = x1*y2 - x2*y1;


printf("cross is %f\n",cross);


area += cross;





}


result = fabs(area/2.0);





printf("The area is %f",result);





}

How to declare and use 2d dynamic array in c language?
Hey mind one simple thing array means static only you cannot declare it dynamic okay
Reply:You do not actually declare a two dimentional dynamic array in C.


What you do is declare some storage. You reference this storage using a 1 dimention array, but you control the subscript in such a way that it acts like a 2, 3 etc. dimension array.





A little bit mind blowing but if you check out the three links you should be able to get it to work.

sd cards

In C, How do I create an array of 360 floats using calloc (or malloc), and check the memory has been...?

allocated ok?





Also how do I populate this array with a series of sin values, where the angle stored is the element of the array?, i.e





f[0] = sin(0);


f[1] = sin(1);





for the output I need to display the values on the screen





Many Thanks for your help :)

In C, How do I create an array of 360 floats using calloc (or malloc), and check the memory has been...?
float *arr;


int i;


arr = malloc(sizeof(float) * 360);


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


arr[i] = sin(i);


How to pass two dimension array to function(by reference in c++)?

arrays are always passed by reference in c++ (so just pass the array like you would an int and it is passed by reference)

How to pass two dimension array to function(by reference in c++)?
void func_for_array(type** array, int size, int size2)


{


};





void main()


{


type array[10][10];


func_for_array(array,10,10);


};


Write a program that will let the user type in 10 integer values and store them in an array using the C++?

#include %26lt;iostream%26gt;


using namespace std;


int main()


{


int myArray(10); // declare your array and size


/*


Create a loop to continuously ask for the user's input until


integer #10 is achieved


*/


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


{


// Prompt for input


cout %26lt;%26lt; "Type integer #" %26lt;%26lt; count + 1 %26lt;%26lt; ": ";


// Input to the specific array # specified by the variable "count"


cin %26lt;%26lt; myArray(count);


}


}

Write a program that will let the user type in 10 integer values and store them in an array using the C++?
#include%26lt;iostream.h%26gt;


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


void main()


{


clrscr();


int num[10];


cout%26lt;%26lt;"Enter 10 numbers:";


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


{


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


}


cout%26lt;%26lt;"The stored elements of the array are:";


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


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


getch();


}
Reply:no, i will not write the program, you should do it your self. but i'll write a harsh function in c of course:


int[10] array;





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


{


cout%26gt;%26gt;type some words


cin%26lt;%26lt; %26amp;array[i];


}


// it'll do the basic function you ask.


// you should repair any function that doesn't work, because its been a while from the last time i wrote program in c++.


May some one tell me what is the strings and the sympols in an array of c++ or c I mean sympols and words c c+

You simply need to initialize the array. It can be made of anything you want. For example,





String names[20] = {These Are Strings} The first box will be These. The second array box will be Are. And the third array box will be Strings where all other 17 boxes will be NULL until you fill them. OR for example,





int numbers[10] = {1,2,3,4,5,6,7,8,9,10} Where box 0-9 will be the numbers 1-10 consecutively.





Arrays are made up of this syntax: %26lt;array type%26gt;%26lt;array name%26gt;[amount of spots in the array]

plants

How do i insert data into a 2-dim array in c-language, and then print it?

i need to make all the values in the array to equal '_' which just represents a space which will later be modified


this is how i started the array


char chararr[60][40];


i need to use a 'for' loop or similar in order to achieve this.





after all the information is in the array i need to print it using the printf command. the way this needs to be done is by printing each value individually so that it looks like an actual matrix, which means a new line should be started after each entire row is printed


i need this urgently so please help me out. and i would greatly appreciate it if you could give me the code for either task


thanks

How do i insert data into a 2-dim array in c-language, and then print it?
//to initialize your array


char chararr[60][40];


int i;


int j;


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


{


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


{


chararr[i][j] = '_';


}


}





//to print your array





int i;


int j;


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


{


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


{


printf("%c", char[i][j]);


}


printf("\n");


}





notice how similar they are? nested for loops are how you'll always step through multi-dimensional arrays. If you need some clarification for the code above, send me an email.





Good luck.


How to make a multi-dimensional array in C++?

Can anyone help me make a multi-dimesional array, im totally lost in one of my class. can anyone make me an small example program like translating a numeric entry to a text entry AND translate a text entry to a numeric one.

How to make a multi-dimensional array in C++?
let assume that your cp keypad is laid out like this.





just declare a variable like this.





char text[3][3][4];





then populate that like this..





text[0][0][0]='a';


text[0][0][1]='b';


text[0][0][2]='c';





text[0][1][0]='d';


text[0][1][1]='e';


text[0][1][2]='f';





text[0][2][0]='g';


text[0][2][1]='h';


text[0][2][2]='i';





and so on..


just visualize the 3d array as a table which is cell has 3 arrays on it...





i can help you more if you want to.. ^_^v


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.


Obtaining the size of an array in C++ at runtime?

I have a problem with finding the length of an array at run time and can't understand what is going wrong.





NB: someObject is a class which need not be shown in the question, any class at all.





#define arraylen(x) (sizeof(x)/sizeof(x[0]))





void failingFunction(int count)


{


someObject *theArray


theArray = new someObject[count];


fprintf(stderr,"length = %d",arraylen(theArray));


}





void workingFunction(int count)


{


someObject theArray[3]


fprintf(stderr,"length = %d",arraylen(theArray));


}





The working function will give me the correct size via the macro, the failing function never gives me anything close to the right size. Assume that "count" is not known when I need to find the size, the code is just an example...





What am I missing, thanks in advance ?

Obtaining the size of an array in C++ at runtime?
I don't think it has anything to do with vectors - at least the explanation of why failingFunction() is failing. It is failing because, to the compiler, "theArray" is just a pointer, and sizeof( theArray ) will yield the size of long, i.e., the integer used to store the address. It does not matter whether theArray is the beginning address of an array, C++ cannot evaluate the size of that array, because it was allocated by new.





To better understand why, let us look at this example:





Probably you know that you if you allocate an array using new[] as you have done, you should use delete [] to prevent memory leak. But if you have allocated using just new (not the parentheses), then you should free the memory using delete (and not delete []).





So what will happen if you allocate using new [] and while freeing, use just delete instead of delete []?





Answer: It will leak memory, only the first element will be freed, the rest won't be freed.





So why does not either the compiler or the runtime libraries give an error when you use delete instead of delete[]?





Answer to that question is - it does not know whether you are doing the right thing or not! Because it does not know the goddamn size of the array! It does not know whether the size is 1 or 3 or 100. So it cannot blame you fearing that you might be knowing what you are doing, and the blame might leave it embarassed!





The whole point was to prove that it does not know the size. And if it does not know the size, how will sizeof() work? It won't!





That is the explanation of why it is not working. As to how you can make it work, that question is equivalent of asking - how do we know the size of an array allocated by new []?





Yes, you can do that by using container classes like vectors, there is not straightforward way. I have always wondered that the method delete[]() somehow knows what the size is, so why not expose another method like size() to return it to the developer?

id cards

Can someone help me write this in C language?

Write a function that will take in a FILE pointer and a double array as parameters, and return an integer. The pointer is to a text file that you will read data from, and the file data (which represents a set of scores) will be read into the array. Have the function read the value into the array, and return the number of items read.

Can someone help me write this in C language?
int func(FILE *fp, int **a) {


/* Fill it up */





return value;


}
Reply:CC c c c c cccc C c c c c C c c cccc c C C C.com


Friday, May 21, 2010

C - How do I save data in a text file?

I have made a maze game in C and am stuck on how to get a user name and save the username and score on a text file. I don't know much about string in C except that "it is an array of characters". I know a user name will need to be string so I am using this:





char username[3];


scanf("%s", username);





I am assuming the variable 'username' will be saved to a file but I do not know how to do this. Any ideas?

C - How do I save data in a text file?
You need the following basic steps:





FILE *fp; //create a file pointer


fp = fopen("file","w"); //open "file" for writing "w"





//check if the file was opened without errors


if(fp==NULL) {


printf("\nCould not open file.. aborting!!");


exit(1);


}





//write to file - you have a number of options here - read more about the functions to suit the formatting and data you need to write to file - one example below:





fprintf(fp, "%s %d", username, score)





fclose(fp); //close the file pointer once you are done writing to the file.
Reply:Use fprintf() function or fwrite() function. Refer the page given below...