• 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

Garantee, probably not (there's too many examples even with companies), but at least you have the possibility to defend yourself. So I think it's needed.

That is what I tried to address with the unless part of that first sentence. :)

Nowadays, even businesses that aren't particularly wise about technology know about the risks of using GPLed code. For Fortune 500, there's typically an approval process to use other people's open source code that runs through their own legal department, and using GPL in that case is a calculated risk.

[EDIT: Took out some hearsay that I did not see first hand.]

If anything, I think tech businesses have gotten too wise to skating about the GPL for it to be useful against unauthorized use. BSD does guarantee at least some public form of credit, and honestly I'm not as sympathetic with Stallman's political motivations behind copyleft as I was when I was younger.

YMMV, totally. I'm merely speaking as an individual here.

[EDIT: I am also not a lawyer. The advice in this post should not be taken as representative of my own views at this time. It is also not representative of the views of any one of my employers past or present.

My current views of the GPL are quite a bit more positive than before, now that I understand more about its broader use and common practices.]
 

Koren

Member
If anything, I think tech businesses have gotten too wise to skating about the GPL for it to be useful against unauthorized use. BSD does guarantee at least some public form of credit, and honestly I'm not as sympathetic with Stallman's political motivations behind copyleft as I was when I was younger.
I'm not overly fond of GPL myself, sometimes.

For example, I'm sometimes reluctant to release source code for work-in-progress programs I develop (at least as long as I'm still in the process of changing a couple of things like data structures, and as long as I'm not satisfied with the tidyness of my sources), but I still want to be able to distribute them to gather some users' comments. GPL make this a nightmare, even if I want to open the sources at the end.
 
Anyone know how I would read a text file such as the one below:

Code:
4
5
12	69	68	30	83	
31	63	24	68	36	
30	3	23	59	70	
68	94	57	12	43

and put into an matrix in C? The top two digits are the matrix dimensions (4x5) while the integers below it are the entire matrix. I'm trying to use fscanf but that doesn't register end of line to my knowledge.

Oh and thx Koren for helping me out earlier, I decided to scrap the function call and just do it all in main().
 

Massa

Member
That's a disadvantage of using cygwin imo, because it lures you into a false sense of portability that incidentally also performs like garbage on Windows since it tries to mimic posix semantics under a threading model that doesn't lend itself well to that. That's the problem with cygwin in general. It makes it too easy to produce crap.

threading support was added to the c++ standard library for a reason, that's what people should be using.

It's rare anymore to find places where C++ is banned and everything must be strict C

Is there anything that hasn't been added to the C++ standard? ;)
 

LegatoB

Member
Anyone know how I would read a text file such as the one below:

Code:
4
5
12	69	68	30	83	
31	63	24	68	36	
30	3	23	59	70	
68	94	57	12	43

and put into an matrix in C? The top two digits are the matrix dimensions (4x5) while the integers below it are the entire matrix. I'm trying to use fscanf but that doesn't register end of line to my knowledge.

Oh and thx Koren for helping me out earlier, I decided to scrap the function call and just do it all in main().
If you know the dimensions of the matrix -- the format of your input -- you don't particularly need to care about catching newlines for this application. You know you have four lines of input (rows) of five values (columns) each. Loops!
 
If you know the dimensions of the matrix -- the format of your input -- you don't particularly need to care about catching newlines for this application. You know you have four lines of input (rows) of five values (columns) each. Loops!

The matrix is user-generated to which I've a program that generates said matrix in the exact way as shown in the example. The user also defines the dimensions according to those two top values.
 

Koren

Member
Is there anything that hasn't been added to the C++ standard? ;)
I'm pretty sure that the Python "standard" library cover far more things, to a point that's not really standard anymore (especially when you have half a dozen ways to do something).

The matrix is user-generated to which I've a program that generates said matrix in the exact way as shown in the example. The user also defines the dimensions according to those two top values.
You definitively need memory allocation...

