• 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

Korosenai

Member
Just finished my programming 2 class, which was pretty much all things c++. All the basic stuff to pointers, vectors, classes, templates, recursion, linked lists.... and now I want to learn a new language over the Christmas break. What would be a good one? I already started Python and i'm already up to classes on that. Im thinking either java or c#.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Can anyone explain recursive methods in java to me like I'm five?
A recursive method is a method that calls itself as part of its execution. Usually there is some sort of termination condition so it doesn't go on forever.

For example, factorials are often represented as a recursive function in order to teach the concept.

5! = 5 * 4 * 3 * 2 * 1

Code:
public int fac(int num)
{
     if (num == 1)
          return;
     else
          return (num * fac(num -1));
}

If you work that out on a sheet of paper, you'll see that fac(5) keeps calling fac() until the parameter reaches 1, and then the call stack resolves in order to give 5 * 4 * 3 * 2 * 1, or 120.
 
Just finished my programming 2 class, which was pretty much all things c++. All the basic stuff to pointers, vectors, classes, templates, recursion, linked lists.... and now I want to learn a new language over the Christmas break. What would be a good one? I already started Python and i'm already up to classes on that. Im thinking either java or c#.

What do you want to do? What domains interest you?

C# is good for desktop apps. I'm actually not a fan of asp.net though. I prefer ruby or python for smaller web apps. For my big items, I like java for web apps. You want to do some cool web backend stuff in a managed language. I recommend learning Java and Scala + Play framework.
 

Kansoku

Member
Can anyone explain recursive methods in java to me like I'm five?

A recursive method is one that calls itself. Take these:

Code:
public void show1(int x){
	if(x>0){
		System.out.print(x+"+");
		show1(x-1);
	}	
}
If you cal this method with 5, for example, it will print 5+4+3+2+1+. However this code:
Code:
public void show2(int x){
	if(x>0){
		show2(x-1);
		System.out.println(x+"+");		
	}
}
Will print 1+2+3+4+5+.

The thing about recursive methods, it's to understand the return:
KMOVUT8.png

Sorry for the crude drawing.
It's like this, you open another instance of the method while you're in the middle of it, and everything that comes after the recursive call is "put on hold" until the instance you opened is finished. That's why it's really important to pay attention to the stop conditions and have a good grasp of the "going back" when the stop condition is met and you go back to finish the previous instances.
 

Gaz_RB

Member
A recursive method is a method that calls itself as part of its execution. Usually there is some sort of termination condition so it doesn't go on forever.
It's like this, you open another instance of the method while you're in the middle of it, and everything that comes after the recursive call is "put on hold" until the instance you opened is finished. That's why it's really important to pay attention to the stop conditions and have a good grasp of the "going back" when the stop condition is met and you go back to finish the previous instances.

Thank you guys, I think I'm starting to wrap my head around it. I'm stumped when it comes to using both strings and ints together though.

Here's the code and it's output:
Code:
public static void main(String [] args)   
 {        
       String answer = recur("Go! ",  3);        
                System.out.println(answer);            
  }

Output: Go! Go! Go!

I have to make the method, but I can't figure it out.

So far I have this:
Code:
public static int recur(String s, int i)
if(s==""||i==0){
            return System.out.println("Error.");
        }
            else{
            
                return recur(s, i-1);
                 
            }

I'm not quite grasping it. I can determine the output but I'm lost when trying to figure out the code from an output.

Edit: Think I got it. Thanks a lot guys, I've think I finally understand it both ways now. I just had to wrap my mind around the idea of how deep it can go, and what the return statements are meant to do.

