• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

CronoShot

Member
Complete and utter noob question. I just started taking an introductory programming class this semester, and I'm already stuck on this assignment:

Code:
Write a C program which prompts the user to enter some numbers and prints “Non-decreasing” if no number is smaller than the previous number, and “No” otherwise. 
Entering 0 should terminate the sequence of numbers and cause the result to be displayed.

• The user can enter numbers with or without a fractional part.
• The program should work as described above for numbers that are positive, negative or zero.
• The prompts and output displayed by the program must be formated as shown in the sample run below (e.g. blank lines, spacing, case of text).
• A sample run of your program should look like:
     Entering 0 will terminate the sequence of input values.
     Enter a number: -7.6
     Enter a number: -2
     Enter a number: 5
     Enter a number: 5
     Enter a number: 0
     RESULT: Non-decreasing

My teacher's lectures really aren't any help. I'm just not sure how to get the program to save the answers you enter, and then compare them to each numbers before it.
 

sephi22

Member
it's the list item that you use as the point of entry into the list. generally you store a pointer to it in your list struct, and each time you want to access the list eg. to do an insert or search for a particular element, you start from the anchor point and follow the links to subsequent nodes. the actual item can change, for instance if you are doing a sort-on-insert list of integers, you might check first that the int you are inserting is less than the anchor point and if so you insert it between the first and last items and set the anchor variable to point to the new item.

Fucking brilliant explanation. Thanks mate
 

Tamanon

Banned
You don't necessarily need to save all the answers, just the previous one and the current one. That can be done using two separate variables, which are replaced on each iteration. In order to figure out if the numbers are non-decreasing, you just need to compare versus the previous entered number, because by nature, if the numbers aren't decreasing, then no earlier ones can be more than the current one.
 

CronoShot

Member
You don't necessarily need to save all the answers, just the previous one and the current one. That can be done using two separate variables, which are replaced on each iteration. In order to figure out if the numbers are non-decreasing, you just need to compare versus the previous entered number, because by nature, if the numbers aren't decreasing, then no earlier ones can be more than the current one.

This is what I've got, and it keeps giving me Non-Decreasing, no matter what I type in.

Code:
#include <stdio.h>

int main(void)
{
    double current_number, previous_number = 0;                         /* entered by user */
    int determiner = 1;                                                 /* determines result */

    printf("Entering a 0 will terminate the sequence of input values.");
    
    printf("\nEnter a number: ");
    scanf("%lf", &current_number);
    
    while (current_number != 0)
        
{
      previous_number = current_number;
    
      printf("Enter a number: ");
      scanf("%lf", &current_number);
    
      if (previous_number > current_number && current_number != 0) determiner = 0;
}
    
    if (determiner = 0)
    {
        printf("\nRESULT: NO\n");
    }
    
    if (determiner = 1)
    {
        printf("\nRESULT: NON-DECREASING\n");
    }
    
    return 0;
}

The int determiner = 1 isn't the cause, since I switched it to equal 0 and it changed nothing. So I have no idea how it's even getting a value of 1.
 

hateradio

The Most Dangerous Yes Man
I was putting the old array into a new array with the keys containing the dates.

I'm building an app with the Laravel framework (MVC). I need to retrieve and manipulate the data before passing it on to the view.

I'm not sure how else to do it while keeping the logic simple in the view.

Code:
@foreach ($dates as $date => $games)
<table>
    <thead>
        <tr>
            <td colspan="5">{{ $date }}</td>
        </tr>
    </thead>
    <tbody>
        @foreach ($games as $game)
        <tr>
            <td>{{ $game->league }}</td>
            <td>{{ $game->round }}</td>
            <td>{{ $game->user_1 }}</td>
            <td>{{ $game->score_1 }} - {{ $game->score_2 }}</td>
            <td>{{ $game->user_2 }}</td>
        </tr>
        @endforeach
    </tbody>
</table>
@endforeach
That looks pretty simple to me.
 
Alright so i'm in a Comp-Sci Course for college and within my program, I got completely screwed over in professors for the C++ course. Out of the three professors, I've had two of them before and they absolutely know their stuff and are amazing. The last one isn't as good. She literally can't teach and since this is a course for intro to C++, normally one would think that we would start out at the basics. Well no. She started us half way through the course and is trying to have us do OpenGL and 3D Rendering based stuff on day one when most of the people in the class still don't know how to write a simple "Hello World" program using the console. let alone any basics about the language such as how to write C++ functions or what not.