In short (I'm in a hurry, unfortunately)

Read the two first arguments into int rows and cols, as usual with fscanf, for example

Then declare the table... If you can use C++ X11, a simple solution :
Code:
auto my_array = new int[rows][cols]()

(or without () if you prefer)

Then read each line from the file in a string, then use split() to cut it into pieces, and convert the pieces to ints so that you can fill your array.
 

LegatoB

Member
The matrix is user-generated to which I've a program that generates said matrix in the exact way as shown in the example. The user also defines the dimensions according to those two top values.
Is there a reason why you want to specifically read in a line at a time, rather than processing individual values? scanf "breaks" input on blank spaces, newlines, etc. if you tell it to look for a number, and since you're already reading in the dimensions of the matrix, a couple of simple loops will do the trick.
 
And should I find a software that use pthreads, compiling it with some posix compatibility layer is easier than rewriting it to support a different kind of threads...
Easier usually doesn't mean better though.

Yes, it use an akward layer between POSIX semantics and Windows, but in some cases, I still find it handy to have this solution available. Most of the time, performances won't really be a huge issue anyway.

I'll be the first to admit that I'm biased, but I would say it's not a solution at all, but rather a workaround. And not even a good workaround, since a better and easier one is to simply use std::thread.

Is there anything that hasn't been added to the C++ standard? ;)
I know you're joking, but since I can't help myself:

Process control, unicode conversions, coroutines (coming most likely in C++17 though), shared memory and IPC, transactional memory, sockets/networking, and more :)

That said, I think it's amazing what's happening with C++ over the last 5 years. The improvements they've made to the language and to the standard library are really great and just what the language needed.
 

Slavik81

Member
Is there anything that hasn't been added to the C++ standard? ;)
Even with the recent additions in C++11 and C++14, the C++ standard library is tiny compared to that of most modern languages. Look at Python. It has a package manager, a tar library, a zip file library, an argument parser, Unicode support, a webserver, cryptographic tools, a curses library, decimals, a diffing library, multiple serialization libraries, sockets, sqlite, ssl, uuids, turtle drawing, wav audio playback, xml and json parsing...

Though perhaps more directly relevant to the topic at hand, I found it a little annoying to try to work with long-lived threads using just std::thread and friends. It's great if your task is large enough to kick up new threads each time you want to use them, but the C++ standard library is a little lacking in synchronization primitives. Of course, if you're willing to spend the time, you can probably build your own fancy stuff on top.

I found POSIX barriers to be incredibly simple to use for adding multi-threading to my fluid simulation. They let me skip breaking my program down into tasks and instead just line all my horses up in parallel tracks, then let them race to the finish. Rinse and repeat a few hundred times a second. Not a perfect parallelization solution, but really, really easy.
 

Hypron

Member
Can't help you directly, but if I understand well what you're doing, I can confirm it's possible, I've help a colleague doing something like this two years ago.

Thanks! My laboratory has this two-wheeled balancing robot (made out of segway parts) that's currently controlled by compiled Simulink code running on an expensive on-board PC. Our main issue is that no one really knows how to use it anymore since the PhD student who used it left (it's using a fairly obscure MATLAB toolbox — the only resource for it is the documentation).

My supervisor and I are looking at modifying the robot to make it easier to use, debug and repair (for example, some undergraduate students will work on it next year and we want them to concentrate on the control systems issues instead of having to spend forever to learn how the hardware works). Using LabVIEW and something like a myRIO would be great because our lab technicians (and other students) are quite knowledgeable about it, whereas they don't know much about Simulink. On the other hand Simulink's simulation features are still quite a bit better than LabVIEW's and most lecturers are more proficient using it.

So it's good to hear that it's possible to integrate the two systems together. I'll definitely investigate that a bit further to see how much work it'd be to move our current low-level interfacing code to LabVIEW and set up that link with Simulink.
 
Lots of academic environments. E.g. the person asking for matrix help at the moment :p

His assignment he posted specifically said c++ was ok

Anyway in an academic environment you usually aren't worried about writing portable code (although that's still no excuse for not using the features provided to you by the language)
 
Even with the recent additions in C++11 and C++14, the C++ standard library is tiny compared to that of most modern languages. Look at Python. It has a package manager, a tar library, a zip file library, an argument parser, Unicode support, a webserver, cryptographic tools, a curses library, decimals, a diffing library, multiple serialization libraries, sockets, sqlite, ssl, uuids, turtle drawing, wav audio playback, xml and json parsing...