Code:
public static String recur(String s, int i)
        {
           if(s==""||i==0){
            return ""; 
        }
            else{
                System.out.print(s);
                return recur(s, i-1);
                 
            }
 

Kansoku

Member
I'm not quite grasping it. I can determine the output but I'm lost when trying to figure out the code from an output

Code:
public String recur (String s, int i){
	String answer="";
	if(s==""){
        	answer="Error.";
        }else if(i>0){           
		answer=s+" "+recur(s, i-1);
	}
	return answer;
}

When i=0, it will return "". That's our stopping condition. The previous call (i=1) will make answer = "Go! " (with the space). The previous one (i=2), will pick that and add to answer, making it "Go! Go! ", the initial one (i=3) will make it "Go! Go! Go! ".

EDIT: Well, seems you got it :p
 

Korosenai

Member
What do you want to do? What domains interest you?

C# is good for desktop apps. I'm actually not a fan of asp.net though. I prefer ruby or python for smaller web apps. For my big items, I like java for web apps. You want to do some cool web backend stuff in a managed language. I recommend learning Java and Scala + Play framework.
I'm honestly not sure, just open to whatever. I just want to stay busy learning new languages. I might just stick with Python and keep learning more, and then expand to java and ruby.

Can anyone explain recursive methods in java to me like I'm five?

While we're talking about recursives, could someone explain to me how this comes out to equal 37? I'm kind of having problems with recursive functions myself.
Code:
int recursive (int n)
{
    if (n == 0 || n == 1)
    {
        return 2;
    }
    else
    {
        return recursive(n - 1) + recursive(n - 2) + 3;
    }
}

int main()
{
    cout << recursive(5) << endl;
}
 

Gaz_RB

Member
Code:
public String recur (String s, int i){
	String answer="";
	if(s==""){
        	answer="Error.";
        }else if(i>0){           
		answer=s+" "+recur(s, i-1);
	}
	return answer;
}

When i=0, it will return "". That's our stopping condition. The previous call (i=1) will make answer = "Go! " (with the space). The previous one (i=2), will pick that and add to answer, making it "Go! Go! ", the initial one (i=3) will make it "Go! Go! Go! ".

EDIT: Well, seems you got it :p

Actually yours is the correct answer, as it assigns "s" to String answer like I was supposed to. I was just simulating the answer instead of doing it right. Thanks again.
 

hateradio

The Most Dangerous Yes Man
I'm not 100% it matters with empty strings (since they probably have the same reference), but you should always use equals() when comparing strings in Java (or a similar method). In this case, isEmpty would work better.

Code:
if (s.isEmpty()) {
    answer = "Error.";
}
// etc
 
I'm not 100% it matters with empty strings (since they probably have the same reference), but you should always use equals() when comparing strings in Java (or a similar method). In this case, isEmpty would work better.

Code:
if (s.isEmpty()) {
    answer = "Error.";
}
// etc

Now, Java is not a language I have used professionally, but wouldn't this be susceptible to a NullPointerException? The variable "s" is an input to the method, and there's no validation in place around it.
 
I'm honestly not sure, just open to whatever. I just want to stay busy learning new languages. I might just stick with Python and keep learning more, and then expand to java and ruby.



While we're talking about recursives, could someone explain to me how this comes out to equal 37? I'm kind of having problems with recursive functions myself.
Code:
int recursive (int n)
{
    if (n == 0 || n == 1)
    {
        return 2;
    }
    else
    {
        return recursive(n - 1) + recursive(n - 2) + 3;
    }
}

int main()
{
    cout << recursive(5) << endl;
}

Step through it.

recursive(0) == 2
recursive(1) == 2
recursive(2) == recursive(1) + recursive(0) + 3
2 + 2 + 3 = 7
recursive(3) == recursive(2) + recursive(1) + 3
7 + 2 + 3 = 12
recursive(4) == recursive(3) + recursive(2) + 3
12 + 7 + 3 = 22
recursive(5) == recursive(4) + recursive(3) + 3
22 + 12 + 3 = 37

It helps to think, when doing recursion, what your base case is, and a couple steps away from your base case. in this case, since you return 2 when n == 0 or 1, that's a good place to start. You're adding the two previous numbers together with 3. You know that recursive(0) = 2 and recursive(1) = 2, so when you call recursive(2), it's just recursive(1) + recursive(0) + 3.
 

Korosenai

Member
Step through it.

recursive(0) == 2
recursive(1) == 2
recursive(2) == recursive(1) + recursive(0) + 3
2 + 2 + 3 = 7
recursive(3) == recursive(2) + recursive(1) + 3
7 + 2 + 3 = 12
recursive(4) == recursive(3) + recursive(2) + 3
12 + 7 + 3 = 22
recursive(5) == recursive(4) + recursive(3) + 3
22 + 12 + 3 = 37

It helps to think, when doing recursion, what your base case is, and a couple steps away from your base case. in this case, since you return 2 when n == 0 or 1, that's a good place to start. You're adding the two previous numbers together with 3. You know that recursive(0) = 2 and recursive(1) = 2, so when you call recursive(2), it's just recursive(1) + recursive(0) + 3.
Wow, thanks! Great explanation.

This was a program from our study guide. I knew what the answer was, by plugging it in, just had no idea how to get there. Thanks for the help.
 

Gaz_RB

Member
I'm having a real basic inheritance problem that seems like it could be simple.

Here's the Code:

Code:
public class Driver {      
    public static void main(String [] args)     
    {         
        Body b1 = new Body("Red", 32); 

        Arm arm = new Arm(4);  
    \
        Legs leg = new Legs(5);
 
        
        //Question one        
        System.out.println(arm.getBones());        
        //Question two        
        System.out.println(leg.getBones());       
        //Question  three       
        System.out.println(b1.getBones());      
        //Question four       
        System.out.println(leg.getType());   
        //Question five       
        System.out.println(arm.getType());   
        //Question six    
        System.out.println("num = " + Body.num);     } }

Code:
public class Body {    
    private String type;     
    protected int bones;     
    public static int num = 0;  
 public Body(String t, int r)    
 {         
     bones = r;     
     type = t;    
     num++;    

    }  public Body(int r)     
{     
        type = "AB";        
        bones = r;        
        num++;   
        
    }   
        public Body()    
        {       
            type="A-";     
            num++;    
            bones = 0; 
          }   
            public int getBones()    
            {      
                return ++bones;     
            }     
                public String getType()     
                {        
                    return type;      
                } }

Code:
public class Legs  extends Body {  
    public Legs (int r)     
    {             
        super(r);     } 
}

Code:
public class Arm extends Body {     
      String type;
    public Arm(int r)     
    {         
        type = "O+";   
        
    }     
    public int getBones()     
    {       
        return bones;     
    }  }

Code:
Output: 
0
6
33
AB
A-
num = 3

I understand everything but one little part in the driver- Why does this line:

System.out.println(arm.getType());

output A- and not O+ like it has been assigned?

Thanks for the help. Sorry for all the questions. I'm just trying to make sure I understand these things in and out before my java final coming up.
 

Hilbert

Deep into his 30th decade
I am trying to get back into C++, an I find myself having a problem with forward declarations and the like. Here is my stripped down example:


I have written this self cleaning list that I will call TidyList, which stores Objects *(as defined in Object.h.
Code:
#pragma once
#include "Object.h"

class TidyList
{

private:
  blah blah blah
	
public:
   Blah blah blah
};

However I would like Objects to have within themselves a tree of objects, and I would love to use my self cleaning list for this:

Code:
#pragma once
#include "TidyList.h"

class TidyList;

class Object
{
	protected:

	Object* parent_; //this object's parent
	TidyList children_;	//clear the list when deleting

public:
	blah blah blah
};

However above gives me an error when compiling in Object as undefined class "TidyList", and a whole lot of errors in Tidylist(things like expected ; )
I realized this is a circular dependency and is probably poor design. Anyone have a suggestion on how to fix this, or how I should redesign the relationships between these classes?
 

hateradio

The Most Dangerous Yes Man
Now, Java is not a language I have used professionally, but wouldn't this be susceptible to a NullPointerException? The variable "s" is an input to the method, and there's no validation in place around it.
"s" is still a string though. If it's empty, it's empty. There no exception. :p

edit: I see, if someone passes null then attempting to use "s" without asserting its validity would case any sort of error when attempting to use methods on "s". Still, it's not a good idea to use == on strings.
 

Slavik81

Member
However above gives me an error when compiling in Object as undefined class "TidyList", and a whole lot of errors in Tidylist(things like expected ; )
I realized this is a circular dependency and is probably poor design. Anyone have a suggestion on how to fix this, or how I should redesign the relationships between these classes?
There's no point including TidyList.h and then forward declaring it afterwards. The 'forward' declaration isn't very forward if it's done after the definition! It's just a redundant declaration at that point. You don't need the TidyList forward declaration in Object.h.

TidyList.h probably does not need the #include of Object.h. Move the #include to TidyList.cpp and just use a forward declaration of Object in TidyList.h. Whether that compiles for you depends on what 'blah blah blah' really is, but I suspect it will be ok.
 

Kansoku

Member
I understand everything but one little part in the driver- Why does this line:

System.out.println(arm.getType());

output A- and not O+ like it has been assigned?

Thanks for the help. Sorry for all the questions. I'm just trying to make sure I understand these things in and out before my java final coming up.

I'm not sure myself, because I didn't saw inheritance yet, but from what I've seen, you would need a super(type). IDK, but since Arm extends Body, when you create a new Arm, you create a new Body with the "empty" constructor, hence the A-; the getType() method is a method of the class Body, not Arm, so you get the type from the Body.

(http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
 
I'm not sure myself, because I didn't saw inheritance yet, but from what I've seen, you would need a super(type). IDK, but since Arm extends Body, when you create a new Arm, you create a new Body with the "empty" constructor, hence the A-; the getType() method is a method of the class Body, not Arm, so you get the type from the Body.

(http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
You're right.

This code:
Code:
public Arm(int r)     
    {         
        type = "O+";   
        
    }
is assigning "O+" to Arm's type member, but it doesn't override the getType() method, which is returning Body's type.

The correct method would be:
Code:
public Arm(int r) {
    super(r); // Calls Body's constructor to set the bones.
    setType("O+");
}

Also modify Body to have the setter:
Code:
public void setType(String t) {
    this.type = t;
}

The above will allow the subclasses to set the type on Body.
Then, remove the String type; from Arm, because it's already inheriting everything from Body. You only need to include things that you want to override (like you did with getBones, as its behaviour is different than Body's version), everything else is inherited and works just like the superclass.
 

Leonsito

Member
Anyone has experience with Android-iOS app and opening a sharing window on the Facebook app?

I'm a bit lost here, I found some methods that were valid until the last Facebook SDK update, like opening fb://publish/profile/me, but that doesn't work anymore :(
 

Gaz_RB

Member
I'm not sure myself, because I didn't saw inheritance yet, but from what I've seen, you would need a super(type). IDK, but since Arm extends Body, when you create a new Arm, you create a new Body with the "empty" constructor, hence the A-; the getType() method is a method of the class Body, not Arm, so you get the type from the Body.

(http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

Thanks again man. I didn't realize that you're actually making a new Body when you make an arm, and then getting the type of that body. Makes sense.
 
"s" is still a string though. If it's empty, it's empty. There no exception. :p

edit: I see, if someone passes null then attempting to use "s" without asserting its validity would case any sort of error when attempting to use methods on "s". Still, it's not a good idea to use == on strings.

There's very few reasons to use == on Strings in Java (or anything else that inherits from Object) but calling s.equals("") can also throw a NullPointerException if s is null. You could write a small function like isNullOrEmpty (a function like that actually exists in C#) that checks if s is null before calling equals.
 

Gaz_RB

Member
Can someone explain args[] to me? Is it like an array?
Code:
int arg[] = {0, 4, 6, 7}, x;                    
   for(x = arg.length; x>0; x++);                             
   System.out.println(--x);

I feel like this code would just churn out infinite 3s. What am I missing?

the output is:

Code:
2147483647
 

usea

Member
Can someone explain args[] to me? Is it like an array?
Code:
int arg[] = {0, 4, 6, 7}, x;                    
   for(x = arg.length; x>0; x++);                             
   System.out.println(--x);

I feel like this code would just churn out infinite 3s. What am I missing?

the output is:

Code:
2147483647
You have a semicolon after the for statement. The print statement is not part of the loop. The loop has no body. The for loop runs, executing `x++` until x is not greater than zero. That happens when it overflows and wraps around to the most negative number int can represent (-2147483648). Then, after the loop ends, you decrement x by 1 (--x) and then print it. `(-2147483648) - 1 = 2147483647`

2147483647 is the biggest signed 32-bit integer value.

That code's style problems are causing logic errors because it makes certain things easy to overlook. The random indents are making it hard to read. Always use curly braces for loops, ifs, etc. Put your loop variable initialization inside the loop. Personally I'd never declare those two variables on the same line, and I'd never declare a variable without assigning to it. `int x;` is just asking for trouble, imo.

Details are important. The code should probably be something like this:
Code:
int arg[] = {0, 4, 6, 7};
for(int x = arg.length; x > 0; x++) {
    System.out.println(--x);
}

FYI to answer your question, `args` is just the variable name of an int array. It doesn't change the behavior at all. You could change it to `waffle` and the code would be exactly the same.
 

Chris R

Member
Project Euler was fun, but I'm slowly getting further away from "programming" questions and closer to pure math questions. Bah.
 

GabDX

Banned
Project Euler was fun, but I'm slowly getting further away from "programming" questions and closer to pure math questions. Bah.

How many problem have you solved? I'm at 45 now. I don't mind the more math oriented questions. It's no fun when you can just rely on brute force the find the answer.

Which language are you using? It's mostly Python for me.
 

Chris R

Member
How many problem have you solved? I'm at 45 now. I don't mind the more math oriented questions. It's no fun when you can just rely on brute force the find the answer.

Which language are you using? It's mostly Python for me.

Only 63 problems (first 50 and then a scattering beyond that) and I'm using c#.

I've not had to brute force anything so far, but I've needed to refine a few of the helper functions I made for prime factorization/detection because they became too slow above 5 million.
 

Gaz_RB

Member
You have a semicolon after the for statement. The print statement is not part of the loop. The loop has no body. The for loop runs, executing `x++` until x is not greater than zero. That happens when it overflows and wraps around to the most negative number int can represent (-2147483648). Then, after the loop ends, you decrement x by 1 (--x) and then print it. `(-2147483648) - 1 = 2147483647`

2147483647 is the biggest signed 32-bit integer value.

That code's style problems are causing logic errors because it makes certain things easy to overlook. The random indents are making it hard to read. Always use curly braces for loops, ifs, etc. Put your loop variable initialization inside the loop. Personally I'd never declare those two variables on the same line, and I'd never declare a variable without assigning to it. `int x;` is just asking for trouble, imo.

Details are important. The code should probably be something like this:
Code:
int arg[] = {0, 4, 6, 7};
for(int x = arg.length; x > 0; x++) {
    System.out.println(--x);
}

FYI to answer your question, `args` is just the variable name of an int array. It doesn't change the behavior at all. You could change it to `waffle` and the code would be exactly the same.

Thank you man. I'm extremely new at this, and that was very helpful.
 

trulsnes

Neo Member
Project Euler was fun, but I'm slowly getting further away from "programming" questions and closer to pure math questions. Bah.
Try onlinejudge.org for more 'real life' algorithmic problems. "Programming Challenges (Skiena & Revilla)" is a good starting point
 
Anyone have any suggestions of a free stock quote web service/API?

A client wants their last trade price/date on their website. They don't trade in high volume whatsoever, less than once a month on average.

Originally we used iGoogle's feeds to get the data and this worked great. However, when iGoogle was discontinued, I switched over to Yahoo's APIs, but that seems to be returning inaccurate information as to the date of the trade. The customer is complaining that the dates that are getting returned are incorrect.

Anyone know of any free alternatives?
 
There's very few reasons to use == on Strings in Java (or anything else that inherits from Object) but calling s.equals("") can also throw a NullPointerException if s is null. You could write a small function like isNullOrEmpty (a function like that actually exists in C#) that checks if s is null before calling equals.
"".equals(s)

You're welcome!
 

Shearie

Member
Man I suck so much at this programming stuff :(

So I'm at exercise 43 in "Learn Python the Hard Way" and we're supposed to make a text adventure game using the the things we learned so far but first I'm just trying to figure out how the example game in the lesson works.

Code:
class Engine(object):

	def __init__(self, scene_map):
		self.scene_map = scene_map
		
	def play(self):
		current_scene = self.scene_map.opening_scene()
		
		while True:
			print "\n--------"
			next_scene_name = current_scene.enter()
			current_scene = self.scene_map.next_scene(next_scene_name)


class Map(object):

	scenes = {
		'central_corridor': CentralCorridor(),
		'laser_weapon_armory': LaserWeaponArmory(),
		'the_bridge': TheBridge(),
		'escape_pod' : EscapePod(),
		'death': Death()
	}

	def __init__(self, start_scene):
		self.start_scene = start_scene
		
	def next_scene(self, scene_name):
		return Map.scenes.get(scene_name)
		
	def opening_scene(self):
		return self.next_scene(self.start_scene)


a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()

There's more code to this but these 2 classes are driving me MAD!!!!! MAD I TELL YOU!!!!!!!!!!!! Can anyone give me a step by step breakdown of what's going on after "a_game.play()" is executed?
 

maeh2k

Member
Man I suck so much at this programming stuff :(

So I'm at exercise 43 in "Learn Python the Hard Way" and we're supposed to make a text adventure game using the the things we learned so far but first I'm just trying to figure out how the example game in the lesson works.

Code:
class Engine(object):

	def __init__(self, scene_map):
		self.scene_map = scene_map
		
	def play(self):
		current_scene = self.scene_map.opening_scene()
		
		while True:
			print "\n--------"
			next_scene_name = current_scene.enter()
			current_scene = self.scene_map.next_scene(next_scene_name)


class Map(object):

	scenes = {
		'central_corridor': CentralCorridor(),
		'laser_weapon_armory': LaserWeaponArmory(),
		'the_bridge': TheBridge(),
		'escape_pod' : EscapePod(),
		'death': Death()
	}

	def __init__(self, start_scene):
		self.start_scene = start_scene
		
	def next_scene(self, scene_name):
		return Map.scenes.get(scene_name)
		
	def opening_scene(self):
		return self.next_scene(self.start_scene)


a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()

There's more code to this but these 2 classes are driving me MAD!!!!! MAD I TELL YOU!!!!!!!!!!!! Can anyone give me a step by step breakdown of what's going on after "a_game.play()" is executed?

So the game (engine) is set up using the scene map defined in Map with the start_scene 'central_corridor'. Then play() is called. The current_scene is set to 'central_corridor' and then the game loop starts (as in the is being played). While the game is still running, it will first print the ----s, then it will enter() the current_scene (in the first iteration that's 'central_corridor', and then it will load the next scene.
So for every scene such as CentralCorridor you have a method enter() that starts the scene and that returns which scene is next. After 'central_corridor', the next scene becomes the current_scene. Then the loop starts again.
 

moka

Member
Has anyone here used bootstrap?

I've used Bootstrap extensively in the past but it's changed so much recently. I'd need to get to grips with it again by reading the docs.

Can anyone explain recursive methods in java to me like I'm five?

Man, I really didn't get recursion at all when I was first introduced to it but then I started doing Haskell in my functional programming classes and did nothing but recursion for ages and it just clicked for me.

I like Kansoku's explanation though.

Anyone have any suggestions of a free stock quote web service/API?

A client wants their last trade price/date on their website. They don't trade in high volume whatsoever, less than once a month on average.

Originally we used iGoogle's feeds to get the data and this worked great. However, when iGoogle was discontinued, I switched over to Yahoo's APIs, but that seems to be returning inaccurate information as to the date of the trade. The customer is complaining that the dates that are getting returned are incorrect.

Anyone know of any free alternatives?

See if these links amount to anything:

http://dev.markitondemand.com/
http://www.xignite.com/product/global-stock-quote-data/api/GetGlobalDelayedQuote/

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

Anyway guys, first semester of my second year at uni is finally over and I'm bored. Any ideas? I've made a few industrial placement applications but they take so long and I'm tired of answering competency questions.
 

diaspora

Member
RE: C

The gcd_lcm function is supposed to be recursive, basically I have to run the function within itself to acquire the GCD (greatest common denominator, the modulus of factor 1 and factor 2), as well as the LCM. I'm not sure how I ought to go about this though. The following compiles but it gets a segmentation fault.

Code:
#include<stdio.h>

void gcd_lcm(int factor1, int factor2, int gcd, int lcm);
int firstfactor();
int secondfactor();

int main()
{
int f1 = firstfactor();
int f2 = secondfactor();
gcd_lcm(f1, f2, 0, 0);
return 0;
}

int firstfactor()
{
int fac1;
char l;
printf("Enter Factor1");

while(scanf("%d%c",&fac1,&l) != 2)
{
    printf("\nPlease enter an integer only : ");
    scanf("%c",&l);
}
if(fac1 < 0)
{
printf("\nPlease enter a positive integer only: ");
while(scanf("%d%c",&fac1,&l) != 2)
{
    printf("\nPlease enter a positive integer only : ");
    scanf("%c",&l);
}
}

return fac1;
}

int secondfactor()
{
int fac2;
char l;
printf("Enter Factor2");

while(scanf("%d%c",&fac2,&l) != 2)
{
    printf("\nPlease enter an integer only : ");
    scanf("%c",&l);
}
if(fac2 < 0)
{
printf("\nPlease enter a positive integer only: ");
while(scanf("%d%c",&fac2,&l) != 2)
{
    printf("\nPlease enter a positive integer only : ");
    scanf("%c",&l);
}
}

return fac2;
}

void gcd_lcm(int factor1, int factor2, int gcd, int lcm)
{
    gcd_lcm(factor1, factor2, factor1%factor2, factor1*factor2 / factor1%factor2);

    printf("The GCD of %d and %d is %d. The LCM is %d.",factor1,factor2,gcd,lcm);
}
 

tuffy

Member
RE: C

The gcd_lcm function is supposed to be recursive, basically I have to run the function within itself to acquire the GCD (greatest common denominator, the modulus of factor 1 and factor 2), as well as the LCM. I'm not sure how I ought to go about this though. The following compiles but it gets a segmentation fault.
Recursive function calls in C need some sort of stop condition in order to end the recursion. In this instance, "gcd_lcm" just keeps calling itself forever until your program runs out of stack space and explodes. You'll need to add a check to stop that from happening.
 

L034

Member
I've never used a CSS framework before so I'm wondering is it worthwhile to learn it or to look for an alternative framework.

I find it totally worthwhile as just by using the examples on their site and adapting them, I was able to offload 90% of the CSS and Javascript work (for dropdowns or carousels) onto bootstrap. Moreover, from version 3 onwards, it is made for mobile too.
 

diaspora

Member
Recursive function calls in C need some sort of stop condition in order to end the recursion. In this instance, "gcd_lcm" just keeps calling itself forever until your program runs out of stack space and explodes. You'll need to add a check to stop that from happening.

I can't use breaks, so perhaps a do/while.

edit: so now I've got this which still breaks.

Code:
#include<stdio.h>

void gcd_lcm(int factor1, int factor2, int *gcd, int *lcm);
int firstfactor();
int secondfactor();
int gcm(int factor1, int factor2);

int main()
{
	int f1 = firstfactor();
	int f2 = secondfactor();
	if(f1 < f2)
	{
		printf("The second factor has to be less than the first.");
	}
	
	int gcdenom, cmulti;
	gcd_lcm(f1, f2, &gcdenom, &cmulti);
	return 0;
}

int firstfactor()
{
	int fac1;
	char l;
	printf("Enter Factor1 ");

	while (scanf("%d%c", &fac1, &l) != 2)
	{
		printf("\nPlease enter an integer only : ");
		scanf("%c", &l);
	}
	if (fac1 < 0)
	{
		printf("\nPlease enter a positive integer only: ");
		while (scanf("%d%c", &fac1, &l) != 2)
		{
			printf("\nPlease enter a positive integer only : ");
			scanf("%c", &l);
		}
	}

	return fac1;
}

int secondfactor()
{
	int fac2;
	char l;
	printf("Enter Factor2 ");

	while (scanf("%d%c", &fac2, &l) != 2)
	{
		printf("\nPlease enter an integer only : ");
		scanf("%c", &l);
	}
	if (fac2 < 0)
	{
		printf("\nPlease enter a positive integer only: ");
		while (scanf("%d%c", &fac2, &l) != 2)
		{
			printf("\nPlease enter a positive integer only : ");
			scanf("%c", &l);
		}
	}

	return fac2;
}

void gcd_lcm(int factor1, int factor2, int *gcd, int *lcm)
{
	*gcd = factor1 % factor2;
	if (gcd > 0)
	{
		gcd_lcm(factor1 = factor2, factor2 = *gcd, gcd, lcm);
	}
}

I figured it'd stop looping once gcd hit 0?

edit again: The function is supposed to be as is, we can't change the parameters or function type. So then... how would I return a value for the if statement to work?
 

Splatt

Member
I find it totally worthwhile as just by using the examples on their site and adapting them, I was able to offload 90% of the CSS and Javascript work (for dropdowns or carousels) onto bootstrap. Moreover, from version 3 onwards, it is made for mobile too.

Cool.

Thanks :)
 

GabDX

Banned
I'm trying to optimize my code a bit. Using only the standard library, I want to make a matrix in both Python and C++. I see two possibilities in both.

In Python, I can make a list of lists (M2) or a single long list (M1). Initializing M2 is faster.

Code:
nrow = 1000
ncol = 1000

M1 = [0 for n in range(nrow*ncol)]
for i in range(nrow):
    for j in range(ncol):
        M1[i*ncol + j] = i + j

M2 = [[0 for n in range(ncol)] for m in range(nrow)]
for i in range(nrow):
    for j in range(ncol):
        M2[i][j] = i + j

If I do something similar in C++, using vectors, the single long vector is more efficient than the vector of vectors.

Code:
    const int ncol = 20000;
    const int nrow = 20000;

    vector<double> M1 = vector<double>(ncol*nrow);
    for (int i=0; i < nrow; i++) {
        for (int j=0; j < ncol; j++) {
            M1[i*ncol + j] = i + j;
        }
    }

    vector<vector<double> > M2 
        = vector<vector<double> >(nrow, vector<double>(ncol));
    for (int i=0; i < nrow; i++) {
        for (int j=0; j < ncol; j++) {
            M2[i][j] = i + j;
        }
    }

Why is that? I though that a single long list or vector would be better but this is not true in Python. Why?
 

diaspora

Member
Sounds sensible enough, but "if (gcd > 0)" needs to be "if (*gcd > 0)", otherwise it won't be comparing what you want it to.

You're RIGHT! Code has improved- it actually works perfectly, but the only thing I need now is to figure out how to get an integer scanf for the inputs to reject floats.
 
I find it totally worthwhile as just by using the examples on their site and adapting them, I was able to offload 90% of the CSS and Javascript work (for dropdowns or carousels) onto bootstrap. Moreover, from version 3 onwards, it is made for mobile too.

I agree, it's pretty great for easily getting a really nice looking site out there. I don't have great design sense, but without a lot of effort I can get a Bootstrapped site working that looks pretty nice (if somewhat generic). This lets me focus more of my time on stuff that I'm more interested in.
 
Top Bottom