Since I don't want to be screwed over in this course, I was wondering if anyone here has any good suggestions for Intro C++ resources whether they be books or videos or hell I'd even take a podcast. I've taken a look at the links in the OP and I'm going to go through some stuff tomorrow morning when I wake up, I'm just wondering if there is any other stuff people recommend I look at.

Some Info. This is my second year and so far I know and have a good understanding of C#, Java, Python, HTML+CSS and some others. So I'm not new to programming. I just need a little help in finding resources.
 
So I started my journey to become a Web Developer a few weeks ago and so far I'm enjoying it a lot. I've been using Team Treehouse and in my opinion in a great resource, what with their point system and pretty good teachers.

Are there any Web Developers on GAF that have any tips for me?
 
This is what I've got, and it keeps giving me Non-Decreasing, no matter what I type in.

Code:
...

The int determiner = 1 isn't the cause, since I switched it to equal 0 and it changed nothing. So I have no idea how it's even getting a value of 1.

I don't know which compiler you're using, but in case you are using clang or gcc, try compiling your program with -Wall (enable all warnings). Generally, a compiler should give you a warning if you're doing something like this:
Code:
if(variable = 5)
    doSomething();
The warnings are very useful in general, even if you don't understand all of them in the beginning. I did a systems programming class last year, also in C, and we had to have our assignments all compile with 0 warnings or else it would be rejected. That was not very fun, but I understand the reasoning behind it.
 

arit

Member
The warnings are very useful in general, even if you don't understand all of them in the beginning. I did a systems programming class last year, also in C, and we had to have our assignments all compile with 0 warnings or else it would be rejected. That was not very fun, but I understand the reasoning behind it.

The "-ansi -pedantic -Wall" we had to use in our C introduction course was not that bad, but even funny once another instructor gave us his code as base, which could not be compiled with these flags.
 

phoenixyz

Member
The "-ansi -pedantic -Wall" we had to use in our C introduction course was not that bad, but even funny once another instructor gave us his code as base, which could not be compiled with these flags.
We had to use the same flags in our C introduction back in the day. But I don't see much of a reason to still enforce ANSI-C in everyday use (-Wall is useful nevertheless).
 

Slavik81

Member
I'm thinking of picking up a few courses I had missed by getting into software through EE. One of them was Compiler Construction.

However, that course strongly recommends an Introduction to Computability. I figured it sounded interesting; an introduction to formal languages and grammars might come in handy.

However, that course has prereqs in Discrete Math and in Logic I (sequential and first order logic). I don't have equivalents for those, but they strike me as being less than immediately useful. I could try to get them waived.

I presume most computer science programs are fairly similar. Can anyone tell me what courses they thought were valuable in retrospect? Do you think I'd be lost in these courses without the math/philosophical background?
 

Kalnos

Banned
If formal languages and grammars are covered in Introduction to Computability then I would think that's extremely relevant (particularly because of lexical analysis). It sounds very much like the 'Automata Theory' course from where I graduated.

If you graduated with an EE degree then I can't see Logic I being very important. Discrete Math is an awesome course, I'd definitely take it. It's the most practical math course I ever took in CE.
 

V_Arnold

Member
Discrete Mathematics is important once you will enter the realm of encryption and data compression. That and Linear Algebra together form the basis that you will need. I would say you should definitely take it.
 
Okay, now I have to learn C, SQL, and Assembly for this semester. Can anyone recommend a good book for C? My TA recommended C: the programming language by Dennis Ritchie, Brian Kernighan. I think I might get it but seems pricey so I would like to hear some feedback before making a commitment to buying it.

I'm currently using headfirst C since I thought the headfirst java was good and helped me out before. I'm also thinking about using cprogramming.com(site posted in the OP) to help me out as well.
 

diaspora

Member
Okay, now I have to learn C, SQL, and Assembly for this semester. Can anyone recommend a good book for C? My TA recommended C: the programming language by Dennis Ritchie, Brian Kernighan. I think I might get it but seems pricey so I would like to hear some feedback before making a commitment to buying it.

I'm currently using headfirst C since I thought the headfirst java was good and helped me out before. I'm also thinking about using cprogramming.com(site posted in the OP) to help me out as well.