Though perhaps more directly relevant to the topic at hand, I found it a little annoying to try to work with long-lived threads using just std::thread and friends. It's great if your task is large enough to kick up new threads each time you want to use them, but the C++ standard library is a little lacking in synchronization primitives. Of course, if you're willing to spend the time, you can probably build your own fancy stuff on top.

I found POSIX barriers to be incredibly simple to use for adding multi-threading to my fluid simulation. They let me skip breaking my program down into tasks and instead just line all my horses up in parallel tracks, then let them race to the finish. Rinse and repeat a few hundred times a second. Not a perfect parallelization solution, but really, really easy.
Python does not have a standard.
 

Koren

Member
Anyone know how I would read a text file such as the one below:

Code:
4
5
12	69	68	30	83	
31	63	24	68	36	
30	3	23	59	70	
68	94	57	12	43

and put into an matrix in C? The top two digits are the matrix dimensions (4x5) while the integers below it are the entire matrix. I'm trying to use fscanf but that doesn't register end of line to my knowledge.

Oh and thx Koren for helping me out earlier, I decided to scrap the function call and just do it all in main().
I hadn't time yesterday evening, but I found some this morning... My previous solution was a bit misleading (forgot that C++ doesn't support well variable length arrays), so here is a suggestion to create a structure that works like a normal 2D array, but for which you can define the dimensions.

It expects you can trust the file content to be correct, though, since it "eats" the values without looking for newlines.
Code:
#include <string>
#include <iostream>
#include <fstream>
#include <memory>

typedef unsigned int uint;
					
class c2DIntMatrix {
    protected:
		uint _nrows, _ncols;
		std::unique_ptr<int[]> data;

	public:
		c2DIntMatrix(const uint nrows, const uint ncols) : _nrows(nrows), _ncols(ncols)
			{ data = std::unique_ptr<int[]>(new int[nrows*ncols]); }
		
		uint nrows() const { return _nrows; }
		uint ncols() const { return _ncols; }
		
		int* operator[](const uint row) { return data.get() + row*_ncols; }
};

int main(int argc, char* argv[]) {
	std::ifstream f;
	
	// Open the file
	f.open("A.txt");
	if (!f.is_open()) return -1;
	
	// Read number of rows and columns
	int nrows, ncols;	
	f >> nrows >> ncols;	
	
	// Create the 2D matrix
	c2DIntMatrix m(nrows, ncols);
	
	// Read the values
	for(int r=0; r<nrows; ++r) {
		for(int c=0; c<ncols; ++c) {
			f >> m[r][c];
		}
	}
	
	// Write the results, to test the program
	for(int r=0; r<nrows; ++r) {
		for(int c=0; c<ncols; ++c) {
			std::cout << m[r][c] << " \t";
		}
		std::cout << std::endl;
	}
	
	f.close();	
}


That's a lot of C++, though.

In pure C, it'll be more difficult to do. You should probably create a 1D table to contain the 2D one, by allocating it like that~:
Code:
int* m = (int*) malloc( sizeof(int) * ncols * nrows );

Then access the item at row r and col c by
Code:
table[r * ncols + c]

Then, at the end,
Code:
free(table)

It'll probably better this way...

If you REALLY want to be able to write m[r][c], you could do this~:
Code:
int* data = (int*) malloc( sizeof(int) * ncols * nrows );
int** m = (int**) malloc( sizeof(int*) * nrows );
for(int i=0; i<nrows; ++i)
    m[i] = data + ncols*i

This way, data will contain the values in a 1D array, but m will contain pointers to the beginning of each row, which will provides you the behavior you could expect.

Makes things slightly easier to manage, but remember you'll need to free *both* data and m at the end. It's easy to forget to free data alongside m.

Easier usually doesn't mean better though.
Usually not... But when I need a program to run, I don't care about developping it further, and I'm not too bothered with a lack of performance, it is...

That said, I think it's amazing what's happening with C++ over the last 5 years. The improvements they've made to the language and to the standard library are really great and just what the language needed.
I agree, but it was really needed. I was using more and more D, but I'm doing C++ again now.

It's still awfully akward at times, because all those improvements are added on a language that didn't expected them...
 

Water

Member
I hadn't time yesterday evening, but I found some this morning... My previous solution was a bit misleading (forgot that C++ doesn't support well variable length arrays), so here is a suggestion to create a structure that works like a normal 2D array, but for which you can define the dimensions.
I don't see the point of defining a special data structure when there are no special data layout or other requirements. vector<vector<int>> is standard.
 
