View Full Version : Kopra's path to the mastery of C
Kopravich
14-03-2010, 14:42
This is the thread i am going to use to ask questions about programming language C. I just started learning it and i would appreciate if you help me in solving things i post here... Thanks in advance :-))
Kopravich
23-03-2010, 13:40
My professor gave me some kind of homework for the next week. I have to solve all the problems here and to explain how i did it. I will get a grade for my performance, so i hope that someone will help me solve all these problems. Unfortunately, i was forced to miss few classes, so i am kinda behind others, but i suppose i can catch them if i understand how to solve problems below:
1. Input two characters from a keyboard and print a number which is equall to the difference of their decal equivallents from the ASCII code table.
2.)Write a program which calculates and prints the values of following real function:
y=(x2-2x+2)/(x+5)
if x changes from Xp to Xk with the step of h.
3.)Enter 10 integer numbers from the keyboard and print the one with the highest value!
4.)
5.)Write a program in C, which will, for two inputed numbers ( a, b ) and one of arithimetic operators ( +,-,*,/,% ) calculate the value of the executed operation. Repeat a program until zero is inputed for b.
6.) Write a program in C which prints all three-digit numbers, which share the following characteristic: (ABC) = (AB)2 – C2 , where A,B,C are the the digits of the number!
7.)Write a program in C which prints the first n lines of the following triangle:
*
***
*****
*******
..................
8.)
What the frell is the purpose of 7? that's just a matter of printing an incremented number of * based on the value of i (in a loop) and printing "\n" at the end of the loop (before i++)
Easiest way to do it would be a double loop on a variable i
i < n and u < i for printing the stars, if you have specific questions, ask them.
I guess you also need stdin to determine n, it's not specified if n is supposed to be user input, but I'd guess so.
6.) Write a program in C which prints all three-digit numbers, which share the following characteristic: (ABC) = (AB)2 – C2 , where A,B,C are the the digits of the number!
A loop, an if statement, and mathematical calculations. The catch?
Splitting the number into three. Google knows all
5.)Write a program in C, which will, for two inputed numbers ( a, b ) and one of arithimetic operators ( +,-,*,/,% ) calculate the value of the executed operation. Repeat a program until zero is inputed for b.
Keywords:
stdin
stdout
otherwise easy, depending on language specifics you may need a switch statement (preferred) to check what operator to use. Since using variables as operators is unlikely to work.
3.)Enter 10 integer numbers from the keyboard and print the one with the highest value!
Keywords:
while / for loop
> < operators
if statements
stdout
2.)Write a program which calculates and prints the values of following real function:
y=(x2-2x+2)/(x+5)
if x changes from Xp to Xk with the step of h.
keyword:
plain old mathematical operation in a for loop with x = x + h and output the result (remember 2x is 2 * x)
Sounds like you're not more than one lesson behind >_> this is mostly basic stuff. The purpose here isn't to pre-chew the answers for you, so google the keywords and come back with specific questions.
Kopravich
23-03-2010, 18:13
Oke, got it... When i said one class, i meant one day... And that was around 5 classes, i think xD
Will try to figure out something now!
Kopravich
29-03-2010, 20:18
#include <stdio.h>
main ()
{
int n,k,x,i;
printf ( "Enter n" );
k=0;
scanf ("%d", &n);
for ( i=1; i<=n; i++);
{
x=i*i*i-3*i*i+n;
if (x%5==0)
{
k=k+1;
printf ( "%d/n",x);
}
}
Thats a code and it gives me following error when i attempt to build it:
"fatal error C1004: unexpected end of file found"
I can't see what's wrong...
I'll have a look, what IDE are you doing this in? ~__~
Kopravich
29-03-2010, 20:20
Microsoft Visual C++ 6.0
Odd, you'd think visual C++ would see the blatantly obvious syntax error. Walk with me here
#include <stdio.h>
// main returns an int, don't argue with me here.
int main ()
{ // <-- opening bracket for main()
// bad kopra, bad. Variables need DESCRIPTIVE names unless
// used as a loop counter (and only a loop counter) not input
int n,k,x,i;
printf ( "Enter n" );
k=0;
scanf ("%d", &n);
for ( i=1; i<=n; i++);
{// <-- opening bracket for for loop
x=i*i*i-3*i*i+n;
if (x%5==0)
{// <-- opening bracket for if clause
k=k+1;
printf ( "%d/n",x);
return 1;
}// <-- closing bracket for if clause
}// <-- closing bracket for for loop
}// <--- originally missing!! closing bracket for main()
Biggest hint in here, count the number of opening and closing brackets. You're missing a closing bracket, which results in a syntax error (main function is not terminated)
use indentation (a tab after every opening bracket, go down one tab level for every closing bracket, like above) and you'll spot these things easily.
Kopravich
29-03-2010, 20:29
Ye, just noticed it... Well, i closed it now, but it still doesn't print the solution...
Oh, solved it xD
Well I can't really help you with that unless you tell me WTF you're trying to do here?
Kopravich
29-03-2010, 20:33
It is solved, don't worry... xD
Enlighten me, for my entertainment >_>
Kopravich
29-03-2010, 20:36
"For" was supposed to be closed before "If"... They shouldn't intersect
Couldn't have caught that for you without knowing what you were trying >_> it seemed reasonable to check the value of X during the loop considering it was recalculated every time *shrug*
you really need to work on your source formatting though
descriptive variable names
indentation
SPACES
makes code readable and maintainable. Don't forget them.
if( x % 5 == 0) not if(x%5==0)
etc.
kyubichan
30-03-2010, 06:22
for ( i=1; i<=n; i++);
o.o
Wut?
Wut indeed O-o; hadn't noticed that one >->
*hits self with paper fan* /fail
kyubichan
30-03-2010, 06:26
Wut indeed O-o; hadn't noticed that one >->
*hits self with paper fan* /fail
That was probably the "unexpected end of file found" error. The semicolon terminated the FOR loop before it could execute anything. If corrected, the compiler would've then detected the missing } as "statement missing".
No, the compiler actually functions with the malfunctional ;, it just executes the for loop without doing anything, and then executes the parts in the brackets once.
I actually ran the code like that for lols.
if it actually killed on the misplaced brackets it'd throw an unexpected { on line x error I'd reckon.
It threw the unexpected EOF because it reached the end of the file while still expecting input. Namely the missing } bracket >_> at least, that's the logical deduction of the compilers behavior.
kyubichan
30-03-2010, 06:37
No, the compiler actually functions with the malfunctional ;, it just executes the for loop without doing anything, and then executes the parts in the brackets once.
I actually ran the code like that for lols.
Ah, it just won't do anything... why'd Visual C bring an EoF error up then if it was just the missing bracket? Because the code did not end, it was left open >.<
*shrug* I'm not intimately familiar with the inner mechanics of the gcc compiler.
It might be that what you're saying is correct, but my compiler actually clears brackets that are not affixed to a statement >_>
Whilst macrocraps just goes haywire.
And the EOF was probably thrown because the code didn't end >->;; even though the file did.
kyubichan
30-03-2010, 06:53
Odd >.<
I tried it on my Visual Studio and DOS-based C++... the same error comes up when I run Kopra's original code, which is "compound statement missing".
Oh well =O
Kopravich
30-03-2010, 14:30
Bah, syntax is fine now, but my logic got screwed somewhere... Basically, i need to print all the numbers which are divideable with 5, from the array (i*i*i + 3*i*i + n )...
post the original assignment, because that is a formula, not an array >_>;; and I dare question why you do i*i*i + 3*i*i + n
your math is probably flawed.
And if you need to print all the numbers ,the printf has to be IN the for loop, kthx. (you mentioned placing it outside of it in an earlier post) otherwise, post source.
Kopravich
30-03-2010, 15:41
Perhaps array was the wrong term... How about sequence or chain?
You know, thing like: 1,2,4,8,16,32, ... , n
And about math... It is :
i^3 - 3* i^2 + n
Hope this is better...
Assignment is:
Write a program which determines how many elements of the chain ( i^3 - 3* i^2 + n ) are dividable with 5 ! Print the number of the elements dividable with 5...
you want to print the number of elements, so you want:
#include <stdio.h>
#include <math.h>
int main ()
{
// bad kopra, bad. Variables need DESCRIPTIVE names unless
// used as a loop counter (and only a loop counter) not input
int n,k,x,i;
printf ( "Enter n" );
k=0;
scanf ("%d", &n);
for ( i=1; i<=n; i++) {
// note: pow requires math.h included
x = (pow(i,3) - 3) * (pow(i,2) + n);
if (x % 5 == 0 ){
//k++ is the same as k=k+1, just shorter and easier to understand
k++;
}
}
printf ( "The number of elements divisible by 5 = %d\n",k);
return(1);
}
Or something similar, this is not compile-ready code. Or rather, it might be considering I didn't test it at all am and going purely on my gut instinct. And my C is rather rusty.
The key elements here are:
pow(x,y) this is x ^ y, part of math.h and is infinitely easier to read than doing i*i*i especially considering you'd have to properly bracket i*i*i to ensure proper operand order and that yadda.
In your previous source you printed x, while you wanted to get the number k printed at the end... I would have caught this earlier, but I did not know the assignment *paper fan*
Ask anything you don't get from the sample above, try to get it to run, and then come back.
edit: the pow() function needs doubles as a parameter and returns doubles, cast your integers to double before passing them, and cast the returned double to an int before comparing, kthx. Like I said this is not compile-ready code, just the general idea.
I trust you've been told about data types and casting, if not your education fails.
Below is the working compile-ready code, copy paste at your own risk
/*
* File: main.cpp
* Author: aeterno
*
* Created on March 29, 2010, 10:20 PM
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main ()
{
// bad kopra, bad. Variables need DESCRIPTIVE names unless
// used as a loop counter (and only a loop counter) not input
int n = 0,k = 0 ,i = 0,x = 0;
printf ( "Enter n" );
scanf ("%d", &n);
for ( i=1; i<=n; i++) {
// note: pow requires math.h included
x = (pow(i,3) - 3) * (pow(i,2) + n);
if (x % 5 == 0 ){
// This printf was not asked for but is here for debugging purposes to validate the mathematical logic
printf("Divisible by 5: %d\n ",x);
//k++ is the same as k=k+1, just shorter and easier to understand
k++;
}
else{
// This printf was not asked for but is here for debugging purposes to validate the mathematical logic
printf("Not divisible by 5: %d\n",x);
}
}
printf ( "The number of elements divisible by 5 = %d\n",k);
return(EXIT_SUCCESS);
}
Notes about the compile-ready code:
- Integers do not make for good variables to dump this kind of math in, the standard int is also too small to contain the results for this operation (try entering a number like 199 with my debug outputs)
- always initialize your variables, this can be done in the declaration like so int n = 0; Saves you the k = 0; line later.
especially in low level languages like C it's possible that leftover data remains in the RAM so your variable might not be 0 at initialization, even though you just declared it.
- use the debug echoes to see what the program DOES, helps you more than just looking at my code and going 'oh, it works' or 'oh, it doesn't work' echoing (or in this case printf'ing) is the basic principle of debugging use it often when you think your program isn't doing what you want. Just print the relevant values at relevant places to see if the code reaches a certain place, what value relevant variables have, or whether or not a loop is actually looped through>
It's better to use your specific IDE functionality for this (breakpoints etc) but in absence of such printf works wonders.
Kopravich
30-03-2010, 16:27
Eh, it displayed one error and warning... It seems that "pow" causes potential data loss, since there was no warning when i wrote the formula in the way i did it before...
Error was just a missing bracket at the end of the code...
- Integers do not make for good variables to dump this kind of math in, the standard int is also too small to contain the results for this operation (try entering a number like 199 with my debug outputs)
Ye, but i believe it is sufficient for my level... I am still at the very basics xD
always initialize your variables
Hmm, always give them value of zero, unless said otherwise ? o.O
Btw, it works xD
return(EXIT_SUCCESS);
What this actually mean? We never returned anything, so far....
Eh, it displayed one error and warning... It seems that "pow" causes potential data loss, since there was no warning when i wrote the formula in the way i did it before...
it causes potential data loss because the returned argument is automatically converted to an int. Also, no data loss occurs because you're dealing with ints anyway.
Error was just a missing bracket at the end of the code...
Copy paste error, so sue me.
Ye, but i believe it is sufficient for my level... I am still at the very basics xD
This has nothing to do with your level, it has to do with the result size, bit-wise it exceeds the maximum bit of a standard int, it'd be better done in a long (higher numbers) or even a double (precision with floating points)
Hmm, always give them value of zero, unless said otherwise ? o.O
That's what you should do, yes. It doesn't do so automatically. Not in C / C++.
What this actually mean? We never returned anything, so far....
It returns 1, and requires stdlib.h to be included. It's basically a constant for 1
const int EXIT_SUCCESS = 1;
is defined in stdlib.h
Kopravich
30-03-2010, 16:38
This has nothing to do with your level, it has to do with the result size, bit-wise it exceeds the maximum bit of a standard int, it'd be better done in a long (higher numbers) or even a double (precision with floating points)
Ye, i understand, but we just have to make the code work, we still don't play with the results... But why not gaining some edge over others? xD
Btw, should i always use the data type with the most number of bits available? Thats long double, i suppose...
No, you should use what works for your specific calculation.
as soon as you start using pow() or multiplication you might want to stick with a long depending on your input variables (check maximum size for a standard integer)
Always use the smalles possible depending on the largest possible outcome. This way you waste the least amount of RAM.
also, double is useless with pow or multiplication since it'll never result in floating point outcomes if you have integer input, but meh.
Kopravich
30-03-2010, 16:52
I see...
One thing is troubling me:
When i look at one assignment, i have no clue how to solve it... Does that mean that i am not actually the "best person" for programming, or i just need to practice a lot?
I am afraid that i don't have what it takes to be a good programmer...
btw, this is the assignment:
Write a program which prints the first n lines of the following triangle:
.......1
......23
....345
...4567
.56789
..........
Note: Consider dots as empty spaces... Which are colored though, just to make them invisible...
that assignment isn't that hard, it just requires some thinking on when to echo a space and when not to. Posting the frelling triangle in a frelling NON MONOSPACED FONT doesn't exactly help in figuring out how many characters you're actually printing...
.......1
......23
....345
...4567
.56789
..........
seems like the number of characters is increasing... Which is most probably NOT the purpose, you probably want this:
......1
.....12
....123
...1234
..12345
.123456
I double post, because I can.
I have sample code of which I think does what you want (it prints the array I echoed above)
but I want you to come up with specific questions or at least some attempt to do it yourself before I make it available for copy pasting >_>
there's a key hint: two loops one for the number of rows and one for each character in there.
Then with an if clause you determine if you need to print a space (printf(" ")) or a number.
Kopravich
30-03-2010, 18:07
I've done this so far...
#include <stdio.h>
main ()
{
int row = 0, num = 0, n = 0; // num is number of characters in one row
printf( " Enter the number of rows n= ");
scan f ( "%d", &n);
for ( row = 1; row <= n; row++) /* As far as i can see, the program should print n number of rows */
{
/* I suppose i need to implement the for loop for num here, but not sure how to do it... n is always the first digit in the row, but i am not sure how to make it stop increasing itself, thus making the row infinite... I suppose it starts with n, then increment itself, but can't figure out the condition for it to stop... By the way, it also add n+1 positions in the row ( after the first n), for example, if you enter n=2, it will make 2 rows and second one will start with 2 ( which is n) and will add 3 next to it, which n+1...
But i can't figure out what to do next... I am not even sure is this logic fine >_>
Or it goes from n-1 to n+1, which would be for ( num = n-1; num <= n+1; num++ ) */
/* EDIT: By the way, if this logic is true, then i suppose i can go with :
if ( num < n-1 )
printf ( " " )
else
printf ("%d", num)
But not sure about it... */
}
Paste it in [ code ] [ / code ] brackets and keep the indentation alive, I can't possibly tell WTF you're doing without them. It's a pain.
You get the basics but your n - 1 logic is incorrect.
The row length is the same as the number of rows you're trying to print (n) and it starts printing from the last character on the row.
So for row 1, you'd start printing at character (n - i) is for example (with 7 rows)
7 - 1 = 6th character (which is actually the last since the counter moves from 0)
after that you continue from the characters
row 2: 7 - 2 = 5th character (second last)
row 3: 7 - 3 = 4th character (third last)
see the pattern?
so the correct logic for the if clause, as I see it. Would be (col < (lines - i))
The second loop is a simple loop from u = 0 to u = n
or as I implemented it
while(u <= n){}
I like to shuffle up for and while loops, too many for loops make for boring code.
Kopravich
30-03-2010, 18:45
#include <stdio.h>
main ()
{
int row = 0, num = 0, n = 0;
for ( row = 1; row <= n; row++)
{
for( num = n - 1 ; num = n +1; num++)
{
if ( row < num - 1 )
{
printf ( " " );
}
else
{
printf ("%d", num);
}
}
}
Ugh, i got confused now... When you say second loop, you mean on second for loop, or new loop which comes after if loop?
the if is not a loop >_> and the if would be IN the second loop.
Two loops, one for each row, and one that loops over all the characters in the row.
while(i < n){
while(u <= n){
}
}
two loops, thusly. Substitute the whiles for for loops freely.
Kopravich
30-03-2010, 18:57
#include <stdio.h>
main ()
{
int row = 0, num = 0, n = 0;
for ( row = 1; row < n; row++)
{
for( num = 1 ; num <= n; num++)
{
if ( row < num - 1 )
{
printf ( " " );
}
else
{
printf ("%d", num);
}
}
}
So, something like this?
gah, my head hurts...
#include <stdio.h>
main ()
{
int row = 0, num = 0, n = 0;
for ( row = 1; row < n; row++)
{
for( num = 1 ; num <= n; num++)
{
if ( row < num - 1 )
{
printf ( " " );
}
else
{
printf ("%d", num);
}
}
}
INDENTATION
And something like that, minus the other comments I already placed above...
you do row < num - 1
so on the first row
1 < (3 - 1 = 2) means it starts printing on the THIRD character of the row, while it should be printing at the n - 1 character of the row.
Write out the examples, you'll see the logic faster
Kopravich
30-03-2010, 19:07
#include <stdio.h>
main ()
{
int row = 0, num = 0, n = 0;
printf ( " Enter n" );
scanf ( "%d", &n) ;
for ( row = 1; row < n; row++)
{
for( num = 1 ; num <= n; num++)
{
if ( row < n - 1 )
{
printf ( " " );
}
else
{
printf ("%d", num);
}
}
}
}
So this should be the final product... Sorry about indentation, have to get used to it...
Is everything ok now?
if ( row < n - 1 )
if ( 0 < 9 - 1)
if ( 1 < 9 - 1)
if ( 2 < 9 - 1)
this will be a constant for the entire loop over num and won't work.
*pokes brain* seriously, write out the numbers of your if clauses if you can't see the logic yet.
you need to print a space depending on three factors:
1. The current row (row) (depends what character you need to start printing on)
2. The current character (num) (what character you're currently at)
3. The maximum number of characters to print (n) (coincides with the number of lines to print)
All of these are in the if, you just have to figure out the relation.
You print at the back, and the number of characters you print is directly proportional to the row number, yes?
row 1 : 1 character
row 2: 2 characters
since you start from the back, if (num) is smaller than (the maximum number of characters to print) - (the amount of characters to print) you print a space.
Do you follow the logic? Because I really can't explain it any better other than telling you to tinker with that part until you see it. My program outputs the following.
0: 1
1: 23
2: 345
3: 4567
4: 56789
5: 678912
6: 7891234
1: is the row number
and I loop back to 1 because otherwise we'd be printing double digit numbers which complicates the process (though it's not impossible to factor that in, I doubt that was the point of the exercise)
I'm going for a shower, I'll be back to check on your brain implosion in 20 minutes.
Kopravich
30-03-2010, 19:29
Nah, i just can't figure it out... Or i am too tired or too stupid, but i really can't get it working...
I practically handed you the solution >__>;;
I'm not a teacher so I can't teach you decently, I can only give you hints and prod you in the general direction (and hand things over on a silver platter)
If you still don't see the logic after that you have three options:
1) Call kyu, she's a teacher >_> (and risk brain damage)
2) Yell at your teacher, duh
3) Come to the conclusion that you are severely lacking in the ways of logic and pattern recognition. Which has two sub-options
3a) Attempt to solve the issue by taking a few classes in binary logic which builds insight
3b) Write it off as a genetic deficiency and give up
In case of emergencies use copy paste code:
/*
* File: main.cpp
* Author: aeterno
*
* Created on March 29, 2010, 10:20 PM
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main() {
int i = 0;
int n = 7; // need to print 7 lines
int print = 1;
while (i < n) {
printf("%d:",i);
if(i < 9){
print = i + 1;
}
int u = 0;
while (u <= n) {
if (u < (n - i)) {
// u < (n - i) means we print a space
// example, 5 < 7 meaning we print a space at the 5th character of line 1 because it's < than 7
printf(" ");
} else {
// u >= n - i means we are on character n for line 1 n-1 for line 2, n-2 for line 3, etc
printf("%d", print);
if(print < 9){
print++;
}
else{
// reset print to 1 if it exceeds 9 otherwise we print double digit numbers, which is bad
print = 1;
}
}
u++;
}
// We're finished with this row of numbers, so print a \n for a new line and increment i (because this is a while loop you do this manually)
printf("\n");
i++;
}
return (EXIT_SUCCESS);
}
therealnaruto
31-03-2010, 01:07
Wow, i'm like i want to be a programmer and i am lost from the first wrod.
Kopravich
31-03-2010, 07:14
Wow, i'm like i want to be a programmer and i am lost from the first wrod.
I was the same when i just got the desire to be a programmer... It really looks complicated when you see it for the first time, but i suppose everyone get used to it after some time...
kyubichan
31-03-2010, 07:27
Computer programming is just like playing a computer game or solving a puzzle. You don't have to memorize a whole lot of things, you just need to practice and challenge yourself.
Computer programming is just like playing a computer game or solving a puzzle. You don't have to memorize a whole lot of things, you just need to practice and challenge yourself.
>-> *keeps that quote for the next time he needs to argue a baby could replace him*
A certain degree of insight into program flow or abstraction helps a great deal, but that insight usually grows over time. For syntax, there's always google >->
Kopravich
31-03-2010, 09:57
That was some nice encouragment ^_^
Kopravich
01-04-2010, 00:06
I believe i don't actually understand the concept of for loop being inserted into another for loop:
Look at the code:
#include < stdio.h >
main ()
{
int n, column, number;
printf (" Enter n" );
scanf ( "%d",&n );
for ( column=1; column<=n; column++)
{
for ( number=1; number<=column; number++)
printf ( "%d", number % 5);
printf ("\n");
}
}
Care to explain me what actually happens in every cycle?
You have an infinite loop in that there code, 'red' is undefined. Will give odd behavior... not compile ready code.
Cycle 1 main loop:
column = 1;
Execute second loop:
cycle 1: print (1 % 5), print "\n"
cycle 2: print ( 2 % 5), print "\n"
cycle 3: print( 3 % 5), print "\n"
-- continues for a while, or not at all --
Cycle 2 main loop:
Execute second loop
column = 2
cycle 1: print (1 % 5), print "\n"
cycle 2: print ( 2 % 5), print "\n"
cycle 3: print( 3 % 5), print "\n"
-- continues for a while, or not at all --
this will output ONE LONG line of numbers (vertical line)
this second cycle does not get called because 'red' does not exist.
the concept of double loops is simple
for every cycle in the first loop, you execute a second loop.
so in this case the second loop would be executed n times. That's all the first loop does in this example, because column is not a variable that's used in the data processing. (not relevant to the output)
I don't know what this code wants to do, but it's highly faulty since it doesn't do anything useful at all. If you just want to echo 1 - 5 with line breaks in between a double loop is NOT the way to go.
Double loops are generally useful when the value of the first loop is actually used in the second loop. Exceptions do occur, so it's hard to give a definite answer. But in this case it just increases the clock cycles required.
Kopravich
01-04-2010, 09:18
I edited the code, you should see what it does now!
~__~ right, doesn't mean I know what it's supposed to do. Since there's probably a difference.
This just prints the following
First cycle of the first loop:
(1 % 5) \n
Second Cycle of the first loop
(1 % 5) \n
(2 % 5) \n
Third cycle of the first loop
(1 % 5) \n
(2 % 5) \n
(3 % 5) \n
-- continue above pattern until n - 1 is reached --
See the pattern, there's no specific question... nor is there a flaw in the program logic without knowing the assignment. So how can I possibly help you? ~__~
Kopravich
01-04-2010, 17:56
Lets see did i get it right:
First cycle of main loop does the whole secondary loop... Then second cycle of main loop also repeats the whole secondary loop... Is that correct?
EVERY CYCLE of the first loop does the second loop.
Because the entire second loop is in the first loop
as designated by the brackets.
Basic loop functions, everything within the brackets is executed repeatedly until the loop ends.
In this case, because you use for loops, the secondary loop is repeated completely.
if it were say, a while loop, that runs based on a variable set in the first loop, it could behave differently.
Kopravich
01-04-2010, 18:07
Hmm... Perhaps this will clarify everything... Can you write me a code which will print numbers from 1 to 20 and a program which will print number " 1" twenty times ?
Print numbers 1 through 20?
for ( number=1; number<=20; number++)
printf ( "%d", number);
printf ("\n");
}
for( number=0;number<20;number++){
printf ( " 1");
printf ("\n");
}
I fail to see the point in this @_@;;
Kopravich
01-04-2010, 18:42
Why on the Earth i assumed that the code would print each number in next row?
It is no wonder i failed to understand the previous assignment... >_>
you print \n
which is a newline character, after that it prints it on the next line. (or row)
Kopravich
01-04-2010, 18:46
No, i thought that "for" prints the number each in next line without next line command... Silly me...
Now imagine what chaos was in my head last night >_>
Kopravich
02-04-2010, 19:42
It seems i still fail with for loops... Why this doesn't want to print " $# $# $# " in 10 rows?
#include <stdio.h>
main ()
{
int row, column;
for ( row = 1; row<= 10; row++)
{
for ( column=1; column<=5; column++)
{
printf ( "$# $# $# \n");
}
}
}
Because it loops 5 sets of $# $# $# every time the first loop loops.
Seriously, you're not getting something blatantly obvious here.
In a loop everything inside the brackets {} is repeated as long as the statement (row<= 10) is true
in this case, it means that the entire second loop is repeated 10 times.
And the second loop repeats
printf ( "$# $# $# \n");
Five times every time it's called.
Which is 10 times because the second loop is embedded in the first loop.
Thus it echoes
Loop 1 cycle 1:
$# $# $# \n
$# $# $# \n
$# $# $# \n
$# $# $# \n
$# $# $# \n
Loop 1 cycle 2:
$# $# $# \n
$# $# $# \n
$# $# $# \n
$# $# $# \n
$# $# $# \n
etc.
If you just wanted to echo it 10 times, WHY ARE YOU USING A SECOND LOOP?
For loops have NOTHING to do with printing things to specific parts of the screen. You can't print a character on a specific row or column on the screen with it. (Well you could but if you just wanted to do that there are easier ways that are way less CPU intensive)
RTFM?
http://cprogramminglanguage.net/c-for-loop-statement.aspx
Seriously, your teacher should have taught you at least this much ~__~;; program flow control is about the only concept people really can't do without.
Kopravich
02-04-2010, 20:04
Well, my teacher is foreigner, comes only once in two weeks and holds 57846582384 classes at once... It is no wonder a lot of us fail with programming >_>
But yeah, i understood my mistake... I have thought direction problem, when i do something on one way, then i kinda try to do all similar tasks on the same way...
therealnaruto
06-04-2010, 18:48
Any one here could help me with PHP?
Depending on what you want ~__~ I might.
therealnaruto
07-04-2010, 23:35
Say some one to correct my Noobish mistakes, give tips along the lines of making a game.
In that case, no. If you're a noob you shouldn't be making games in the first place, they'll just be made of fail.
therealnaruto
08-04-2010, 17:34
Well i know that it will take years of practise but that's my ultimate goal. It was becuase of you anyway why i got so intrested in programming.
PHP scripts are basic, go write something interesting instead.
therealnaruto
08-04-2010, 17:58
I would, but i want to start with PHP, when i get the hang of it i move on to javascript.
Kopravich
11-04-2010, 20:33
I don't actually see the difference between while and do while loop... Is there any practical one, apart from "do while" having to execute a loop at least once, while "while" can be not executed at all?
That's basically the difference right there, do while always executes once >_> nothing more.
Hunter666
12-04-2010, 18:38
I would, but i want to start with PHP, when i get the hang of it i move on to javascript.
If you're just starting you should begin with more isolated scripts like member registrations, logging in, and a chat system.
With something with so many interrelated scripts like a game, you'll end up having to do a lot of back tracking as you get better to adjust scripts for purposes you had no clue about when you started
More so than that, before you do a game... make sure you understand the principles of OO >__> otherwise managing your code will be a huge pain in the not so proverbial ass.
therealnaruto
12-04-2010, 22:57
OO? Object Orinated?
Kopravich
12-04-2010, 23:01
Object Oriented!
Kopravich
14-04-2010, 17:25
2.)Write a program which calculates and prints the values of following real function:
y=(x2-2x+2)/(x+5)
if x changes from Xp to Xk with the step of h.
My solution:
#include <stdio.h>
main()
{
float x,y;
int Xp=0,Xk=0,h=0;
printf (" Enter the values for Xp, Xk and h:");
scanf ( " %d %d %d ", &Xp,&Xk,&h);
for (Xp = Xp; Xp <= Xk; Xp++)
{
x=Xp + h;
}
y= ( x*x - 2*x + 2 ) / ( x+5);
printf( " Value of the function y is %y ", y);
}
What did i do wrong?
- You're doing the calculation for every value between Xp and Xk and it says to increment with h
so instead of Xp++ you should do Xp += h
- The actual formula is not in your for loop... so it only calculates once
You want both the echo and the calculation in your loop.
printf (" Enter the values for Xp, Xk and h:");
scanf ( " %d %d %d ", &Xp,&Xk,&h);
for (Xp = Xp; Xp <= Xk; Xp += h)
{
y= ( Xp*Xp - 2*Xp + 2 ) / ( Xp+5);
printf( " Value of the function y is %y ", y);
}
might not be compile-ready, but gets the point across.
Kopravich
14-04-2010, 17:38
Ah, got the point, but i can't get it working... When executed, it just displays me to enter the values and then nothing happens... Program doesn't want to terminate, there is no " press any click to continue" and nothing else happens...
Then you screwed something up, probably an endless loop.
Debug echoes FTW. I'm not psychic ~__~ I can't remotely debug your code.
Kopravich
14-04-2010, 17:47
#include <stdio.h>
main()
{
float y;
int Xp,Xk,h;
printf (" Enter the values for Xp, Xk and h:");
scanf ( " %d %d %d ", &Xp,&Xk,&h);
for (Xp = Xp; Xp <= Xk; Xp += h)
{
y= ( Xp*Xp - 2*Xp + 2 ) / ( Xp+5);
printf( " Value of the function y is %y ", y);
}
}
That is the whole code... Idk, everything looks ok and i still have to learn how to use debugger...xD
You do realize running the debugger is as easy as pushing a button ~__~;;
Kopravich
14-04-2010, 17:57
Yes, but i don't know what to do when it starts... It looks the same as execution, no values are displayed in that window which opens at the bottom, so i can't follow what happens with them...
Wouldn't have helped, because I'm going to take a wild guess and say you raped your scanf statement, since it never gets beyond that.
And considering I have it working now I can guarantee it >_> I should have seen it right off the bat but I'm tired.
There's too much spaces in your scanf.
scanf ( "%d %d %d", &Xp,&Xk,&h);
instead of
scanf ( " %d %d %d ", &Xp,&Xk,&h);
you're not going to type space(number)space(Number)space(number)space as a user, that's plain retarded and causes the program to crash because it gets a space when it expects a number, and vice versa.
Kopravich
14-04-2010, 18:14
lol, noone ever told me that *kicks the professor*
Anyway, thanks... I was starting panicking already xD
Because it's common sense, sort of >-> in any other language this would throw exceptions all over the place. But C isn't that advanced, and relies heavily on the intelligence of the code monkey.
Still, it's less retarded than your for loop error. That was plain logic fail.
kyubichan
15-04-2010, 03:32
There are things that the professor won't tell, mainly because he/she expects you to know it already. But you can always ask how and why something does not work.
C is way down the language hierarchy, closer to mid level than to high level languages. So, as Aet-chi said, it relies on the programmer. If you fail, the program fails. On a positive note, if you can get used to C, it'd be easier for you once you move on to other programming languages since some of them are based on C's structure, and your logical analysis would've ... improved (?)
Kopravich
15-04-2010, 14:24
Well, i am glad i am learning C... It is quite difficult for a complete n00b, but i suppose it will pay out eventually...
Kopravich
06-05-2010, 18:20
New problem:
Write a program which prints the first 2*M numbers dividable by 2 and in range 100 - 1000!
Enter M from the keyboard!
My solution:
#include <stdio.h>
main()
{
int solution,M,counter;
printf ( " Enter M\n");
scanf ( "%d", &M);
if ( solution > 99 && solution < 1000 && solution % 2==0)
{
for( counter = 1; counter <= 2*M; counter++)
printf ( " \n%d", solution);
}
}
Where did i fail?
Everywhere?
first:
if ( solution > 99 && solution < 1000 && solution % 2==0)
this never evaluates to true, because solution is never initialized. The value remains whatever is in memory at the time the program runs.
Second, this program does not check if something can be divided by two.
How do you check that?
int number = 6;
if(number % 2 == 0){
printf("this number can be divided by two");
}
else{
printf("this number cannto be divided by two");
}
So you need to:
- initialize solution at 100 (because the range is 100 - 1000)
- use an if clause IN the loop, not outside it because the if clause outside the loop is only evaluated once.
- make the if clause from the previous point check if number % 2 == 0
- keep count of the number of solutions with a counter int
- stop the loop if 2*M solutions have been found
I don't feel like making compile ready code today, busy with my own impossible C/C++ error concerning OpenGL and camera geometry.
Kopravich
06-05-2010, 20:33
Awww, i solved it... xD
First time i actually used modular solving and it is much easier when i figure it out step by step, not everything at once :-)
Anyway, here it is:
#include <stdio.h>
main()
{
int solution=100,M,counter=1;
printf ( " Enter M\n");
scanf ( "%d", &M);
while ( solution >99 && solution <1000 && counter <=2*M)
{
if ( solution % 2==0)
{
printf ( "\n%d", solution);
counter++;
}
solution++;
}
}
Now i have to do it with for and do while loops :-)
same thing, different syntax .-. you can just use the 'solution' counter for the for loop and do a break when 'counter' exceeds 2*M to exit the for loop .-.;;
as far as the do while goes, that's just a while loop that always executes once. Which is not a problem in this scenario. Since the loop is designed in a way that should always execute at least once anyway.
Unless someone is stupid enough to enter zero...
Kopravich
06-05-2010, 20:59
Our teacher doesn't allow us to violently break the program... She says that is not the way the structural programming should be done... But eh, if the syntax allows it, why not?
By the way, there is a flaw my code... It doesn't print 100 as a first number >_>
*goes to repair*
Kopravich
06-05-2010, 21:16
Lawl, can't fix it actually... >_>
Halp!
Btw, do while solution:
#include <stdio.h>
main()
{
int solution=100,M,counter=1;
printf ( " Enter M\n");
scanf ( "%d", &M);
do
{
if ( solution % 2==0)
{
printf ( "\n%d\n", solution);
counter++;
}
solution++;
}
while ( solution >=100 && solution <1000 && counter <=2*M);
}
I said break the loop, not break the program *paper fan*
~___~;;
That's because you do solution++ before the if clause, always do ++ as the last thing you do in your loop. Just for consistency.
EDIT: Oh, never mind, you just did an indentation fail... ...
Hunter666
07-05-2010, 03:48
Why don't you just add 2 to solution instead of incrementing it by one .-.; It'll have to loop half as much and eliminate the need for an if statement....
int solution = 100;
//While loop
int counter = 1;
while (counter <= 2*M && solution <= 1000) {
printf("%d\n", solution);
solution += 2;
counter++;
}
//For loop
for (int counter = 1; counter <= 2*M; counter++) {
if (solution > 1000)
return false;
printf("%d\n", solution);
solution += 2;
}
Hush, don't teach him optimizations like that >_>;;
Kopravich
07-05-2010, 14:09
Finished with for loop, as well... And btw, that optimization crossed my mind, but i decided not to experiment and go more basic way... Anyway, i used the trick in the code below:
#include <stdio.h>
main()
{
int solution=100,M,counter=1;
printf (" Enter M\n");
scanf ( "%d", &M);
for ( solution=100;solution<=999;solution+=2)
{
if ( counter <=2*M)
{
printf ( "\n%d", solution);
counter++;
}
}
}
Assigment done... I had this on my exam, but failed to do it correctly back then. Unfrotunatelly, we had to do it on paper, so i couldn't test and fix my mistakes, but i really figured out some things now... Thank you guys xD
Coding on paper == fail.
Fire the professor that made you do that ~__~;; coding on paper takes 5 times as long, and you're 5 times more prone to make errors you wouldn't make when typing.
Simply because your brain actually has to spend time on writing, whereas typing happens more or less on autopilot.
Normal writing does as well, but brackets and crap get in the way of that...
*throws spinning cubes of doom at professor*
Kopravich
07-05-2010, 15:13
Well, that is the way we do programming exams... I was doing the exam for slightly more than 3 hours, so imagine how much overloaded my brain was.
Not to mention that some idiotic assitent thought that i was cheating... howtf i can cheat on programming,especially when doing it on paper??? >_>
But still, coding on paper has its advantages, when it comes to learning....
>_> I have yet to see any of those advantages... the only thing you want to do on paper is pseudo-code.
The outline of the program and it's functions without actually doing all the nitty-gritty pointer stuff.
Kopravich
07-05-2010, 15:43
Well, it improves your concentration, makes you really focus on the code, think much more because you can't rely on complier etc...
Btw, i got new assigment:
"Write a program in C which calculates the value of the following mathematical expression:
E=2*d-3/c+a/b
where are:
b and c are integer variables who values must be entered from keyboard
a is an integer variable which needs to be initialized upon declaration at the value of a=10
d and E are real variables ( type double ), but the value of d must be entered from the keyboard
Print the solution on the screen adjusted on 3 decimal places.
Enable the process in program which enables b and c to be entered again and again, just until zero
is entered as a value for one of them..."
As much as i understood, this last things needs to repeat the whole program, not just the process of scanning...
I am going to try to do something on my own now, but posted just so you can think about it in case i fail to do it alone xD
Nekomata Kayangelus
07-05-2010, 21:49
#include <stdio.h>
main(){
int a = 10, b = 1, c = 1;
double d, E;
scanf("%lf", &d);
while(b*x != 0){
scanf("%d %d", &b, &c);
if(b*c == 0)
{
continue;
}
E = 2*d - 3/c + a/b;
printf("%.3lf", E);
}
since my comp that has a compiler on it is a pain to log in with, I might have a typo or two in there. Also, I'm sure there is a more efficient way to do it...
Kopravich
12-06-2010, 23:54
Why the bloody thing don't want to work?
#include <stdio.h>
main ()
{
int array[10],i,sum;
float arithmetic;
printf ("Enter 10 numbers");
for ( i=0;i<10;i++)
{
scanf ( " %d", &array[i]);
sum += array[i];
}
arithmetic = sum/10;
for ( i=0;i<10;i++)
{
if ( array[i] < arithmetic)
printf ( "Number with lower value than arithmetic are %d", array[i]);
}
}
The whole point of the assignment is written in the last printf
Let's see what you're doing here:
for each number from 0 - 10 you place a signed integer in an array at position 0 - 10, this is an array containing signed integers, no problem there.
then you try to increment sum with the contents of array[i], should also work :/
then you divide sum by 10, fine and dandy.
And then you loop over all array elements (a for loop is not the best way to do that)
And print a blob of text if the number is lower than arith-bleh.
Oh looksie, you forgot the \n so everything is printed on one line.
also:
#include <stdio.h>
main ()
{
int array[10],i,sum;
float arithmetic;
printf ("Enter 10 numbers");
for ( i=0;i<10;i++)
{
scanf ( " %d", &array[i]);
sum += array[i];
}
arithmetic = (float)sum / 10;
printf("Numbers with lower value than arithmetic (%f) are:\n",arithmetic);
for ( i=0;i<10;i++)
{
if ( array[i] < arithmetic)
printf ( "%d \n", array[i]);
}
}
Cast Sum to (float) before the division, otherwise the result is handled as an int and is rounded before being dumped in the float
\n, use it >_>
that was about the only problem. I added a print of the value of arithmetic so you can SEE WTF it's comparing with.
This process is called debugging, use it ~-~
Kopravich
17-08-2010, 14:00
Few questions to answer pl0x...
1. Is it possible to name a database with a C source code as "Example.txt" ?
Nope, right?
2. ("A") is a sign for 2 characters, A and 0, right?
3. Operators have more, less, or equall priority as brackets?
4. Relation operators has higher, lower or equal priority as logical operators?
5. Operators increment and decrement are higher, lower or equal priority as other aritihmetic operators?
6. Which type conversions C compiler does automatically:
a.) char => int, int => long
b.) long => int, int => char
c.) None of them
It should be a, right?
Thanks in advance!
1. Is it possible to name a database with a C source code as "Example.txt" ?
The hell is with this question? Is it a database or C source? Make up your mind.
A database "with" C source makes absolutely no sense whatsoever.
You can stuff C source code OR a plaintext database in a file named example.txt ~__~;;
2. ("A") is a sign for 2 characters, A and 0, right?
Depends on character encoding <_<
Unless I'm missing some kind of language constant...
3. Operators have more, less, or equall priority as brackets?
Oh come on, you know this one ~__~;;
4. Relation operators has higher, lower or equal priority as logical operators?
Just consider how such a thing is resolved and you'll have your answer
(x == 5 && y == 4)
5. Operators increment and decrement are higher, lower or equal priority as other aritihmetic operators?
Depends on the compiler, the C language standard does not specify. There's also the difference between ++x and x++
Kopravich
17-08-2010, 20:50
Thank you...
Sorry for the first question, i have no idea why did i write database. I should have written "file", sorry...
And regarding the last question, your answer is not among the answer i can pick... My professor probably failed with this one >_>
Quite possible, if you want the answer your professor wanted, use your compiler to compile some examples to see how the priority is handled.
It's quite possible there is no difference in priority between x++ and ++x, I've never actually used that in a fashion where it was relevant. (I shy away from increments in actual calculations, and as such I can't give you an immediate answer on operator priority there either. I'm a code monkey not an encyclopedia, I look things up rather than remembering everything)
But yes, you can insert C code in a file named example.txt and compile that ~__~ since the .c extension isn't a requirement for most compilers, it's just a way to organize your files properly.
All that matters is that the code is valid.
Kopravich
14-09-2010, 17:02
Since i forgot to let everybode know, i passed the programming exam, with quite good score. My next course will be C++ , with much more difficult assigments, so this thread could serve for that purpose.
Anyway, thanks to everyone who helped me, especially Aet. I really improved a lot, even my teacher acknowledged that. In fact, she thinks that i am the student which improved the most ;-)
>_> well you know what to do when you're stuck.
I'm not an expert on C++, but my experience in general allows me to easily devise or google solutions.
You doing OO C++ or ye olde procedural?
Kopravich
14-09-2010, 17:15
I have no clue... I will have two programming courses on next year, called:
1.) Programming languages
2.) OO programming
I don't know what we are supposed to study in there, but i heard from some students that we are going to do C++ first. And since "Programming languages" is the first course, i can't know. But we will surelly do some OO in the other course, but not sure for this one. Maybe we will do some procedural and get basics in OO before moving completely to OO.
I have no clue... I will have two programming courses on next year, called:
1.) Programming languages
2.) OO programming
I don't know what we are supposed to study in there, but i heard from some students that we are going to do C++ first. And since "Programming languages" is the first course, i can't know. But we will surelly do some OO in the other course, but not sure for this one. Maybe we will do some procedural and get basics in OO before moving completely to OO.
Programming languages probably covers he various scripting langauges. At least, that was what my course in programming langauges was... mine had either minimal or no OO in it
In my case programming languages goes into paradigms and stuff like that >_> but that's way overkill for someone that hasn't even learned OO.
Kopravich
14-09-2010, 20:34
I suppose that we are going to do something like Ino. But i still can't confirm anything.
I'll ask some older student, so i could go little ahead of course...xD
getmoney216
15-09-2010, 04:42
I gotta say C looks way harder than PHP xD
Kopravich
15-09-2010, 12:59
I gotta say C looks way harder than PHP xD
I wouldn't know, never bothered with PHP much enough xD
Anyway, C syntax looks kinda intimidating, but it isn't that difficult. As soon as you learn some background behind programming and computers in general, then understand how to manipulate elements in arrays, you are quite much covered the basics.
But be aware that things done and displayed in this thread are far from programming... These are just basics ;-)
It's not the C syntax that's intimidating, since A TON of languages use a C like syntax.
java, C#, C++, PHP, ASP.net the popular languages out there.
Things done in this thread are still programming. They might be the basics but they're meant to give you some insight into both language mechanics and syntax. As well as giving you a treshold into data structures and algorithms later.
Are you making full software? No, obviously not. But the key part of software is the business logic, which won't really look too different from what you do here, mostly.
The only thing you're completely unfamiliar with now would be OO (isn't in C) and GUI programming.
In terms of the latter, you do not want to do that without OO, it's horrid. And GUI's aren't cross-platform unless you use something like GTK or QT.
Kopravich
24-11-2010, 20:06
/*Assignment 9:Write a program for entering data about dimensions of geometric figures, or better to say, elements of union type which in the same memory space save the data about the dimensions of a circle ( radius), rectangle ( chains a and b ) and triangle ( chains a,b,c ) and prints the circumference of all the figures.*/
#include <stdio.h>
#include <math.h>
main()
{
struct rectangle
{
float a;
float b;
};
struct triangle
{
float a;
float b;
float c;
};
struct figure
{
int type;
union
{
float r;
struct rectangle p;
struct triangle t;
};
} figures[50];
int n, i;
double o=0;
printf("Enter the number of figures\n");
scanf("%d",&n);
for (i=0; i<n; i++ )
{
printf("Enter the type of figure (0-circle, 1-rectangle, 2-triangle)\n");
scanf("%d", &figures[i].type);
switch( figures[i].type) // !!!
{
case 0:
printf("Enter radius\n");
scanf( "%f", &figures[i].r );
break;
case 1:
printf("Enter the chains of rectangle\n");
scanf("%f%f", &figures[i].p.a,
&figures[i].p.b);
break;
case 2:
printf("Enter the chains of triangle\n");
scanf("%f%f%f", &figures[i].t.a,
&figures[i].t.b, &figures[i].t.c);
}
}
for (i=0; i<n; i++ )
{
switch( figures[i].type) // !!!
{
case 0:
o+=2*3.14*figures[i].r;
break;
case 1:
o+=2*(figures[i].p.a+figures[i].p.b);
break;
case 2:
o+=figures[i].t.a+figures[i].t.b+figures[i].t.c;
}
}
printf("Circumference of all figures is: %f\n", o );
}
I think i translated everything correctly...
Ok, walk me through this whole structure declaration process. I get most of it, but this union things bugs me. This is probably the most critical thing for me to understand. And pay attention for the !!! comments. Care to explain the syntax in the brackets?
And i get all the logic, don't bother with that. I jsut have issue with structures, their syntax and why they are declared the way they are...
the struct syntax is simple
struct <identifier>{
<variable type> <variable identifier>;
}
There's nothing more to it.
Afterwards you can call or manipulate items from the struct with
<struct var identifier>.<variable identifier>
A union is a different data type, with the same syntax (although with union, rather than struct, duh)
in a struct, everything is allocated in one continuous space on the stack (or heap, the exact implementation in C eludes me, even though I know how it's done in C++), whereas with union, everything is in the same storage space
essentially, a union is a pointer to a single memory address, which can be interpreted in different ways. In your case, your piece of memory can either contain a struct rectangle, a struct triangle, or an float r, depending on what type of figure it is (a rectangle, triangle, or a circle)
You'll never see this in modern languages, because you'd just use polymorphism to achieve the same result of being able to map multiple types of values in the same address space depending on non-compile-time variables.
Kopravich
24-11-2010, 20:23
Oh, i kinda get it now... My biggest problem was with the struct rectangle and struct triangle ( those before the figures structure). Is it necessary to define these two structures or it can be done without it?
If you want to use them -__- you obviously have to declare them >_> what are you getting at?
The only define I know of is the #DEFINE but that's for constants <_<
yes you can use them with typedef but I suppose that's not what you were after.
it's 22:30 here so I might be missing something obvious.
Kopravich
24-11-2010, 20:31
Ugh, let me rephrase. Was i obligated to make structures for all the variables regarding their respective figures or i could declare all of them independently and use them as variables of struct figures?
This is kinda messy, but i really hope that you udnerstand me. I am not sure how to explain this...
Code it out -__- that's the only damn way to understand WTF you want.
Yes it is possible to do what the structs do without using the structs. But there is absolutely no reason whatsoever why you would want to. Since each struct consists of multiple points of data.
To do it without the structs would result in something like this:
struct figure
{
int type;
float a;
float b;
float c;
float r;
} figures[50];
which is messy (less readable), and uses up more memory since you can't use the union.
You can't use the union because you have multiple data points that are either used, or not used depending on the integer value. And since they're all floats a union is pointless.
(you can use unions with non-structs by the way, so let's not get confused there)
Kopravich
24-11-2010, 20:41
Something like this:
float rectangle_a;
float rectangle_b;
float triangle_a;
float triangle_b;
float triangle_c:
struct figure
{
int type;
float p;
float t;
}figures[50];
Or actually, when i think about it, you did what i wanted... I was referring to exactly what you wrote above!
That wouldn't work at all because you only have two floats inside your figure, and you need THREE for a triangle >_>
The figure specific floats are outside of the struct, so you only have one of each, even if you have 50 figures, they'd all have the same dimensions.
Did they teach you NOTHING in that hell-hole over there?
Kopravich
24-11-2010, 20:58
And if i put everything into the struct?
And as i said, i was forced to miss majority of the programming classes. My life was chaos in last time and attending school wasn't the option. Or at least, it wasn't the option at the days when i had programming lessons. And to make it even more ironic, my college was one of the culprits for such chaos... But that's irrelevant anyway!
what is "everything"? >_> everything is ABSOLUTELY EVERYTHING which is impossible, so you must mean a subset of everything.
Since you can't put methods into structs you can't put everything into structs >_>
Unless you mean putting all the variables into the struct, which I already did in my first example:
struct figure
{
int type;
float a;
float b;
float c;
float r;
} figures[50];
<_< works, but isn't good for the exact reason I specified earlier. At least read the damn posts.
Kopravich
09-02-2011, 20:02
Quick question:
Lets say i have some int i=888.
If i go:
b= i % 10;
The value of i didn't change, right?
The value of i should still be 888, yes.
If it is not you did something else that borks i.
Kopravich
09-02-2011, 20:13
Got it. I am trying to figure out an algorithm which will extract me digits with the highest and second to highest "weight" from the multi digit numbers, but without changing the value of the numbers and write down those extracted digits into whatever.
For the digit with the highest "weight" ( Idk how to translate it properly, it is the same thing like the first bit into a byte), i thought about dividing the number with 10 all the way until its value is beyond 10. That would be the first number .
For the second one, i would use the same thing, but just do "%" instead of "/" in the last divide.
This should work because they are integers, but something is causing me problems.
However, this is part of much larger project, so it is difficult to debug it >_>
You should be able to just debug the single unit. There's no reason why you can't just run a single function in a debug context...
But for any real advice I'll need a numbers example, because I can't understand how you actually get this 'weight' right now.
Kopravich
09-02-2011, 20:25
I figured it out. One loop was giving me issue, but i solved it now.
Anyway, lets take number i= 1234567 as example.
Value with the highest weight is 1.
Value with the lowest weight is 7. ( Its just like bytes and bits)
In my thing, i want to get the first two with highest weight, which are 1 and 2.
And how do i do it:
I keep diving this number with 10, in the loop "while ( i>9)"
Since the number is integer, my last value with be 1, which i what i want.
For the second one, I'll do the same, but will put i>99 in the loop, which will result me in having 12 as outcome. Then i just go a single %10 and i get 2.
And now i feel proud xD
Should be a way to do that that doesn't involve a loop... since the most significant digit (which is what it's called) is always the first one. And you can probably figure that out easily just from the binary representation.
My insight isn't thus that I can say for certain that this would work. But I'm 100% sure there's a better way.
A loop is just a performance hit you want to avoid if possible.
Kopravich
09-02-2011, 20:35
Maybe if i turned the number into a string and then just read the first character from the string?
And yea, it works flawlessly! xD
C has no strings, you'd have to somehow cast all the individual digits into chars.
Which is silly since for that you have to be able to see all individual digits, and the char cast becomes useless.
A quick google shows this is an algorithmic problem (as I kind of figured) that has more in its roots than simply calling a function or two (unless you're on hardware with specific bitwise instructions and more of that sweet stuff, but meh) and your %10 approach is the mostly used brute force one.
so gg.
Kopravich
09-02-2011, 20:44
C has no strings
o.O
I worked with string many times before, in C.
Strings are arrays of chars, right?
If yes, then C definitely supports them!
o.O
I worked with string many times before, in C.
Strings are arrays of chars, right?
If yes, then C definitely supports them!
arrays of chars != strings.
the datatype for strings is different than an array.
What Ino says, while a string is often displayed as an array of chars, in modern languages the String is a built-in datatype with some added functionality you wouldn't have with a char array.
C supports char arrays,yes. But not Strings in any form other than a char array. And you cannot cast an integer directly into a char array (if you convert an int to a char it uses the ASCII table to determine the character in question, it doesn't convert the integer '145' to the char array [1][4][5] or even a string '145' like say, Java might.)
Kopravich
09-02-2011, 21:30
Oh, i get it... Well, array of chars is the only string i know of.
Bah, whatever, i just had to figure out the algorithm, i wasn't obligated to make it memory efficient...
But i still want to find a better solution!
it is memory efficient, it's just not clock cycle efficient.
I've seen some algorithms pass by that use bit shifts to figure this out. But meh.
Kopravich
10-02-2011, 11:21
Uh yes, that is what i meant.
And i figured out another way to do it, but it involves some IFing and even CASE-ing, but the code becomes horrible looking. o.o
But at least it is better for the performance xD
Kopravich
11-05-2011, 18:03
public ComplexNumber (int r)
{
real = r;
imaginary = 1;
}
public ComplexNumber (int i)
{
real = 1;
imaginary = i;
}
Umm, in case I want to initialize two object with these two constructors, how will complier know which one I am actually using? o.o
This should trigger a compiler error, the two objects are ambiguous, which is impossible in C. The methods need two distinct signatures. Both of the signatures here are
ComplexNumber(int)
Either have
ComplexNumber(int,int) and just add the 1 manually.
Or have ComplexNumber()
and then have setReal(int) and setImaginary(int)
As you imply, the compiler can't tell which one you're using if you do it this way, because the signatures are identical.
public ComplexNumber (int r)
{
real = r;
imaginary = 1;
}
public ComplexNumber (int i)
{
real = 1;
imaginary = i;
}
Umm, in case I want to initialize two object with these two constructors, how will complier know which one I am actually using? o.o
It won't. i don't remember exactly what will happen, but i'm pretty sure you will get a compiler error.
Just change the name? or make an if statement in one to figure out what you want declared to what?
Ino, he can't change the name because it's a constructor. And changing the variable name changes nothing because the signature doesn't look at the name of the variable in the local scope.
An if statement would mean also supplying a bool, it's an ugly solution. Best he just does ComplexNumber(int,int) then to keep the code more logical.
Kopravich
11-05-2011, 18:12
I found it weird, as well, but that is what I had to do in some previous homework. I just forgot to ask... I did it another way and teacher didn't complain, but my task was specifically that.
Now I am in the process or removing all the confusing I had so far, so I might have few questions. I really want to understand this stuff as much as I can..
Thx for the answers anyway...
If this is what you HAD to do, then I'm pretty sure you did it wrong, or remembered wrong. One of the constructors was probably overloaded and had a different signature >->;;
By the way, if you have objects and constructors. You're no longer in C, you're in C++ D: I see what you did thar.
Kopravich
11-05-2011, 18:15
If this is what you HAD to do, then I'm pretty sure you did it wrong, or remembered wrong. One of the constructors was probably overloaded and had a different signature >->;;
By the way, if you have objects and constructors. You're no longer in C, you're in C++ D: I see what you did thar.
I did it the other way, calling constructor with two parameters. I guess you missed the edit ^^
And yea, it is C#, i forgot to mention :-)
Bleh, C#.
Well doesn't work any differently since overloading is consistent in all of those languages. but next time you do a language switch, tell us.
Could be relevant ~_~
Kopravich
23-05-2011, 14:38
Any of you know a way how to emulate multiple inheritance in C#?
Its lack of support for such feature bugs my mind >_>
Any of you know a way how to emulate multiple inheritance in C#?
Its lack of support for such feature bugs my mind >_>
First hit from a google search of "Multiple inheritance c sharp" (http://www.c-sharpcorner.com/UploadFile/cbreakspear/MultipleInheritance11082005004843AM/MultipleInheritance.aspx)
edit: secondary link (http://stackoverflow.com/questions/178333/multiple-inheritance-in-c) from a couple links down on google.
Any of you know a way how to emulate multiple inheritance in C#?
Its lack of support for such feature bugs my mind >_>
More interestingly, WHY do you want multiple inheritance? In any normal OO application there is no reason whatsoever to use multiple inheritance.
You only need it in C++ because it doesn't have interfaces.
Ino's first link basically describes this. But I'm curious as to your reasons.
Kopravich
23-05-2011, 14:44
@ Ino:I was more thinking something like emulating multiple inheritance with single inheritance, not using interfaces or whatever.
It might hit me on the exam and I am not allowed to use something I didn't learn, like interfaces and stuff...
@Aet:
I have a new OO teacher which loves to make students to weird things. Remember the constructor issue thing?
Well, I have a feeling that he might make us emulate multiple inheritance and learning interfaces is not in plans for now...
They simply cannot ask you to use multiple inheritance on an exam where you are supposed to use C#. It cannot, and it will not happen.
If it does, you're allowed to shoot them because C# does not support it, and there is rarely ever a logical reason to do it. Especially at the level of your classes.
So don't bother.
Kopravich
23-05-2011, 14:49
They simply cannot ask you to use multiple inheritance on an exam where you are supposed to use C#. It cannot, and it will not happen.
If it does, you're allowed to shoot them because C# does not support it, and there is rarely ever a logical reason to do it. Especially at the level of your classes.
So don't bother.
I so imagine myself quoting this post of yours when he gives me multiple inheritance on the exam ^^
And yea, I guess there is no reason to bother then.
However, I will check it out... To learn interfaces, if for nothing else.
well, they can.
Some professors seem to get off asking those types of things, that are semi-useless in life.
I also said that assembler programming was useless, and if i ever found myself in a job that uses assembler to shoot me. Well, guess what? My job occasionally uses assembler. And i havent shot myself yet.
They should have taught you about interfaces ,if not the education of the Object Oriented paradigm is sorely lacking. Especially if they expect you to use C#.
And yes, you can quote me on that. And ask them what the reason is to use multiple inheritence in that specific assignment as opposed to single inheritence with interfaces >_>
well, they can.
Some professors seem to get off asking those types of things, that are semi-useless in life.
Teaching people to use multiple inheritance when it's not strictly required undermines proper software design. Unlike learning assembly. Telling people to use it will hurt them in the long run, and as such is bad practice unless the conditions in which it is to be used is STRICTLY adhered to and explained.
Which they were obviously not. On top of that the language itself doesn't support it. Hell, the only language IN THE WORLD, that supports multiple inheritance is C++.
Kopravich
23-05-2011, 15:00
well, they can.
Some professors seem to get off asking those types of things, that are semi-useless in life.
I also said that assembler programming was useless, and if i ever found myself in a job that uses assembler to shoot me. Well, guess what? My job occasionally uses assembler. And i havent shot myself yet.
Haha, irony, isn't it? ^^
But yeah, they can ask whatever they want. Which doesn't mean that they should o.o
But meh...
They should have taught you about interfaces ,if not the education of the Object Oriented paradigm is sorely lacking. Especially if they expect you to use C#.
And yes, you can quote me on that. And ask them what the reason is to use multiple inheritence in that specific assignment as opposed to single inheritence with interfaces >_>
They should have teach me many things, but they prefer overloading me with useless math and engineering stuff which isn't associated with programming in any way. IT makes around 15% of all subjects on this year, which is severe minority. That's the drawback of going on a college where there is only one course you are interested in. And that is the only college I can go for IT course, so... Bah, I can't wait to end this year and start with the real stuff. >_>
EDIT: I thought that C# was the only OO language which doesn't support that feature. I thought that multiple inheritance was of the vital importance, given how our teacher presented it o.o
Kopravich
05-01-2012, 14:42
This might get back to life, but this time... for Java purposes o.o
Now quick question:
When you want certain method to be overridden in sub class, do you need to label that method with something in super class ( like it was done with "virtual" in c#) or that method can be overridden as soon as that class is inherited?
A method can be overridden as long as the method is not explicitly declared with the final keyword. Also, the method of course needs proper visibility at that point (protected or public. not private)
If you want to ensure it is implemented in a child, rather than in a parent, make it an abstract function (a function without a body) though in this case you'll need an abstract class. AND will have to ask yourself if you shouldn't be using interfaces instead.
Yes, slapping you with interfaces again, because I got curious if they finally saw fit to teach you proper OO paradigms.
With all your education you should now know more than me. If not they're doing something wrong.
Kopravich
05-01-2012, 18:32
They are doing something very wrong. Apart from throwing at you dozens of classes I'll never need ( advanced math and eletrical engineering stuff ), they teach you basics of C, then repeat the same with C# ( although the basics of OO are also there ) and then... guess what... they repeat the same with Java >_>
So, 75% of my education so far is worth nothing >_>
However, things should be better in next semester, where all of my classes are going to be IT related and coupled with last year, that's 16 pure IT classes, but that doesn't change the fact that I pretty much wasted two and a half years of my education :/
Only good thing about this Java course is teaching us some project management, version control software and such, so we are better prepared for real world projects.
Anyway...
I see then. I know about interfaces now, but I am still struggling to understand them properly. I am not sure what is the point of them when I have to implement their methods in every class I decide to inherit them.
Multiple inheritance sounds better to me, but as I said, my head is in mess when it comes to properly grasping OO.
I see then. I know about interfaces now, but I am still struggling to understand them properly. I am not sure what is the point of them when I have to implement them in every class I decide to inherit them.
Multiple inheritance sounds better to me, but as I said, my head is in mess when it comes to properly grasping OO.
*dons teacher-like apparel. Imagine the 11th doctor >_>*
Warning, this explanation may not make any sense.
The point of interfaces is to ensure that all the classes that implement an interface have the same functions. So that you can use them in a more generic sense without knowing the specialized object it is. There are numerous OO patterns that rely on this behavior.
You don't inherit interfaces (unless you're making child classes of an interface, but that would also be an interface.) you implement them. If you want predefined behavior, you'd use an abstract class. With inheritance. The cut-off point here is whether or not all your classes need member variables and predefined behavior rather than common methods.
Multiple inheritance has flaws, flaws your professor probably failed to mention, since he was apparently a multiple inheritance evangelist. Which means he himself doesn't understand the OO paradigm all that well.
Although multiple inheritance can assure that you have all the required functions much like with interfaces. An object that inherits from many different parent classes has inherent problems determining hierarchy. The diamond problem is the most obvious one.
Diamond problem reading (http://en.wikipedia.org/wiki/Diamond_problem)
In C++ the inheritance has problems of it's own, as inheritance there is nothing more than sticking the inherited from object WITH the rest of the object. Essentially increasing object size and memory footprint significantly if the same class is extended by multiple parents.
An interface is something that mostly helps clean up your code for re-usability. It can also be used to standardise communication between modules of your application. By having them all implement the same interface, you ENFORCE the fact they all have a certain method of communication to each other. And to the outside world. You could theoretically implement all functions in all of them anyway, but you'd have no way of enforcing it. And without having a single class or interface they all inherit from or implement you can't group all the elements in a single data structure without losing the ability to call their member functions (good luck finding out what type of object something is once you've put it into a void pointer.)
I'd advise reading a _good_ book on OO, I might delve into the internets to see if I can find you one. I think the one they shoved down my throat was dutch, so that won't help you much. But there might be an english version around.
Also read up on The big four's OO design patterns (and anti-patterns) it'll be way more useful to you than listening to antiquated professors.
The 'basics' of OO tells you nothing about how the paradigm works, and why it works. It tells you nothing of the importance of clean re-usable code. It tells you nothing of program structure and ground rules such as low coupling, high cohesion. And just so the raptor doesn't eat me. Good reading (http://www.codeodor.com/index.cfm/2009/6/17/Strive-for-low-coupling-and-high-cohesion-What-does-that-even-mean/2902)
Kopravich
06-01-2012, 10:56
So, the point of interfaces is not to actually replace multiple inheritance, but enable other form of polymorphism. From what I understood, the only distinguishing benefit of using interfaces is the ability to enforce the class implementing interface to implement all the methods from the interface. Everything else could be done without them, I guess.
However, I am still stuck in that multiple inheritance mindset, but that will gradually drift away, especially when I know about that diamond issue. I can't even imagine what kind of horror that could produce when you are dealing with tons of class o.o
Kopravich
10-01-2012, 17:52
package data.read.implementation;
import java.util.Vector;
import data.read.interfaces.ReadFileStrategyInterface;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class X14Strategy implements ReadFileStrategyInterface
{
private String path;
public int numberOfLines() throws IOException
{
FileReader file= new FileReader(path);
BufferedReader reader= new BufferedReader(file);
int numberOfLines=0;
String line;
while((line=reader.readLine()) != null)
{
numberOfLines++;
}
reader.close();
return numberOfLines;
}
@Override
public Vector<?> readFile(String path) throws IOException
{
FileReader file= new FileReader(path);
BufferedReader reader= new BufferedReader(file);
int i;
int number_of_lines=numberOfLines();
Vector<String> data_from_the_file = new Vector<String>();
for(i=0;i<number_of_lines;i++)
{
data_from_the_file.add(i, reader.readLine());
}
reader.close();
return data_from_the_file;
}
}
This part is underlined with red:
public Vector<?> readFile(String path) throws IOException
And I am getting this error:
Exception IOException is not compatible with throws clause in ReadFileStrategyInterface.readFile(String)
Link to the file I have to read:
http://78.28.157.8:8080/redmine/attachments/download/345
The interface doesn't declare the function as throwing said exception? What does the interface look like?
Kopravich
10-01-2012, 18:04
package data.read.interfaces;
import java.util.Vector;
public interface ReadFileStrategyInterface
{
public Vector<?> readFile(String path);
}
That is the issue *smacks myself*
However, I did try removing that part and maintaining the same signature, but then I get "Unhandled exception type IOException" errors all over the method.
package data.read.interfaces;
import java.util.Vector;
public interface ReadFileStrategyInterface
{
public Vector<?> readFile(String path);
}
That is the issue *smacks myself*
However, I did try removing that part and maintaining the same signature, but then I get "Unhandled exception type IOException" errors all over the method.
That's because you need to catch and handle the error, einstein.
Kopravich
10-01-2012, 18:12
So, generic try/catch will solve the problem? I mean, it will, but I don't get it why I am forced to do that.
You're forced to do that because an exception COULD happen, and without a try/catch there, it wouldn't be caught anywhere, resulting in total meltdown of the application.
It's how java works, they explicitly declare what function throws what exception, so that it's impossible for exceptions to be thrown 'unexpectedly' and easy to tell if you've handled all possible error scenarios (at least exception wise)
Kopravich
10-01-2012, 18:33
I see... Well, that's a good thing then, but my pretty little method now looks awful :/
Anyway, moving on to algorithm, let me see if I can understand it. I'll scream if not ^^
Kopravich
11-01-2012, 18:17
umm, what this means: "Vector <?>".
Question mark interests me...
<> indicates generics, the question mark probably indicates the exact implementation isn't known. So it can return any type of implementation of the generic. But don't pin me on this.
Java generics are something I never actually really looked into, and I haven't touched java in a while.
Use the force of google.
If you google generics, you'll see my hunch was correct. Huzzah
As an example of an unbounded wildcard, List<?> indicates a list which has an unknown object type
Kopravich
11-01-2012, 19:44
Umm, question.
I have a certain class ( GraphNode) given, it's code is below. I have to make vector of that type (GraphNode) and store all nodes from the file inside that vector.
These are my nodes:
0->A->[6->1]->[2->2]->[1->3]
1->B->[13->4]
2->C->[4->5]
What does this mean? Example:
2->C->[4->5]
2 is index of the node, C is the value of the node, 4 is the weight of the branch going from the node and 5 is the index of the node which branch 4 goes into.
I have to parse them somehow, so I can store them.The problem is with those nodes who have multiple squares and data inside them. Since the constructor written in the class accepts only 4 values to be passed to it, things get little more problematic.
So, as much as I can figure it out, the only way for me to store these nodes in the vector is to parse the data like this:
0->A->[6->1]
0->A->[2->2]
0->A->[1->3]
1->B->[13->4]
2->C->[4->5]
and then pass the required data to the constructor?
Is that right?
Or there is a way to pass the entire nods to the constructor, without breaking it into multiple nodes?
package objects;
import java.util.Vector;
public class GraphNode
{
private Integer index = null;
private Object info = null;
private Vector<GraphEdge> edges = new Vector<GraphEdge>();
public GraphNode(Integer index, Object info)
{
setIndex(index);
setInfo(info);
}
public GraphNode(Integer index, Object info, Object weight, Integer lastNodeIndex)
{
this(index, info);
this.edges.addElement(new GraphEdge(index, weight, lastNodeIndex));
}
public void setInfo(Object info)
{
this.info = info;
}
public Object getInfo()
{
if (info instanceof String)
{
return ((String)info).toString();
}
return info;
}
public void setIndex(Integer index)
{
this.index = index;
}
public Integer getIndex()
{
return index;
}
public void addEdges(Vector<GraphEdge> edges)
{
for (int i = 0; i < edges.size(); i++)
{
this.edges.addElement(edges.elementAt(i));
}
}
public Vector<GraphEdge> getEdges()
{
return edges;
}
}
Only when I do that, I can proceed with Kruskal's algorhitm.
I'm not even sure what your problem is here...
Kopravich
11-01-2012, 20:34
How can I store this node:
0->A->[6->1]->[2->2]->[1->3]
into GraphNode vector?
Constructor for GraphNode accepts 4 values and this node has 8 values (0,A,6,1,2,2,1,3).
For nodes which have only 4 values ( like 1->B->[13->4] ), it is easy, but when I have more than 4, that is the problem.
I thought about breaking down the node which has more than 4 values in multiple nodes with the same index and value, but different other two values... Example:
This:
0->A->[6->1]->[2->2]->[1->3]
would be broken down to this:
0->A->[6->1]
0->A->[2->2]
0->A->[1->3]
That's because I believe that there is no other way, so I am asking you to either confirm or bash me :D
Breaking one node into four nodes completely corrupts your data structure. How the hell are you going to reliably compute the paths from any single node with reasonable complexity (both time and memory) if you need to loop over your entire node list an extra time?
Obvious answer: you don't.
Kopravich
12-01-2012, 08:50
I really don't have an idea what to do then. We didn't even mention these algorithms on the classes , nor anything regarding graphs in programming because they are planned for the next semester. :/
We just got the assignments and were told to research. And yeah, there is a deadline >_>
Fine then, a hint for the blind kid:
public void addEdges(Vector<GraphEdge> edges)
Now onwards.
Kopravich
12-01-2012, 09:26
Umm, this is weird. At the time when I copied the code here, it seems I had that method. Now I don't have it o.o
It was probably gone with the last update from the server, which means that someone was stupid when committing stuff.
Lemme check out the previous version of the project.
EDIT: Someone was stupid indeed. Rolling back to previous version...
Kopravich
18-01-2012, 17:41
Please help me diagnose this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: ">1"
Okay, it is obvious that number format is messed up and it occurs on the line when I try to parse string to int. But I am not sure how it is messed up... What would ">1" mean?
Please help me diagnose this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: ">1"
Okay, it is obvious that number format is messed up and it occurs on the line when I try to parse string to int. But I am not sure how it is messed up... What would ">1" mean?
Need code, it looks like you're trying to parse string ">1" toInt, which will fail because the parser doesn't know what to do with the > symbol.
Just a guess, but a pretty damn good one.
Kopravich
18-01-2012, 18:10
Code is kinda long and complicated, are you sure you want it?
Btw, that might be a cause. the file I am reading does have ">" symbol, but I wrote the method which removes it. But maybe that method doesn't work fine
Code is kinda long and complicated, are you sure you want it?
Btw, that might be a cause. the file I am reading does have ">" symbol, but I wrote the method which removes it. But maybe that method doesn't work fine
It probably doesn't, log the string to console before running that function, or put a breakpoint there in the debugger to see its value.
I'd be willing to bet on it.
Kopravich
19-01-2012, 00:02
I am desperate now, program breaks for no obvious reason. I tried debugging, but I can't figure out why it breaks and the error message just doesn't make sense. Debugger isn't even close to reaching that line where the error is the displayed when it breaks.
Please, could you run a debugger and check it out?
You'll need add these classes in the project:
/**
* Klasa tip cuva informaciju o granama grafa.
*
* @author Dijana
*
*/
public class GraphEdge
{
private Integer firstNodeIndex = null;
private Object weight = null;
private Integer lastNodeIndex = null;
/**
* Inicijalizuje {@code GraphEdge} objekat sa postavkama cvora iz koga grana
* izlazi, tezinu grane i indeksa cvora u koji grana ulazi.
*
* @param firstNodeIndex indeks prvog cvora
* @param weight tezina grane
* @param lastNodeIndex indeks drugog cvora
*/
public GraphEdge(Integer firstNodeIndex, Object weight,
Integer lastNodeIndex)
{
setFirstNodeIndex(firstNodeIndex);
setHeuristics(weight);
setSecondNodeIndex(lastNodeIndex);
}
public void setFirstNodeIndex(Integer firstNodeIndex)
{
this.firstNodeIndex = firstNodeIndex;
}
public Integer getFirstNodeIndex()
{
return firstNodeIndex;
}
public void setHeuristics(Object weight)
{
this.weight = weight;
}
public Object getHeuristics()
{
return weight;
}
public void setSecondNodeIndex(Integer lastNodeIndex)
{
this.lastNodeIndex = lastNodeIndex;
}
public Integer getSecondNodeIndex()
{
return lastNodeIndex;
}
}
import java.util.Vector;
/**
* Klasa tip koji opisuje cvor grafa.
* @author Dijana Kosmajac
*
*/
public class GraphNode
{
private Integer index = null;
private Object info = null;
private Vector<GraphEdge> edges = new Vector<GraphEdge>();
/**
* Inicijalizuje {@code GraphNode} objekat sa postavkama indeksa
* i vrijednosti cvora.
* @param index
* @param info
*/
public GraphNode(Integer index, Object info)
{
setIndex(index);
setInfo(info);
}
/**
* Inicijalizuje {@code GraphNode} objekat sa postavkama indeksa, vrijednosti
* cvora, tezine izlazece grane i krajnjeg cvora u koji grana ulazi.
* @param index indeks cvora
* @param info vrijednost cvora
* @param weight vrijednost grane (npr. tezina)
* @param lastNodeIndex indeks krajnjeg cvora
*/
public GraphNode(Integer index, Object info, Object weight, Integer lastNodeIndex)
{
this(index, info);
this.edges.addElement(new GraphEdge(index, weight, lastNodeIndex));
}
public void setInfo(Object info)
{
this.info = info;
}
public Object getInfo()
{
if (info instanceof String)
{
return ((String)info).toString();
}
return info;
}
public void setIndex(Integer index)
{
this.index = index;
}
public Integer getIndex()
{
return index;
}
public void addEdges(Vector<GraphEdge> edges)
{
for (int i = 0; i < edges.size(); i++)
{
this.edges.addElement(edges.elementAt(i));
}
}
public Vector<GraphEdge> getEdges()
{
return edges;
}
}
import java.util.Vector;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class X14Strategy
{
public int numberOfLines(String path) throws IOException
{
FileReader file= new FileReader(path);
BufferedReader reader= new BufferedReader(file);
int numberOfLines=0;
String line;
while((line=reader.readLine()) != null)
{
numberOfLines++;
}
reader.close();
return numberOfLines;
}
public Vector<String> fileToString(String path) throws IOException
{
FileReader file= new FileReader(path);
BufferedReader reader= new BufferedReader(file);
int i;
int number_of_lines=numberOfLines(path);
Vector<String> data_from_the_file = new Vector<String>();
for(i=0;i<number_of_lines;i++)
{
data_from_the_file.add(i, reader.readLine());
}
reader.close();
return data_from_the_file;
}
public Vector<GraphNode> readFile(String path)
{
int i;
Vector<GraphNode> graph = new Vector<GraphNode>();
Vector<String> fileData = new Vector<String>();
try {
fileData=fileToString(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String helper;
fileData.remove("graph");
fileData.remove("x14");
int index=0;
char info='A';
for(i=0;i<fileData.size();i++)
{
helper=fileData.get(i);
helper=helper.replace(">", "");
int j;
Vector<String> weights = new Vector<String>();
Vector<String> lastNodeIndexes= new Vector<String>();
for(j=0;j<helper.length();j++)
{
if( (helper.charAt(j)=='[') && (helper.charAt(j+2)=='-'))
{
weights.add(helper.substring(j+1, j+2));
}
else if(helper.charAt(j)=='[' && helper.charAt(j+3)=='-')
{
weights.add(helper.substring(j+1, j+3));
}
}
for (j=0;j<helper.length();j++)
{
if(helper.charAt(j)==']' && helper.charAt(j-2)==']')
{
lastNodeIndexes.add(helper.substring(j-1, j));
}
if( helper.charAt(j)==']' && helper.charAt(j-3)=='-')
{
lastNodeIndexes.add(helper.substring(j-2, j));
}
}
GraphNode node= new GraphNode(index+i, info+i, weights.get(0), Integer.parseInt(lastNodeIndexes.get(0)));
weights.remove(0);
lastNodeIndexes.remove(0);
int z;
if(weights.size()>0)
{
Vector<GraphEdge> edges= new Vector<GraphEdge>();
for(z=0;z<weights.size();z++)
{
GraphEdge edge= new GraphEdge(index+i, weights.get(z), Integer.parseInt(lastNodeIndexes.get(z)));
edges.add(edge);
}
node.addEdges(edges);
}
graph.add(node);
}
return graph;
}
}
This is the main class:
import java.util.Vector;
public class MainClass
{
public static void main(String[] args)
{
String path="C:\\graph_x14_kruskal-2.txt";
X14Strategy object= new X14Strategy();
Vector<GraphNode> vector = new Vector<GraphNode>();
vector=object.readFile(path);
System.out.println(vector);
}
}
Make a text file and put this into it:
graph
x14
0->A->[6->1]->[2->2]->[1->3]
1->B->[13->4]
2->C->[4->5]
3->D->[5->6]
4->E->[11->13]->[3->7]
5->F->[8->8]
6->G->[1->7]->[7->11]->[2->12]
7->H->[3->3]->[13->9]->[2->10]
8->I->[4->11]
9->J->[15->4]->[12->13]->[5->17]
10->K->[1->8]->[9->14]
11->L->[6->15]
12->M->[3->16]->[7->15]
13->N->[4->17]
14->O->[20->13]
15->P->[1->10]
16->Q->[7->15]
17->R
In the main class, be sure to set the path to this file.
When debugging, I put the breakpoint in this line:
"weights.add(helper.substring(j+1, j+2));"
which is in X14Strategy class. And everything works fine, the program reads first two values, then crashes, eventhough the conditions are exactly the same. Or I am missing something... But whatever it is, it is making my life hell. I just can't make this thing work.And as I said before, the point is to parse that input file in vector<GraphNode>.
I hope that you can help me make this work, I am really desperate now.
Don't have any time short-term to debug for you. Just post the error and the chances are we can make some sense of it.
Kopravich
19-01-2012, 08:20
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 0
at java.util.Vector.get(Unknown Source)
at X14Strategy.readFile(X14Strategy.java:106)
at MainClass.main(MainClass.java:13)
The error is reported at line 106, but debugger doesn't even reach that line. It breaks on the final iteration of the first j loop( the one getting all the weights) since it fails to get the last value.
Or that's what I think, at least...
Is that the entire stack trace? I'd be expecting a bit more... because the fact the debugger says (Unknown source) for the error isn't exactly a good thing.
Point is the error is thrown in java.util.Vector, so somewhere along the line you're doing something horribly wrong getting or setting something in the Vector. Which coincides with where the code breaks.
If it's not reaching your breakpoint, the breakpoint is obviously set wrong.
Like I said, I don't have the time to actually run this through a debugger for you. I'm stuck at work for another 7 hours, and I have other stuff I'd rather be doing when I'm not working.
Most amusingly is that the index '0' is out of bounds. So it looks like there's an uninitialized array somewhere that doesn't actually have a size...
Also,a bit more generally: Y u no catch exception? D:
Kopravich
19-01-2012, 08:47
Is that the entire stack trace? I'd be expecting a bit more... because the fact the debugger says (Unknown source) for the error isn't exactly a good thing.
I copied entire error message.
Point is the error is thrown in java.util.Vector, so somewhere along the line you're doing something horribly wrong getting or setting something in the Vector. Which coincides with where the code breaks.
Makes sense, but I can't figure out what is wrong. If you pay some attention to that weights statement, I need to get 6,2 and 1 into that string vector( check out the first node in the file ). values 6,2 are handled well and added to weights vector, but the program breaks before it gets the last value (1).
If it's not reaching your breakpoint, the breakpoint is obviously set wrong.
Like I said, I don't have the time to actually run this through a debugger for you. I'm stuck at work for another 7 hours, and I have other stuff I'd rather be doing when I'm not working.
It does reach my breakpoint since I set it on the statement I just described.
Also,a bit more generally: Y u no catch exception? D:
Only when java forces me to :D
Makes sense, but I can't figure out what is wrong. If you pay some attention to that weights statement, I need to get 6,2 and 1 into that string vector( check out the first node in the file ). values 6,2 are handled well and added to weights vector, but the program breaks before it gets the last value (1).
Wait, wait. Why are all these string vectors? That seems very memory inefficient and blatantly useless. The whole point was to use a data structure that has all your data readily accessible in a reasonable fashion. Not forming one string into another string, which you then access as an array just because you can.
Though probably unrelated to your error.
Only when java forces me to :D
You're doing it wrong then ~_~ don't make software that exits uncleanly. Bad practice, bad.
It's even bad practice in .net, and any non-OO language.
Kopravich
19-01-2012, 08:58
Wait, wait. Why are all these string vectors? That seems very memory inefficient and blatantly useless. The whole point was to use a data structure that has all your data readily accessible in a reasonable fashion. Not forming one string into another string, which you then access as an array just because you can.
Though probably unrelated to your error.
Well, arraylist is the only other thing which comes on my mind. I need it in an array form because the number of values in vector determines how many edges I have. And I use for loop to read all the values from the vector once they are stored... but this time, the last value fails to be stored and program breaks >_>
You're doing it wrong then ~_~ don't make software that exits uncleanly. Bad practice, bad.
It's even bad practice in .net, and any non-OO language.
Noone taught me how to properly use it o.o
I'll read about it a little.
Well, arraylist is the only other thing which comes on my mind. I need it in an array form because the number of values in vector determines how many edges I have. And I use for loop to read all the values from the vector once they are stored... but this time, the last value fails to be stored and program breaks >_>
Did they even teach you WHAT a vector is?
The vector STORES the edges. But why are you storing the edges as string data? We've discussed generics, as in I told you they exist, and I pointed out to you that the <> indicates a generic. So Y u abuse string?
You'd want something like a Vector<Array[2]> where the array stores the endpoint of the edge, and the weight. Yes this is only slightly different from doing it string based. But using strings here is simply ABUSING their ability to be referenced as an array and shows a distinct lack of insight into data typing.
An OO fanatic would even tell you to store edges into Edge objects so you can more easily define functions on them, and you can work with the edges directly. Causing you to possibly also store the edge starting point in them. But I won't quite go that far within the context of your current assignment.
Unless it turns out you actually need to do calculations on edge data that would be more suited to actually being IN the edge. It would create a certain layer where your actual data model is more extensible and less hard coded. But that's not your initial concern here.
Also mind stabbing whomever wrote those comments with a rusty knife? Writing comments in anything other than english is generally bad practice.
Kopravich
19-01-2012, 09:18
Well, I am storing weights in string vector because the constructor requires weights to be passed to it as strings.
Regarding lastNodeIndexes, they are strings just because it is easy to turn them to integer, which constructor requires.
But now when I look at the constructor, I see that it doesn't actually require weights to be strings >_>
An OO fanatic would even tell you to store edges into Edge objects so you can more easily define functions on them, and you can work with the edges directly. Causing you to possibly also store the edge starting point in them. But I won't quite go that far within the context of your current assignment.
Once I get all the required data, I am storing edges as edge objects. All of them are later stored into edge vector, which then is passed to addEdge method of GraphNode object.
And regarding comment, blame those who gave me the assingment. Those classess are theirs.
Well, I am storing weights in string vector because the constructor requires weights to be passed to it as strings.
Regarding lastNodeIndexes, they are strings just because it is easy to turn them to integer, which constructor requires.
But now when I look at the constructor, I see that it doesn't actually require weights to be strings >_>
Just store them as INTS for crying out loud. Just parse them into int immediately after extracting them from the line you read.
It's nonsensical, silly, and doesn't serve any higher purpose.
Kopravich
19-01-2012, 09:54
I just pinpointed a problem in this loop:
for (j=0;j<helper.length();j++)
{
if(helper.charAt(j)==']' && helper.charAt(j-2)=='-')
{
lastNodeIndexes.add(helper.substring(j-1, j));
}
if( helper.charAt(j)==']' && helper.charAt(j-3)=='-')
{
lastNodeIndexes.add(helper.substring(j-2, j));
}
}
This is where the code actually breakes, not in the loop I was mentioning before. There was a typo in the if condition which is now fixed. However, when debugging, I manage to read first two values,but it can't get the third value. I believe that the reason is in the fact that once loop hits the final iteration, it doesn't execute the statement because it closes itself before that. I need one more iteration for that to happen, but I can't provide it because string doesn't have one additional element. Now I wonder how to fix that.
EDIT:I think I did it...
Kopravich
19-01-2012, 19:52
So, generic vector can receive value of any other vector, without any data corruption?
A Vector<?> can contain references to ANY instanced type of vector generic, so you can have Vector<int> in there, but also Vector<string> without compiler warnings, yes.
It just means that it becomes a pain in the ass to determine what the values inside the vector actually are data type wise. Because the compiler has no way of knowing.
Kopravich
22-01-2012, 19:57
Okay, what is the best... and... standard way to document my project?
How frequently do I have to write comments?
Am I really obligated to write HTML tags and stuff?
Okay, what is the best... and... standard way to document my project?
How frequently do I have to write comments?
Am I really obligated to write HTML tags and stuff?
What you should use depends on a number of factors, in this particular case your teacher's requirement.
But the following his highly advisable:
- Use Javadoc
this means prefacing every
- Class
- Method
- Member variable
with a javadoc style comment, which look something like this
/**
* Generates a random number
*
* @param int seed random number generator seed
* @return int random number
*/
public int randomNumber(int seed) {
}
Most IDE's will also show these descriptions when hitting CTRL + Space, so it really helps when you can't remember the order of the arguments. You can also generate incredibly helpful documentation in HTML format for your project this way, which is especially useful when you're writing a library that can be re-used in later projects.
Other than that there's UML for models, but I would only use that for more complex projects.
There's no real need for you to insert HTML tags, unless you want fancier descriptions in your JavaDoc :/
Also, this style of commenting works with any language, but there's a <lang>Doc parser for a couple of languages, amongst which PHP and Java.
Other comments in functions and such, I generally only place comments for
- TODO snippets
- Suboptimal solutions that are done for a specific reason (so someone else doesn't go and WTF at it)
- Complex algorithms that aren't immediately obvious
There's no real standard, most organisations have their own standards, but the above is a basic and common sense approach.
Powered by vBulletin® Version 4.2.0 Copyright © 2013 vBulletin Solutions, Inc. All rights reserved.