C for Dummies, all-in-one desk reference IMO.
 
Okay, now I have to learn C, SQL, and Assembly for this semester. Can anyone recommend a good book for C? My TA recommended C: the programming language by Dennis Ritchie, Brian Kernighan. I think I might get it but seems pricey so I would like to hear some feedback before making a commitment to buying it.

I'm currently using headfirst C since I thought the headfirst java was good and helped me out before. I'm also thinking about using cprogramming.com(site posted in the OP) to help me out as well.
The K&R book is a classic and I definitely recommend it.
 

cyborg009

Banned
Hey guys I started my class in android development and I'm currently really enjoying it. But at the moment I'm having some issues using a second activity for this assignment.

The code is suppose to have names and next to the names a button that will show a person details. I got the first activity working but I'm having issues implementing the info shown when the (details) buttons is clicked. I feel like its simple but I can't wrap my head around it.

Edit: I know i could use some if statements and set the text to the strings but the code for the buttons are in another class.
 

gblues

Banned
I'm working on a project that is more or less my first time writing a GUI, using C# and WPF.

Data binding is driving me nuts.

XAML said:
Code:
<TextBox Height="23" HorizontalAlignment="Right" Margin="0,12,12,0" Name="tbUsername" VerticalAlignment="Top" Width="160" Text="{Binding Path=bindUser}" />

C# said:
Code:
public partial class Login : Window, INotifyPropertyChanged
    {
        private string sfUser;

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

        public string bindUser {
            get
            {
                return sfUser;
            }
            set
            {
                if (value != sfUser)
                {
                    sfUser = value;
                    OnPropertyChanged("bindUser");
                }
            }
        }

        public Login()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            var service = new SFDC.SoapClient();
            SFDC.LoginResult lr =  null;
            try
            {
                var authKey = sfPassword + sfToken;
                MessageBox.Show("User: "+bindUser+"\nAuthKey: " + authKey);
                // bindUser is empty and I don't know why
                lr = service.login(null, bindUser, sfPassword + sfToken);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Authentication error: " + ex.Message, "Error", MessageBoxButton.OK);
            }
        }

When I enter something into the form, it doesn't get updated, so my login query fails. And don't worry about the missing variables, I chopped some stuff out that isn't relevant.

Any tips?
 

tokkun

Member
Anyone using Vim 7.4? I just upgraded, and all my key mappings from 7.3 are broken now. For example:

Code:
inoremap jk <Esc>

Now inserts the string "<Esc>" instead of sending the escape character.
 
The K&R book is a classic and I definitely recommend it.
Awesome, I found it online. Some university uploaded it so guess I'll use that. I'm going to go through headfirst since I'm 190 pages deep so might as well continue. Will be reading it though to get a better understanding of C probably this weekend and to see if headfirst missed anything.
 

_Isaac

Member
I'm working on a project that is more or less my first time writing a GUI, using C# and WPF.

Data binding is driving me nuts.





When I enter something into the form, it doesn't get updated, so my login query fails. And don't worry about the missing variables, I chopped some stuff out that isn't relevant.

Any tips?

I haven't worked with WPF in a long time, but I played around with your code, and I set the DataContext to the current class, so the Path to the bindUser property would work, so the constructor is now.

C# said:
Code:
public Login()
        {
            InitializeComponent();
            myGrid.DataContext = this;
        }

myGrid is just the name of the grid surrounding the textbox. I'm sure any other container element would work.

XAML said:
Code:
    <Grid x:Name="myGrid">
        <TextBox 
            Height="23" 
            HorizontalAlignment="Right" 
            Margin="0,12,12,0" 
            Name="tbUsername" 
            VerticalAlignment="Top" 
            Width="160" 
            Text="{Binding Path=bindUser}" />
        <Button 
            x:Name="btnLogin"
            Content="Button" 
            HorizontalAlignment="Right" 
            Margin="133,127,0,0" 
            VerticalAlignment="Top" 
            Width="75" 
            Click="btnLogin_Click" />
    </Grid>

I don't know if there's a XAML way of setting the DataContext like that, but this seemed to work for me. :p
 

Chris R

Member
That feel when you finally get a breakthrough on a project you have been tinkering with for some time... Soooo goood.

Now to improve my algorithm if possible, it works fine with just me testing it locally, need to make sure it isn't too slow running on an actual server accessed from the web by multiple people.
 