I hadn't time yesterday evening, but I found some this morning... My previous solution was a bit misleading (forgot that C++ doesn't support well variable length arrays), so here is a suggestion to create a structure that works like a normal 2D array, but for which you can define the dimensions.

It expects you can trust the file content to be correct, though, since it "eats" the values without looking for newlines.
Code:
#include <string>
#include <iostream>
#include <fstream>
#include <memory>

typedef unsigned int uint;
					
class c2DIntMatrix {
    protected:
		uint _nrows, _ncols;
		std::unique_ptr<int[]> data;

	public:
		c2DIntMatrix(const uint nrows, const uint ncols) : _nrows(nrows), _ncols(ncols)
			{ data = std::unique_ptr<int[]>(new int[nrows*ncols]); }
		
		uint nrows() const { return _nrows; }
		uint ncols() const { return _ncols; }
		
		int* operator[](const uint row) { return data.get() + row*_ncols; }
};

int main(int argc, char* argv[]) {
	std::ifstream f;
	
	// Open the file
	f.open("A.txt");
	if (!f.is_open()) return -1;
	
	// Read number of rows and columns
	int nrows, ncols;	
	f >> nrows >> ncols;	
	
	// Create the 2D matrix
	c2DIntMatrix m(nrows, ncols);
	
	// Read the values
	for(int r=0; r<nrows; ++r) {
		for(int c=0; c<ncols; ++c) {
			f >> m[r][c];
		}
	}
	
	// Write the results, to test the program
	for(int r=0; r<nrows; ++r) {
		for(int c=0; c<ncols; ++c) {
			std::cout << m[r][c] << " t";
		}
		std::cout << std::endl;
	}
	
	f.close();	
}


That's a lot of C++, though.

In pure C, it'll be more difficult to do. You should probably create a 1D table to contain the 2D one, by allocating it like that~:
Code:
int* m = (int*) malloc( sizeof(int) * ncols * nrows );

Then access the item at row r and col c by
Code:
table[r * ncols + c]

Then, at the end,
Code:
free(table)

It'll probably better this way...

If you REALLY want to be able to write m[r][c], you could do this~:
Code:
int* data = (int*) malloc( sizeof(int) * ncols * nrows );
int** m = (int**) malloc( sizeof(int*) * nrows );
for(int i=0; i<nrows; ++i)
    m[i] = data + ncols*i

This way, data will contain the values in a 1D array, but m will contain pointers to the beginning of each row, which will provides you the behavior you could expect.

Makes things slightly easier to manage, but remember you'll need to free *both* data and m at the end. It's easy to forget to free data alongside m.


Usually not... But when I need a program to run, I don't care about developping it further, and I'm not too bothered with a lack of performance, it is...


I agree, but it was really needed. I was using more and more D, but I'm doing C++ again now.

It's still awfully akward at times, because all those improvements are added on a language that didn't expected them...

If you just need it to run, std::thread is still a better choice because it takes 1/5 the code to get it running. Literally 2 lines. One to create a std::thread object, one to join on it. Put them on the same line and it even fits in 80 columns.
 

Koren

Member
I don't see the point of defining a special data structure when there are no special data layout or other requirements. vector<vector<int>> is standard.
Let's say I'm not fond of the idea of creating thousands of vector<int> for storing a large matrix when I can allocate a single memory chunk for the whole matrix.


Philosophically, I don't like much vector<vector<int>> for a matrix where lines should have the same length.

But I agree the advantages are really slim, till you try to go a bit further and try to define a copy, for example.

It's not as if the structure is huge, either. You don't need to define accessors, and if you want to prepare the right size
Code:
vector<vector<int>> m(p, vector<int>(q))
isn't the nicest to me, and you'll perform the initialization twice.
 

Koren

Member
If you just need it to run, std::thread is still a better choice because it takes 1/5 the code to get it running. Literally 2 lines. One to create a std::thread object, one to join on it. Put them on the same line and it even fits in 80 columns.
I was talking about existing code to compile, with signalling, not writing a new program.
 
Let's say I'm not fond of the idea of creating thousands of vector<int> for storing a large matrix when I can allocate a single memory chunk for the whole matrix.


Philosophically, I don't like much vector<vector<int>> for a matrix where lines should have the same length.

But I agree the advantages are really slim, till you try to go a bit further and try to define a copy, for example.

It's not as if the structure is huge, either. You don't need to define accessors, and if you want to prepare the right size
Code:
vector<vector<int>> m(p, vector<int>(q))
isn't the nicest to me, and you'll perform the initialization twice.

You might be interested in N3851

Btw, if you know the dimensions at compile time a multi dimensional std::array is a reasonable workaround.
 
You can still allocate space on the stack any time *inside* the function... You could technically perform the first cout call, for example, before reserving stack for j.

One thing I forgot to mention is that just taking the address of a local variable is not sufficient to mandate the compiler allocate stack space for it. It's only necessary if the address escapes the function. (i.e. you pass it to an external call, or basically anything where the compiler does not have control over how the address is used).

If the address doesn't escape the function, the compiler can keep it in the register the whole time, and it can generate code that just uses register operations everywhere the the address is used.

Also, allocating stack space in the middle of the function is only a valid thing to do if the function does not have FPO enabled. By extension, if the compiler decides it's going to do this (allocate stack space in the middle of the function), then it has to disable FPO for that function as well. The same applies when calling the C API alloca(), for the same reason.
 

Water

Member
Let's say I'm not fond of the idea of creating thousands of vector<int> for storing a large matrix when I can allocate a single memory chunk for the whole matrix.
The example given was a 4x5 matrix, and it seemed to me like this was an intro to C++ sort of problem. If that's the case, then not only is performance irrelevant in this scenario (as it is in most other scenarios), but a simple vector-based solution is probably more relevant for a beginner than writing custom classes with unique_ptrs and operator[]:s.

Even if this was about matrices with dimensions in the 1000s, the optimization should start from considering the expected operations on the data, followed by profiling.
 

SOLDIER

Member
Latest assignment requires me to take the previous Python code I created:

Code:
def main():
    rainfall = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    high_rainfall = 0.0
    low_rainfall = 0.0
    total_rainfall = 0.0
    average_rainfall = 0.0

    rainfall[0]=int(input("Enter the rainfall for January: "))

    rainfall[1]=int(input("Enter the rainfall for February: "))

    rainfall[2]=int(input("Enter the rainfall for March: "))

    rainfall[3]=int(input("Enter the rainfall for April: "))

    rainfall[4]=int(input("Enter the rainfall for May: "))

    rainfall[5]=int(input("Enter the rainfall for June: "))

    rainfall[6]=int(input("Enter the rainfall for July: "))

    rainfall[7]=int(input("Enter the rainfall for August: "))

    rainfall[8]=int(input("Enter the rainfall for September: "))

    rainfall[9]=int(input("Enter the rainfall for October: "))

    rainfall[10]=int(input("Enter the rainfall for November: "))

    rainfall[11]=int(input("Enter the rainfall for December: "))

    high_rainfall = (max(rainfall))

    print ("The highest rainfall is: " +str(high_rainfall))

    low_rainfall = (min(rainfall))

    print ("The lowest rainfall is: " +str(low_rainfall))

    total_rainfall = (sum(rainfall))

    print ("The total rainfall is: " +str(total_rainfall))

    average_rainfall = (sum(rainfall)/len(rainfall))

    print ("The average rainfall is: " +str(average_rainfall))

main()

and enhance it so that it sorts the array in ascending and descending orders, and also display the values it contains.

This should be something I can figure out on my own. I just wonder how I'm supposed to have it sort the array in ascending and descending at the same time.
 
and enhance it so that it sorts the array in ascending and descending orders, and also display the values it contains.

This should be something I can figure out on my own. I just wonder how I'm supposed to have it sort the array in ascending and descending at the same time.

Store the 2 different sorted arrays in 2 separate variables.
 

MrCuddle

Member
Just bought myself an Arduino starter kit with the intention of trying out some low level bit fiddling in practice. Anyone who could recommend me some good reading on the topic?
 

SOLDIER

Member
Store the 2 different sorted arrays in 2 separate variables.

Figured as much. A quick Google makes it look easy, but as usual there's a formatting problem I'm not aware of.

Code:
a = [5, 8, 99, 4, 1, 6]
print (sorted(a))
print (sorted(a), reverse=True)