mackattk

Member
Having trouble with this ... I think I almost got it but I am sure I am making a stupid mistake.

Relevant info:

Code:
header:
void sortArray(phoneRecords, int size);

in main:
		for (int i=0; i<512; i++){
		sortArray(phoneDatabase[i], 512);
		cout << phoneDatabase[i] << endl;
		}

void sortArray (phoneRecords phoneDatabase[], int size) { 
	bool swap;
	string temp;
	do {
		swap = false;
		for(int count = 0; count < (size - 1); count++) { 
			if (phoneDatabase[count].getLastName() > phoneDatabase[count+1].getLastName()) {
				temp = phoneDatabase[count].getLastName(); 
				phoneDatabase[count].getLastName() = phoneDatabase[count + 1].getLastName(); 
				phoneDatabase[count+1].getLastName() = temp;
				swap = true;
			}
		}
	} while(swap);
}
errors:
Error 1 error LNK2019: unresolved external symbol "void __cdecl sortArray(class phoneRecords,int)" (?sortArray@@YAXVphoneRecords@@H@Z) referenced in function _main

Error 2 error LNK1120: 1 unresolved externals
 

Water

Member
Having trouble with this ... I think I almost got it but I am sure I am making a stupid mistake.

errors:
Error 1 error LNK2019: unresolved external symbol "void __cdecl sortArray(class phoneRecords,int)" (?sortArray@@YAXVphoneRecords@@H@Z) referenced in function _main
Pretty straightforward. Your header promises that there's going to be a sortArray function taking parameters of types "phoneRecords" and "int", and that's enough to compile the main. After it's compiled, though, the linker is supposed to find the implementation of sortArray, and can't find one, because the definition you have written takes parameters of types "phoneRecords[]" and "int".

Anyway, you are asking for trouble by using C-style arrays. Use std::vector instead.
 

mackattk

Member
Pretty straightforward. Your header promises that there's going to be a sortArray function taking parameters of types "phoneRecords" and "int", and that's enough to compile the main. After it's compiled, though, the linker is supposed to find the implementation of sortArray, and can't find one, because the definition you have written takes parameters of types "phoneRecords[]" and "int".

Anyway, you are asking for trouble by using C-style arrays. Use std::vector instead.

That is basically what I figured out as well. I have been trying to play around with the header in order for it to accept an array in the function, but haven't figured it out yet. We haven't gotten to vectors yet in the class, so that is out.
 

tokkun

Member
That is basically what I figured out as well. I have been trying to play around with the header in order for it to accept an array in the function, but haven't figured it out yet. We haven't gotten to vectors yet in the class, so that is out.

Make the argument a pointer. You can index into it just as if it was an array.

Code:
void sortArray(phoneRecords* phoneDatabase, int size);
 

Slavik81

Member
Having trouble with this ... I think I almost got it but I am sure I am making a stupid mistake.

....

errors:
Error 1 error LNK2019: unresolved external symbol "void __cdecl sortArray(class phoneRecords,int)" (?sortArray@@YAXVphoneRecords@@H@Z) referenced in function _main

Error 2 error LNK1120: 1 unresolved externals
You declare the function as:
void sortArray(phoneRecords, int size);
But you define it as
void sortArray (phoneRecords phoneDatabase[], int size)

The linker goes to look for a function matching the signature you declared it with, and can't find one. Hence the linker error.

Just change the header to match the implementation. If it's exactly the same, it'll be fine.
 

mackattk

Member
You declare the function as:
void sortArray(phoneRecords, int size);
But you define it as
void sortArray (phoneRecords phoneDatabase[], int size)

The linker goes to look for a function matching the signature you declared it with, and can't find one. Hence the linker error.

Just change the header to match the implementation. If it's exactly the same, it'll be fine.

I tried that too, and am not having any luck getting it to run.

It is getting hung up on the sortArray(phoneDatabase, 512); inside of the loop

Here is the complete code as I have it now:

Code:
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>

using namespace std;

class phoneRecords {
private:
	string mLastName;
	string mFirstName;
	int mAreaCode;
	int mPrefix;
	int mDigits;

public:
	phoneRecords();
	phoneRecords(string, string, int, int, int);

	//accessor or getter methods

	string getLastName() const;
	string getFirstName() const;
	int getAreaCode() const;
	int getPrefix() const;
	int getDigits() const;