Error message says "'reverse' is an invalid keyword argument for this function"
 

MrCuddle

Member
Figured as much. A quick Google makes it look easy, but as usual there's a formatting problem I'm not aware of.

Code:
a = [5, 8, 99, 4, 1, 6]
print (sorted(a))
print (sorted(a), reverse=True)

Error message says "'reverse' is an invalid keyword argument for this function"

I know pretty much nothing about Python, but my guess is that you're trying to send reverse as a keyword argument to the print function and not the sorted function.

Try

Code:
a = [5, 8, 99, 4, 1, 6]
print (sorted(a))
print (sorted(a, reverse=True))
 

SOLDIER

Member
I know pretty much nothing about Python, but my guess is that you're trying to send reverse as a keyword argument to the print function and not the sorted function.

Try

Code:
a = [5, 8, 99, 4, 1, 6]
print (sorted(a))
print (sorted(a, reverse=True))

That worked, thanks.

Now to see if I can put this together with the existing code.
 
Figured as much. A quick Google makes it look easy, but as usual there's a formatting problem I'm not aware of.

Code:
a = [5, 8, 99, 4, 1, 6]
print (sorted(a))
print (sorted(a), reverse=True)

Error message says "'reverse' is an invalid keyword argument for this function"

You're passing reverse as a keyword to the print function. You need to pass it to the sorted function.
 

SOLDIER

Member
How's this?

Code:
def main():
    rainfall = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    high_rainfall = 0.0
    low_rainfall = 0.0
    total_rainfall = 0.0
    average_rainfall = 0.0

    rainfall[0]=int(input("Enter the rainfall for January: "))

    rainfall[1]=int(input("Enter the rainfall for February: "))

    rainfall[2]=int(input("Enter the rainfall for March: "))

    rainfall[3]=int(input("Enter the rainfall for April: "))

    rainfall[4]=int(input("Enter the rainfall for May: "))

    rainfall[5]=int(input("Enter the rainfall for June: "))

    rainfall[6]=int(input("Enter the rainfall for July: "))

    rainfall[7]=int(input("Enter the rainfall for August: "))

    rainfall[8]=int(input("Enter the rainfall for September: "))

    rainfall[9]=int(input("Enter the rainfall for October: "))

    rainfall[10]=int(input("Enter the rainfall for November: "))

    rainfall[11]=int(input("Enter the rainfall for December: "))

    print ("The ascending rainfall is: " +str(sorted(rainfall)))

    print ("The descending rainfall is: " +str(sorted(rainfall, reverse=True)))

    high_rainfall = (max(rainfall))

    print ("The highest rainfall is: " +str(high_rainfall))

    low_rainfall = (min(rainfall))

    print ("The lowest rainfall is: " +str(low_rainfall))

    total_rainfall = (sum(rainfall))

    print ("The total rainfall is: " +str(total_rainfall))

    average_rainfall = (sum(rainfall)/len(rainfall))

    print ("The average rainfall is: " +str(average_rainfall))

main()

I think that's what he wants, unless I'm missing something.
 

LegatoB

Member
How's this?

I think that's what he wants, unless I'm missing something.
I'd iterate through a list of month names rather than writing a specific statement for each line of input. It looks prettier and it's easier to maintain, and since you mentioned this is an enhancement of code you'd worked on before, it's a good habit to practice now.
 

peakish

Member
I'd iterate through a list of month names rather than writing a specific statement for each line of input. It looks prettier and it's easier to maintain, and since you mentioned this is an enhancement of code you'd worked on before, it's a good habit to practice now.
I agree and there are two other things that stick out as dangerous in the code. The first is:
Code:
rainfall = [0]*12 # Easier to read, less chance of creating incorrect list of length 11 or 13
But I'd really suggest to not preallocate the list at all, but to append to it. Less risk of forgetting to change an index when copy-pasting and no need to worry about the initial list length:
Code:
rainfall = []                    # Create empty list
rainfall.append(int(input(...))) # Add a value to the end of it
Other than that, the code seems to work well enough.
 

SOLDIER

Member
I'll look into those suggestions and see if I can wrap my head around them.

Meantime, I'd like to ask for help in another matter: creating psuedocode with Raptor, which has been a requirement for these assignments.

Any good tutorial or guide with Raptor would be appreciated. Some people told me to try YouTube, which I'll look into.
 
I have a really noob question, but I was wondering if anyone could help me understand how to get functions to transfer data from one function to the next in C? Here's my code:

Code:
/* Determines student's grade with 3 test scores between 0 and 100. 
 If score is 90% or more, the grade is an A. If score is 70% or more
 but less than 90%, it will check the third score. If third score is more than 90%, 
 the grade is A, otherwise, grade is. If score is 50% or more and less than 70%, 
 it will check average of second and third scores. If iavergae of the two is greater
 than 70%, the grade is C, otherwise it is D. If score is less than 50%, grade is F. 
 
 Written by: 
 Date: 10/18/2015
 CRN: COP-1000C-18519
 */
 
 #include <stdio.h>
 
 
 
 //Global Declarations
		int test1;
		int test2;
		int test3;
		int totalTest;
		
		int testPercent;
		int totalPercent;
		
		int gradeA;
		int gradeB;
		int gradeC;
		int gradeD;
		int gradeFailed;
 
 void inputscores()
 {
	//statements
	printf("======TEST SCORES=====\n");
	printf("Enter the score for the first test:");
	scanf("%d", &test1);
	printf("Enter the score for the second test:");
	scanf("%d", &test2);
	printf("Enter the score for the third test:");
	scanf("%d", &test3);
	
	totalTest = (test1 + test2 + test3);
	
	testPercent = (totalTest / 3);
	
	
 }
 
 
 void convertscores()
 {
	 
		
	if (testPercent >= 90) testPercent = gradeA
	; 
	
	else if (testPercent <= 90 && testPercent >= 70 && test3 >= 90) testPercent = gradeA
		;
	
	else if (testPercent < 90 && testPercent >= 70 && test3 < 90) testPercent = gradeB
	;
	
	else if (testPercent >= 50 && testPercent < 70 && test2 + test3 / 2 >= 70) testPercent = gradeC
	;
	
	else if (testPercent >= 50 && testPercent < 70 && test2 + test3 / 2 < 70) testPercent = gradeD
	;
	
	else if (testPercent < 50) testPercent = gradeFailed
	;
	
	
	
}
 
 void printscores()
 {
 
	if (testPercent == gradeA)
	{ printf("You got a grade of A"); // printing outputs
	}
	
	else if (testPercent == gradeB)
	{ printf("You got a grade of B");
	}	

	else if (testPercent == gradeC)
	{ printf("You got a grade of C");
	}	
	
	else if (testPercent == gradeD)
	{ printf("You got a grade of D");
	}
	
	else if (testPercent == gradeFailed)
	{ printf("You got a grade of F, which means you failed. Sorry!");
	}
	
	
 }


 
 int main()
 {
	 
	 inputscores();
	 
	 convertscores();
	 
	 printscores();
	 
	 return 0;
	 
 
}

Everytime I run it, the final grade is always A nomatter what I enter for test scores. If I can get the functions to pass on the data from one function to the next I can actually have a functional program. Thanks in advance!
 

NotBacon

Member
You need to give your functions parameters to accept values, and return statements to return a value back to where the function was called.

E.g.
Code:
// specify return type int instead of void
int cool_function(int param)
{
    printf("You passed in %d", param);
	
    return 5*param;  // functions can only have one return statement
}
 
int main()
{
    int returned_number = cool_function(7);
    printf("%d", returned_number);  // prints 35

    return 0; // main returns the exit code (0 = fine, 1 = there was an error)
}
 

Hypron

Member
I just found out that the newly released Atmel Studio 7 has inbuilt support for Arduino projects.

And since it's based on Visual Studio 2015 you can use that Dark Theme, and more importantly it's an extremely good IDE.
 

peakish

Member
I have a really noob question, but I was wondering if anyone could help me understand how to get functions to transfer data from one function to the next in C? Here's my code:

Everytime I run it, the final grade is always A nomatter what I enter for test scores. If I can get the functions to pass on the data from one function to the next I can actually have a functional program. Thanks in advance!
Functions are one thing, but what actually is gradeA, gradeB, etc. in your program? You are declaring that they are integers but they're not given any value to separate them. After you set
Code:
testPercent = gradeA;
what value does testPercent have? What if you set it to gradeB? Try printing the value of testPercent after the if ... else statements in convertscores().