	// mutator or setter methods
	void setLastName(string lastName){
		mLastName=lastName;}
	void setFirstName(string firstName){
		mFirstName=firstName;}
	void setAreaCode(int areaCode){
		mAreaCode=areaCode;};
	void setPrefix(int Prefix){
		mPrefix=Prefix;}
	void setDigits(int Digits){
		mDigits=Digits;}
};

phoneRecords::phoneRecords(){
		mLastName="UNKNOWN";
		mFirstName="UNKNOWN";
		mAreaCode=0;
		mPrefix=0;
		mDigits=0;
}

phoneRecords::phoneRecords(string lastName, string firstName, int areaCode, int Prefix, int Digits){
		mLastName=lastName;
		mFirstName=firstName;
		mAreaCode=areaCode;
		mPrefix=Prefix;
		mDigits=Digits;
}

	string phoneRecords::getLastName() const {
		return mLastName;}

	string phoneRecords::getFirstName() const{
		return mFirstName;}

	int phoneRecords::getAreaCode() const{
		return mAreaCode;}

	int phoneRecords::getPrefix() const{
		return mPrefix;}

	int phoneRecords::getDigits() const{
		return mDigits;}



	ostream & operator << (ostream & out, const phoneRecords & emp){
		out << emp.getLastName() << ", " << emp.getFirstName() << " (" << emp.getAreaCode() << ") "
			<< emp.getPrefix() << "-" << emp.getDigits();
		return out;
	}

void sortArray(phoneRecords phoneDatabase[], int size);


int main(){
		phoneRecords phoneDatabase[512];

		ifstream phoneFile;
		phoneFile.open("phoneDatabase.dat");

		string templastname;
		string tempfirstname;
		int tempareacode;
		int tempprefix;
		int tempdigits;

		for (int i=0; i<512; i++){
			phoneFile >> tempareacode >> tempprefix >> tempdigits >> templastname >> tempfirstname;

			phoneDatabase[i].setLastName(templastname);
			phoneDatabase[i].setFirstName(tempfirstname);
			phoneDatabase[i].setAreaCode(tempareacode);
			phoneDatabase[i].setPrefix(tempprefix);
			phoneDatabase[i].setDigits(tempdigits);

		}
		phoneFile.close();

		for (int i=0; i<512; i++){
		sortArray(phoneDatabase[i], 512);
		cout << phoneDatabase[i] << endl;
		}

		system("PAUSE");
		return 0;
}

void sortArray(phoneRecords phoneDatabase[], int size) { 
	bool swap;
	string temp;
	do {
		swap = false;
		for(int count = 0; count < (size - 1); count++) { 
			if (phoneDatabase[count].getLastName() > phoneDatabase[count+1].getLastName()) {
				temp = phoneDatabase[count].getLastName(); 
				phoneDatabase[count].getLastName() = phoneDatabase[count + 1].getLastName(); 
				phoneDatabase[count+1].getLastName() = temp;
				swap = true;
			}
		}
	} while(swap);
}
 

mackattk

Member
Thanks poweld, I didn't think of passing the phoneDatabase outside of the loop. There is a big in the sort loop that I will need to figure out, but I could confirm that the phoneDatabase was being passed into the sortArray function successfully. I am usually good with computers and technologically savvy, but C++ has been really hard for me to grasp.
 

tokkun

Member
Thanks poweld, I didn't think of passing the phoneDatabase outside of the loop. There is a big in the sort loop that I will need to figure out, but I could confirm that the phoneDatabase was being passed into the sortArray function successfully. I am usually good with computers and technologically savvy, but C++ has been really hard for me to grasp.

Your sort loop does not work because these lines

Code:
phoneDatabase[count].getLastName() = phoneDatabase[count + 1].getLastName(); 
phoneDatabase[count+1].getLastName() = temp;

Do not do what you want them to do. getLastName() creates a new string.

So when you do
Code:
phoneDatabase[count+1].getLastName() = temp;

what happens is that you create a new string with a copy of the last name data. Then you assign the value in temp to that new string. However you don't actually change the value of the last name in the database.

Basically it is equivalent to doing this:

Code:
{
  string short_lived_str = phoneDatabase[count+1].getLastName();
  short_lived_str = temp;
}

To do what you want, you need to use the setter method:

Code:
phoneDatabase[count+1].setLastName(temp);
 