I'll look into those suggestions and see if I can wrap my head around them.

Meantime, I'd like to ask for help in another matter: creating psuedocode with Raptor, which has been a requirement for these assignments.

Any good tutorial or guide with Raptor would be appreciated. Some people told me to try YouTube, which I'll look into.
This and this post has examples of making a loop to collect the values. Hope it helps! No idea about Raptor, though.
 

Makai

Member
Thanks for the pointer. I'm thinking of using games like these to get students warmed up for actual programming. So far I have Zachtronics' Spacechem ready to go, and TIS-100 is on my shopping list.
This one is less nerdy and more gender inclusive than those - I really think it's going to hit the big time as a mainstream teaching tool. I'm mainly impressed because it teaches procedural programming quite directly. You have to convert an input queue into an output queue using source code. You're given an array in the middle for storing temporary variables. There are optimization challenges for completing the level in the least lines of code or least steps. There's even a debugger!
 

Makai

Member
My friend has been recommending Infinifactory, which I guess combines Infiniminer and Spacechem.

infinifactory_steam_early_acc_4.jpg
 

SOLDIER

Member
Still need help to figure out how to get Raptor to sort lists in ascending and descending order.

But in the meantime, I wanted to ask another question that some here might know. For this career path I'm currently following (Information Security), I've been told that the best thing to do is get experience through entry level jobs/internships related to the field as soon as possible, as bigger companies tend to want at least 2 years experience before hiring.

So I wanted to ask if anyone knew what kind of job titles I should be searching for online that offer entry level positions. "Help Desk" was one suggested to me, but beyond that I don't know what else to look for.
 
Still need help to figure out how to get Raptor to sort lists in ascending and descending order.

But in the meantime, I wanted to ask another question that some here might know. For this career path I'm currently following (Information Security), I've been told that the best thing to do is get experience through entry level jobs/internships related to the field as soon as possible, as bigger companies tend to want at least 2 years experience before hiring.

So I wanted to ask if anyone knew what kind of job titles I should be searching for online that offer entry level positions. "Help Desk" was one suggested to me, but beyond that I don't know what else to look for.

Just out of curiosity, have you tried your university's career guidance department?
 

Chris R

Member
TIS-100 is HARD

Granted, I've only a few unsolved puzzles and could probably do them if I focused, but right now TIS-100 is my "on the couch with my laptop" game.
 

Water

Member
This one is less nerdy and more gender inclusive than those - I really think it's going to hit the big time as a mainstream teaching tool.
That implies the Zachtronics games somehow favor or exclude a particular gender. Writing assembly code for an imaginary computer is very nerdy, but last I checked, even tumblrites had not managed to invent high-level-programming-construct-genders and those would be the only ones oppressed in TIS-100.
 
But in the meantime, I wanted to ask another question that some here might know. For this career path I'm currently following (Information Security), I've been told that the best thing to do is get experience through entry level jobs/internships related to the field as soon as possible, as bigger companies tend to want at least 2 years experience before hiring.

So I wanted to ask if anyone knew what kind of job titles I should be searching for online that offer entry level positions. "Help Desk" was one suggested to me, but beyond that I don't know what else to look for.

For Information Technology college grads you want to aim higher than help desk.I mean, you can do help desk but you should push yourself a bit more to see just how talented and trained you really are.

Look for titles like software engineer (don't pigeonhole yourself out of this-CS isn't a make-or-break standard), service and support engineers (if you want a path towards software), software engineers in test (SDET, again this is going to be a software career), and more or less anything entry level requirements with the term analyst or administrator on it. The latter categories will still likely have you dealing a lot with software and infrastructure deployments. There's also consultant positions but I think it's better go to into one of those as an expert in a field so you always have work and can command a premium.

Internships are made of solid gold and you should aggressively pursue them. Don't settle for just busywork either-if you're iffy about the company make sure you ask questions about what kind of work you'll be able to do in the internship. Completing and working on real projects with full-time team members and getting actual results is a HUGE boost in an interview loop for college grads.

Also I would not say that bigger companies want two years experience before hiring. If you show the ability to adapt to change, learn quickly, and work with passion big companies (the good ones you want to work for) will invest heavily into your development.
 
Top Bottom