Thanks poweld, I didn't think of passing the phoneDatabase outside of the loop. There is a big in the sort loop that I will need to figure out, but I could confirm that the phoneDatabase was being passed into the sortArray function successfully. I am usually good with computers and technologically savvy, but C++ has been really hard for me to grasp.

Don't worry. Andrei Alexandrescu (a pretty well-known C++ programmer and author) says the following about C++:
I'll expand on a few points I made in the last day's panel.

In my opinion C++ is a language for experts and experts only. Even simple use requires an unusually high amount of fluency. It has enough pitfalls in virtually all of its core constructs to make its use by benevolent amateurs virtually impossible except for the most trivial applications.

As a simple example, consider something does not compile. The error messages (all jokes about their length aside) use fundamental notions (elaborate types, addresses, conversions, lookup arcana) that are not only difficult to understand, but use notions and concepts that most non-specialists won't even grasp. It follows that the bucolic story of a non-expert writing C++ code only works assuming they make no compilation errors of any substance.

The problem gets only compounded by a program that does compile but runs erroneously. C++ has only a thin layer of structure and safety on top of an unsafe core, and the tiniest of scratches will expose it. There are even constructs that look eminently safe but are marred by subtle issues.

Last, there's what I call a "crowding of syntaxes". For compatibility reasons (which are nevertheless important), C++ offers too many ways of doing the same thing, most of which are inefficient, unsafe, or both. Herb Sutter, Scott Meyers, and I spent weeks on an email discussion on what's the best way to initialize a variable with an expression. One might naively think that

Code:
auto v = expr;

is best, but it isn't. The alternative forms:

Code:
T v = expr;
auto v(expr);
T v(expr);

also have subtle issues. It turns out that the best way is:

Code:
auto v { expr };

which to me looks uglier than sin, and very non-C++-y. The reason for which things have gotten to this point is that all good syntaxes have been taken by imperfect constructs, which now must be carried forward.

Source
 
Had the dream job opportunity that fell through in July call me again last week only for things to fall through again this week.

This shit is beyond depressing.
 

mackattk

Member
Thanks everyone for your help. Things started finally clicking a little bit, and this is what I came up with that works. I initially had trouble with the temp variable. but then figured that I needed to make it an instance of the phoneRecords class for it to properly sort, as I couldn't get and int or string for it to work. It was trying to compare two different types of objects.

The phoneDatabase[count+1].setLastName(temp); was able to make the program run, but set everybody's last name to what it was after it was sorted, which in this case was "Zhang". After this semester I might try to learn a language that is a little more beginner-friendly. C++ is widely used, and maybe it is just a weed out class for college, but it is one of the harder classes I have had.

Code:
void sortArray(phoneRecords phoneDatabase[], int size) { 

	bool swap;
	phoneRecords temp;
	do {
		swap = false;
		for(int count = 0; count < (size - 1); count++) { 
			if (phoneDatabase[count].getLastName() > phoneDatabase[count+1].getLastName()) {
				temp = phoneDatabase[count]; 
				phoneDatabase[count] = phoneDatabase[count + 1]; 
				phoneDatabase[count+1]=temp;
				swap = true;
			}
		}
	} while(swap);
}
 

Slavik81

Member
Thanks poweld, I didn't think of passing the phoneDatabase outside of the loop. There is a big in the sort loop that I will need to figure out, but I could confirm that the phoneDatabase was being passed into the sortArray function successfully. I am usually good with computers and technologically savvy, but C++ has been really hard for me to grasp.
To explain why you were having that problem:

phoneDataBase is an array of phoneRecords
phoneDataBase returns a reference to a phoneRecord
void sortArray (phoneRecords phoneDatabase[], int size) expects to take an array of phoneRecords and an integer.
Hence why passing sortArray (phoneDataBase, 512) doesn't work: you were passing a reference to a phoneRecord and an integer to a function that expected to receive an array of phoneRecords and an integer.

Your current problem is a little harder. It's not obvious to me why everyone would end up with the same last name.
 

Relix

he's Virgin Tight™
After working on business-level C# and VB applications (web apps too!) I wanna move to PHP and expand my knowledge outside Microsoft stuff. I am pretty damn cozy developing in Visual Studio, and SQL Server Management and ASPX stuff but gotta move out of the comfort zone. Since I am here.... what are the best tools/IDE for PHP applications and is there an alternative to SQL Management Server?
 

mackattk

Member
To explain why you were having that problem:

phoneDataBase is an array phoneRecords
phoneDataBase returns a reference to a phoneRecord
void sortArray (phoneRecords phoneDatabase[], int size) expects to take an array of phoneRecords and an integer.
Hence why passing sortArray (phoneDataBase, 512) doesn't work: you were passing a reference to a phoneRecord and an integer to a function that expected to receive an array phoneRecords and an integer.

Your current problem is a little harder. It's not obvious to me why everyone would end up with the same last name.


Thanks, sometimes its easier when it is explained in plain english what is going on. I got the sort function to work, and so everything is great now.

The reason why everybody was ending up with the same last name was because it was overwriting everyone's last name with the last name in the database file (which was Zhang).
 

CronoShot

Member
Another stupid question.

I current have this little section

Code:
    printf("\nYear    Population\n");                              
    printf("----    ----------\n");
    printf("%4d%14.lf\n", n, CurrentYr);
        
        n=1;
        while (n < 26) {
        printf("%4d%14.lf\n", n++, NextYr);
        }

And the formula for NextYr is

Code:
NextYr = Rate * CurrentYr * (1 - (CurrentYr/1000000));

Problem is I want to take the result of the formula, and plug it back into CurrentYr so it can continue looping. Right now it's just giving me the first unique answer (just user input), applying the formula for the second answer, and then just repeating that same answer instead of applying the answer to the next use of the formula.

EDIT: NVM, got it.
 

hateradio

The Most Dangerous Yes Man
After working on business-level C# and VB applications (web apps too!) I wanna move to PHP and expand my knowledge outside Microsoft stuff. I am pretty damn cozy developing in Visual Studio, and SQL Server Management and ASPX stuff but gotta move out of the comfort zone. Since I am here.... what are the best tools/IDE for PHP applications and is there an alternative to SQL Management Server?
I wouldn't recommend PHP since it's kinda amateurish when you compare it to other languages and systems.

There is no "best" IDE, but you can try NetBeans (free) or PHP Storm (not free, I think). For DB, you can probably use MySQL and MySQL Workbench.

If you want to play with PHP w/o actually installing everything at a time, I'd suggest using Uniform Server.
 

nitewulf

Member
what's the most efficient matching algorithm for matching values in two different columns in excel? initially i coded by looping through cell references, iterating through column A while holding Column B steady, finding a match, advancing in Column B and so on. it works for my purposes. but just for fun, i randomized 40,000 rows and tried my code...and it obviously took a long time. so next i tried doing it via arrays, throwing Column A into an array, and Column B into an array, then looping through the arrays. still pretty long.

is there actually any faster method of doing it? or is that always going to be a limitation of excel/vba?
 

tokkun

Member
what's the most efficient matching algorithm for matching values in two different columns in excel? initially i coded by looping through cell references, iterating through column A while holding Column B steady, finding a match, advancing in Column B and so on. it works for my purposes. but just for fun, i randomized 40,000 rows and tried my code...and it obviously took a long time. so next i tried doing it via arrays, throwing Column A into an array, and Column B into an array, then looping through the arrays. still pretty long.

is there actually any faster method of doing it? or is that always going to be a limitation of excel/vba?

Your approach is O(n^2). I'm no Excel expert, but I imagine it would support one of the following:

  • Sort both columns (O(n log n)). Then do matching on sorted lists (O(n)). Overall complexity: O(n log n)
  • Create a hash table using a 1-to-1 hashing function. For example, the hash of the value in column A represents a row number elsewhere in column A. Enter the original row number in the hashed row. Keep a list of all hashed rows. Repeat for column B. Then iterate through the list of hashed rows and see if that row has an entry in both column A & B. If so, you have a match. Complexity: O(n), but possibly high memory use (may use a lot of rows).
 

Water

Member
what's the most efficient matching algorithm for matching values in two different columns in excel?
- By "matching", do you mean "find the set of all values that are present somewhere in both columns"?
- Do you need to track which rows the value was found from?
- Can the same value exist on multiple rows in one column?
- Are the values decimal numbers or integers? If integers, are they from a small range or could they be any integer?

Tokkun's suggestions are how you should generally do this thing, but if more is known about the data, it may be possible to do better.
 
Top Bottom