Home Forums Programming Beginning C++

Viewing 195 reply threads
  • Author
    Posts
    • #6554
      Anonymous
      Inactive

      I want to start trying to teach myself C++ before i go to college in September… can anyone recommend perhaps a good book for doing so, or link me to a good site. I wouldnt consider myself a complete airhead when it comes to code, I enjoy working with javascript, PHP etc (mainly web based code) but this will be the first time I’m trying to dive into coding applications, so I’m a complete beginner. Also, does anyone know a good compiler?

      Thanks in advance
      Daniel

    • #40176
      Anonymous
      Inactive

      Good idea, start early and your programming class will be a breeze.

      I’m a fan of the CPlusPlus.com tutorial – it’s easy to follow, well laid out, and gives a good intro to the language. As for a good compiler, you can’t go wrong with Visual Studio Express which is free and contains everything you need.

    • #40181
      Anonymous
      Inactive

      In terms of books I found "C++ How To Program" by Deitel and Deitel to be great as a beginners book. It’s pricey enough as per usual in stores but you can pick it up for much cheaper on Play.com or Amazon.

    • #40182
      Aphra K
      Keymaster

      and just to let you know gizmo and a small crew have just been through C++ internship and bootcamp in Demonware – so they should know all about it.

      Aphra.

    • #40185
      Anonymous
      Inactive

      Most books by Dietel and Dietel are quite good.

    • #40196
      Anonymous
      Inactive

      Try Accelerated C++ by Andrew Koenig and Barbara E. Moo. Its very much a beginners book and doesn’t throw ghastly MFC at you which a lot of the beginners book do.

    • #40198
      Anonymous
      Inactive

      #Daniel

      http://www.amazon.com/gp/product/1598633600/ref=s9_flash_asin_image_1?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-7&pf_rd_r=0VT07TBXH54TVBNREXFZ&pf_rd_t=101&pf_rd_p=287704301&pf_rd_i=507846

      This is a pretty good text book, and will bring you up to speed quickly, with relevant projects and Q&A at the end of each chapter.

      Oh, and you make some games along the way.

      This is also a great beginner textbook:
      http://www.amazon.com/gp/product/1584504528/ref=s9_asin_image_3?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-3&pf_rd_r=0VT07TBXH54TVBNREXFZ&pf_rd_t=101&pf_rd_p=320448801&pf_rd_i=507846

      Compiler:
      Visual Studio 2008 Express Edition is free.
      Visual Studio 2005 Express Edition is free.

      http://www.microsoft.com/express/vc/

      There was some issues with Windows Programming using these versions, so you had to download the Windows Platform SDK, but that may have been sorted in the 2008 version.

      B.

    • #40190
      Anonymous
      Inactive

      Thanks for the help guys, appreciated :D

    • #40223
      Anonymous
      Inactive

      Deitel and Deitel is pricey but if you look on eBay you can buy the "Eastern Economy Edition" (I know!) that’s way cheaper.

      Good luck!

    • #40815
      Anonymous
      Inactive

      If you’ve had a look though the beginning C++ books I’d recommend The C++ Programming Language by the author of C++ himself, Bjarne Stroustrup.

      http://www.amazon.co.uk/C%2B%2B-Programming-Language-Third/dp/0201889544/ref=sr_1_2?ie=UTF8&s=books&qid=1209031785&sr=1-2

    • #40817
      Anonymous
      Inactive

      Try Accelerated C++ by Andrew Koenig and Barbara E. Moo. Its very much a beginners book and doesn’t throw ghastly MFC at you which a lot of the beginners book do.[/quote:48bc07542b]

      Really ? Throwing beginners straight into MFC ? That’s pretty harsh. Evil even.. :roll:

    • #40818
      Anonymous
      Inactive

      +1 for Accelerated C++

      I’m working through it between mental breakdowns

    • #42050
      Anonymous
      Inactive

      erm, i happened 2 stumble across this line: "you cannot assign multiple characters to a single character variable type. When more than 1 character is needed for storing a single variable, you must use a character array."

      I dont understand this very well, somebody help pls, a simple example will be great :)

    • #42051
      Anonymous
      Inactive

      http://www.cplusplus.com/doc/tutorial/arrays.html

      C++.com….array tutorial :)
      hope this helps.

    • #42052
      Anonymous
      Inactive

      The char type only holds a single letter, symbol or digit.

      You can define a char that holds letter "a" for example but not more than one character at a time. To form words etc. you need to put individual chars together in a sequence called an array of chars like the following ["h","e","l","l","0",""].

      Last array entry is special and called the nul character indicating that the sequence of chars is ended.

      You can define such arrays of chars in C++ simply as follows
      char greeting[] = "hello";

      Java has a string type which is similar in effect to the above line.

      You will find something like what I said in any book or on the web about programming.

      Edit: Ah omen beat me

    • #42053
      Anonymous
      Inactive

      erm, i happened 2 stumble across this line: "you cannot assign multiple characters to a single character variable type. When more than 1 character is needed for storing a single variable, you must use a character array."

      I dont understand this very well, somebody help pls, a simple example will be great :)[/quote:be45c5032b]

      It means you can’t do this.

      char a = "abababababa"; //this is a single character type assigned multiple characters. (incorrect)

      who must do one of the following:

      1: char* a = "abababababa"; //multiple characters assigned to a character pointer. (correct)

      2: char a [11]; //allocate the character array

      strncpy(a,"abababababa",11); // copy the 11 character string to this array. (correct)

      3: char a[11] = "abababababa"; // assigning multiple characters to a character array (correct).

      Note: a variable like a below can only be assigned like below:

      char a = ‘a’; //single character type assigned to a single character (note instead of " ).

      Hope that helps.

    • #42054
      Anonymous
      Inactive

      Basically it means you can only store one value per variable.
      If you want to store a bunch of chars next to each other in memory (like you do if you want to store a string) you need to make an array.
      this should help with both arrays and strings

      edit: man, talk about being beaten to the punch :D

    • #42055
      Anonymous
      Inactive

      Gees were all super helpful today. Nice to get easy ones. :)

    • #42056
      Anonymous
      Inactive

      Gees were all super helpful today. Nice to get easy ones. :)[/quote:4fee426485]

      Anyone able to help write a shader for screen space ambient occlusion ;) then explain it..lol..

    • #42057
      Anonymous
      Inactive

      You could render a depth texture per poly :D
      Is ssao possible without deferred shading, or at least rendering the z buffer?

    • #42058
      Anonymous
      Inactive

      Holy sweet jesus, TO EVERYONE THAT HELPED ME, u guys(pretty sure most of yee are guys) rock!!, thanks, i really appreciate it. guess i’ll post up more questions in the future if i get stuck again… too bad i dont have cookies wit me or i’m gonna hand out loads :D

    • #42059
      Anonymous
      Inactive

      You could render a depth texture per poly :D
      Is ssao possible without deferred shading, or at least rendering the z buffer?[/quote:6bcf31be43]

      AFAIA deferred shading is the only way. Sure its a grand way so it is ;)

    • #42064
      Anonymous
      Inactive

      Don’t nVidia give you the basics on how to do it?
      I know someone who could write and explain it if that helps :)

    • #42065
      Anonymous
      Inactive

      There’s no reason you need deferred shading for SSAO, all you need is a depth texture laid down in a z prepass.

    • #42066
      Anonymous
      Inactive

      Don’t nVidia give you the basics on how to do it?
      I know someone who could write and explain it if that helps :)[/quote:3c85545844]

      I’m kidding.. I’ve written a few variations myself in the past. Ya nvidia\ati etc all have versions

    • #42074
      Anonymous
      Inactive

      yea thanks for all the helps last time but this time i only have a lil questions.

      first code :
      int main()
      {
      int x = 35;
      float y = 3.64;
      char z = ‘R’;

      printf("\nThe values of x,y and z are : %d, %.2f, %c respectively\n",x,y,z);
      return 0;
      }

      second code :
      int main()
      {
      const int x = 35;
      const float y = 3.64;
      const char z = ‘R’;

      printf("\nThe values of x,y and z are : %d, %.2f, %c respectively\n",x,y,z);
      return 0;
      }

      ok i found out that both this prints out the same result. but the book says the second code is only read-only variable or constant(because of the CONST). does tat mean the displayed output cant be changed??? my heads a bit messed up here(since they both display EXACTLY same results) :( help??

    • #42076
      Anonymous
      Inactive

      ok i found out that both this prints out the same result. but the book says the second code is only read-only variable or constant(because of the CONST). does tat mean the displayed output cant be changed??? my heads a bit messed up here(since they both display EXACTLY same results) :( help??[/quote:e8b800b1b9]

      No what it means is once you assign to that variable you cannot re-assign to that variable.

      i.e.

      const int a =10; (okay)

      a=5; (compiler error on the reassign because variable is const)

    • #42077
      Anonymous
      Inactive

      @ peter_b

      const int a =10; (okay)

      a=5; (compiler error on the reassign because variable is const)

      so lets say-

      int main()
      {
      int a = 10;

      a = 5;(wont this be a compiler error s well??)

      printf("value of a = %d",a);

      }

      wat exactly is the const use for??

    • #42078
      Anonymous
      Inactive

      no that wont be a compiler error, your just re-assigning a variable.

      const is a guarantee that this variable will not change if declared with const(eventhough you cannot change it even if you want to (well you can using a cast but ignore for now)). Typically you might use it for magic numbers.

      const int SCREEN_WIDTH = 640;
      const int SCREEN_HEIGHT = 480;

      You declare like this, as the screens width and height will not change during runtime.

      There are about 5 places const are used, all except this case are alot more involved for a beginner, so ignore for now. If you do want to know them all (its a standard interview question ;)) check out the site omen post earlier in this thread.

    • #42122
      Anonymous
      Inactive

      sorry man last week had been real busy. i got the const figured out, cheers peter_b :)

    • #42215
      Anonymous
      Inactive

      ok in the chapter’s last page there’s a little challenge for me which it asked me to prompt the user’s name using the scanf() function and return a greeting to the user using the name provided…this is all i came up with:

      #include<stdio.h>

      int main()
      {

      char name;

      printf("\nPlease enter your name: \n ",name);
      scanf("%c%c%c%c%c",&name);
      printf("\nGreetings %c%c%c%c%c%c\n",name);

      return 0;

      }
      problem: dunno how to store the user’s name using the scanf() function and i suppose i dont have to assign something to char name…right???please i’m stuck, i’m doing this with a book and a laptop and only myself, tats all :(

    • #42219
      Anonymous
      Inactive

      #include<stdio.h>

      int main()
      {

      char name[30]; //I think it would be easier for you to make a char array to hold say 30 characters. That should be enough for most names.

      printf("Please enter your name: \n ",name); //This is fine
      scanf("%s",name); //This puts what the user types into the name array
      printf("\nGreetings %s\n",name); //Print it back use %s rather than loads of single chars like you have "%c"

      //As the above line shows what the user typed is stored in the name array.

      return 0; //All done

      }

    • #42220
      Anonymous
      Inactive

      thanks alot david i only came across array like 2 days ago but the book says it will go into more details in like chapter 8 or 9, so i never really know wat it is but thanks anyway :)

    • #42232
      Anonymous
      Inactive

      erm i went over ur answer david and i found out that u dont use "&" for the scanf() function and it works fine?????????? 0.0 am i missing something here??

    • #42233
      Anonymous
      Inactive

      yea its me again…anyway its only a lil question, the code below runs perfectly fine…until i change every %f in the scanf() function to %.2f…anyone knows exactly why??

      #include<stdio.h>

      int main()
      {
      float a, b, x, y;

      printf("\nPlease enter the value of a:\n");
      scanf("%.2f",&a);

      printf("\nPlease enter the value of b:\n");
      scanf("%.2f",&b);

      printf("\nPlease enter the value of x:\n");
      scanf("%.2f",&x);

      printf("\nPlease enter the value of y:\n");
      scanf("%.2f",&y);

      printf("\nThe result of the formula f = (a – b)(x – y) = %.2f\n",(a – b)*(x – y));

      return 0;

      }

    • #42234
      Anonymous
      Inactive

      You can do:

      scanf("%s",&name);
      printf("\nGreetings %s\n",&name);

      and for clarity maybe I should have, but arrays are sort of special, just using the array name gives a reference to the memory location of the first entry so its the same as using &arrayname or even &(arrayname[0]).

      Arrays and pointers are very important in programming so I suggest you read thoroughly and if your book is not making these things clear try another one. Their are threads here about good books.

    • #42235
      Anonymous
      Inactive

      Can you tell me what you think scanf("%.2f",&a); will do?

      Try this as should help you understand rather than me giving you the answer.

      [code:1:0af959f547]
      #include<stdio.h>

      int main()
      {
      float a, b;
      printf("\nPlease enter a long number for a and put a decimal place in for fun:\n"); //try say 1.3456789 then rerun and try1.3456
      scanf("%8f",&a); //8 characters total //Easier just to use %f and not restrict user in most cases
      printf("\nLets see whats in a: %f\n",a);
      printf("\nHow to show only three numbers past the decimal place: %.3f\n",a);
      printf("\nGive me a number for b\n");
      scanf("%f",&b);
      printf("\nThis is what is in b:%f",b);
      return 0;
      }
      [/code:1:0af959f547]

    • #42236
      Anonymous
      Inactive

      Instead of using printf and scanf you should try using cin and cout. They’re easier for beginners. So for this you could do this:

      [code:1:36d612eadf]
      #include <iostream> // Use for cin, cout, endl
      using namespace std; // Namespace directive

      int main()
      {
      float a, b;

      cout << endl << "Please enter a long number for a and put a decimal place in for fun:" << endl; //try say 1.3456789 then rerun and try1.3456
      cin >> a;

      cout << endl << "Lets see whats in a: " << a;

      //cout << endl << "How to show only three numbers past the decimal place:" << a; // Can’t remember the call for this.
      cout << endl << "Give me a number for b: ";
      cin >> b;

      printf("\nHow to show only three numbers past the decimal place: %.3f\n",a);

      cout << "What is what is in b: " << b;

      return 0;
      }
      [/code:1:36d612eadf]

    • #42238
      Anonymous
      Inactive

      Thanks david for bearing with me, ok back to the topic

      i think [scanf("%.2f",&a);] will just restrict the user’s input number to 2 places after the decimal,then the number will be stored in "a", for example if the user type in 5.678 i expect the computer to store just 5.67(tats wat i THINK & WANT BUT it seems like i’m TELLING it to do other things)…

      OK i tried out ur code n erm…it works fine when i put in 1.3456 but when i put in more than 6 digits after the decimal, the digits after the sixth digit mysteriously appears as the value for b??? i seriously dont get in since the value was assigned to "a" but the digits after the sixth digit automatically turn themselves to the value of "b" :shock:

      sorry i hope i dont confuse you man :roll:

    • #42240
      Anonymous
      Inactive

      Yep sounds logical but scanf won’t recognise %.2f like that as its not that smart. Also console won’t stop the user from typing more than two decimal places but think you got that. Best thing to do is read in all of what the user types and then work on the float to knock off the decimal places you don’t want.

      To do what you want directly sounds easy but actually requires a fair bit of code. As I showed in my code you can use %#f but then as you saw when you type more than # the overflow skips to the next scanf. There are methods of clearing the overflow but are not standard C++ as far as I know.

    • #42241
      Anonymous
      Inactive

      alright now i see i’m going abit ahead of myself :oops:

      i will no doubt put up more questions in the future n i really hope u can b ther 4 me man…
      anyway thanks a million david, btw it would b a waste if ur not a lecturer :D

    • #42242
      Anonymous
      Inactive

      @ thane- whoa wait a sec the VEEERY 1st thing i learned from the book was the printf function, the books called c programming second edition for the absolute beginner(n a little line says no experience required)…but ur code looks a bit html-ish when ur using << and >>…n i never heard of cin, cout,endl, n yes i’m a newbie, buti’ll still try out the code s it wont hurt anyway :D…thanks for the help n the friendly advice, take care

    • #42243
      Anonymous
      Inactive

      http://www.cplusplus.com/doc/tutorial/basic_io.html !

      basically cout is your screen (console out) and cin is your keyboard (console in!)

      also what in the hell were they thinking with << and >> :D

    • #42244
      Anonymous
      Inactive

      One small little addition I’d add to all the excellent recommendations above;

      http://www.amazon.co.uk/Mathematical-Ideas-Really-Need-Know/dp/1847240089

      Coupled with

      http://www.amazon.co.uk/Physics-Ideas-Really-Need-Know/dp/1847240070/ref=pd_sim_b_2/203-2361905-1237560

      This will give you some problems to solve while you cut your teeth at C++

    • #42245
      Anonymous
      Inactive

      @ thane- whoa wait a sec the VEEERY 1st thing i learned from the book was the printf function, the books called c programming second edition for the absolute beginner(n a little line says no experience required)…but ur code looks a bit html-ish when ur using << and >>…n i never heard of cin, cout,endl, n yes i’m a newbie, buti’ll still try out the code s it wont hurt anyway :D…thanks for the help n the friendly advice, take care[/quote:009e4e7743]
      Yeah, that’s corrent printf and scanf are part of c programming. Cout and Cin are the c++ versions of it.
      I advised them to use it because I’ve used both, and I think cin and cout are easier for beginners. Also he wanted c++ advise not c.

    • #42431
      Anonymous
      Inactive

      Hello its me jin again, just came back from holidays and college starts straight away, so i think it might be the the best for me to continue my programming lessons :)

      Problem: Allow a customer to deposit or withdraw money from a bank account, if the user wanna withdraw money, make sure thers enough fund exist in his/her account.

      code:
      if action == deposit
      Deposit funds into account
      else
      if balance < withdraw amount
      Insufficient funds for transaction
      else
      withdraw money
      end if
      end if

      Questions: So which one is the nested condition and which one is the parent condition? is it the "if action == deposit" the parent condition while the "if balance < withdraw amount" the nested condition?? I just need to make sure :)

    • #42433
      Anonymous
      Inactive

      if action == deposit is the parent
      if balance < withdraw amount is the child.

      An easy way to tell when writing it out is to ident. Won’t work on forums but if you’re using word or something for pseudocode just hit Tab when you’re "inside" something like an If statement.

      *Let’s see if this works*

      if action == deposit
      —–Deposit funds into account
      else
      —–if balance < withdraw amount
      ———-Insufficient funds for transaction
      —–else
      ———-withdraw money
      —–end if
      end if

      Using – instead of whitespace you can see that the second If statement is between the If and End If of action==deposit so it’s the child.

    • #42444
      Anonymous
      Inactive

      thanks skyness i’ll pay attention to that in the future :)

      anyway i got a very small problem here:

      # include<stdio.h>

      int main()
      {
      ———— int decision;
      ———— int amount_to_deposit;
      ———— int amount_to_withdraw;

      —-printf("\n\t\tATM\n");
      ———— printf("1\tDeposit Funds\n");
      ———— printf("2\tWithdraw Funds\n");

      ———— printf("Please enter your selection :\n");
      ———— scanf("%d",&decision);

      ———— if(decision == 1){
      ————————–printf("Please enter the amount of funds to deposit:\n");
      ————————–scanf("%d",&amount_to_deposit);
      ————————–printf("An amount of %d has been deposit, thank you and have a nice day\n!",amount_to_deposit);
      ———–}

      if (decision == 2){
      ————————–printf("Please enter the amount of cash that you would like to withdraw:\n");
      ————————–scanf("%d",amount_to_withdraw);
      ————————–printf("You have withdrawn %d from your account:\n",amount_to_withdraw);
      }

      return 0;
      }

      The program runs smooth when 1 is theinput but when 2 is insert instead of 1, a run time error occurs saying amount_to_withdraw is being used without redefine :shock:…help??

    • #42447
      Anonymous
      Inactive

      Your just missing "&" in your scanf

      scanf("%d",amount_to_withdraw);
      should be scanf("%d",&amount_to_withdraw);

    • #42451
      Anonymous
      Inactive

      @david- well spot!! haha silly me

    • #42460
      Anonymous
      Inactive

      Just a small questions – Do i need to include the ‘ ‘ sign when i’m using the char type??

      like: char Response = ‘0’;
      or
      char Response = 0;

      i wrote a program code n it runs fine with or without them…

      just wonder if its alright if i use ‘ ‘ all the time??

    • #42461
      Anonymous
      Inactive

      You should always put quotes around the characters.

    • #42467
      Anonymous
      Inactive

      Just a small questions – Do i need to include the ‘ ‘ sign when i’m using the char type??[/quote:a31fa9da40]

      If you want to store a single character as you have typed it into the source code, yes. Otherwise, if you want to store a number in the char- no.

      Single quotes tell the compiler to take the character you put into the quotes and convert it into it’s numerical/binary form. For instance capital ‘A’ is converted into the number 65. See the ascii table for a list of these conversions: http://www.cs.mun.ca/~michael/c/ascii-table.html

      At the end of the day a char is just a number like everything else in the computer, and whether you interpret it as a character or as a number is up to you.

      For instance, these assignments both do the exact same thing- but one is more appropriate than the other depending on if you are treating the char as an actual character or just using it to hold a number:

      char a;

      a = 65; // ASCII character ‘A’
      a = ‘A’; // Numerical value 65

      Also note that these two assignments are not the same:

      char a;

      a = 0; // Null terminating (end marking) character for strings
      a = ‘0’; // Numerical value 48

      Hope this helps.

    • #42510
      Anonymous
      Inactive

      hi all, yea its me jin again…

      anyway, i got a small problem with the function rand(), here’s the code:

      // A number guessing game
      //Cheng Yet Choo
      //07-10-2008

      #include<stdio.h>
      #include<ctype.h>

      int main()
      {
      ———— int decision = 0;
      ———— int RandomNumber = 0;

      ———— RandomNumber = rand() % 99;

      ———— printf("\n\t\tWelcome to the best guessing game of all time!!\n");
      ———— printf("\nPlease guess a number ranging from 1 -99(no decimals please)\n");
      ———— scanf("%d",&decision);

      ———— if (decision == RandomNumber){
      ———— ———— printf("Congratulations!! The number you have guessed was…correct!!\n");

      ———— else{
      ———— ———— printf("The number that you have entered was wrong");
      ———— ———— printf("The correct number was %d",RandomNumber);
      ———— }
      }

      problem: rand-identifier not found :( help ??

    • #42511
      Anonymous
      Inactive

      You need to include the standard library header to use rand(), hence its not being found.
      Chuck this at the top and you should get past that error
      #include <stdlib.h>

    • #42515
      Anonymous
      Inactive

      What will be more fun is when you find out why the game can be won every time after the first run.

      Look into what srand does.

      #include <ctime>
      srand(time(0));

      Check your brackets again too.

    • #42518
      Anonymous
      Inactive

      thanks parrot and david. the book also said the rand() will generate same sequence of number each time so…anyway thanks again forpointing me in the right direction :)

    • #42540
      Anonymous
      Inactive

      #include<stdio.h>
      #include<ctype.h>
      #include<stdlib.h>
      #include<ctime>

      int main()
      {
      ———— char decision = ”;
      ———— int RandomNumber = 0;
      ———— srand(time(0));

      ———— RandomNumber = (rand() % 99) + 1;

      ———— printf("\n\t\tWelcome to the best guessing game of all time!!\n");
      ———— printf("\nPlease guess a number ranging from 1 -99(no decimals please)\n");
      ———— scanf("%c",&decision);

      ———— if (decision == RandomNumber){
      ———— ———— printf("Congratulations!! The number you have guessed was…correct!!\n");
      ———— }

      ———— if(isdigit(decision)== 0){
      ———— ———— printf("Sorry you did not enter a digit, please rerun the program and enter a digit again\n");
      ———— }
      ———— else{
      ———— ———— printf("The number that you have entered was wrong\n");
      ———— ———— printf("The correct number was %d\n",RandomNumber);
      ———— }
      }

      This code runs fine and it does generates different numbers each time.
      However, is there a way to prompt the user to enter another digit without him/her restarting the whole program if the user entered a non-digit for the 1st time, and the program can keep asking the user to enter a proper digit if he/she kept entering a non-digit??? loop maybe?

    • #42542
      Anonymous
      Inactive

      Use a while loop. In pseudocode…

      CreateRandomNumber
      While ( number not found or number of allowed guesses reached)
      — print text asking for input
      — read in input
      — evaluate input
      — print right / wrong text on screen
      — if right, break from loop, else loop

    • #42546
      Anonymous
      Inactive

      Challenge: create a fortune cookie program that prompts the user to enter their chinese zodiac. More specifically, the user may need to input her month,year and day of birth depending on the zodiac’s technique used. Create a fortune after obtaining these infos.

      #include<stdlib.h>
      #include<stdio.h>
      #include<ctype.h>

      int main()
      {
      ———— int selection = 0;
      ———— printf("\n\t\tPlease select your Chinese Zodiac\
      ———— printf("\t1\tRat\t\t2\tCow\n");
      ———— printf("\t3\tTiger\t\t4\tRabbit\n");
      ———— printf("Please enter a digit ranging from 1 to 4 ONLY:");
      ———— scanf("%d",&selection);
      —–switch(selection){
      ————————–case 1:
      —————————printf("\nYou should be more careful with your health, avoid spicy foods and hot drinks\nand you shall have a happy year\n");
      ————————–break;
      ————————–case 2:
      —————————printf("\nYou should be more careful with your finance, conservative is a virtue my friend\n");
      ————————-break;
      ————————-case 3:
      ————————–printf("\nThe ferociousness of a tiger can sometimes get you in trouble, try to do some yoga\n");
      ————————-break;
      ————————-case 4:
      ————————–printf("\Sometimes it also takes a hell lot of courage to step up and admit your mistake, dont let your pride blinds you\n");
      ————————-break;
      ————————-default:
      ————————–printf("Sorry your unmber is either outta range or you dint enter a digit\n");
      ————————-}
      }

      problem: ok any suggestions on how do i use birthdays as well?? i’m stuck again :(

      btw the chinese zodiac has 12 i only put up 4 here for space reason.

    • #42560
      Anonymous
      Inactive

      I would use an emum for clarity of code.
      Year of birth would be sufficient as calendar is a 12 year cycle but you should look into checking full dob’s with days in each month and account for leap years as a worthwhile exercise.

      Answer done below so don’t look if you want to figure it out yourself.

      [code:1:d9d5e66439]
      #include<stdlib.h>
      #include<stdio.h>
      #include<ctype.h>

      int main()
      {
      enum Zodiac { Rat=1, Cow, Tiger, Rabbit, Dragon, Snake, Horse, Sheep, Monkey, Rooster, Dog, Pig};

      enum Zodiac mySymbol;

      printf("Please select your Chinese Zodiac\n");
      printf("1:\tRat\n2:\tCow\n3:\tTiger\n4:\tRabbit\n5:\tDragon\n6:\tSnake\n");
      printf("7:\tHorse\n8:\tSheep\n9:\tMonkey\n10:\tRooster\n11:\tDog\n12:\tPig\n");
      printf("Please enter a digit ranging from 1 to 12 ONLY or year of birth YYYY:");
      scanf("%d",&mySymbol);

      if ((int)mySymbol>1864) //Then must be a year
      {
      //1864 was a year of the rat so will make modulo opp quicker to subtract first.. as only zombies that old
      mySymbol=(Zodiac)((((int)mySymbol-1864)%12)+1);
      //12 year cycle so modulo 12 but rat=1 not 0 so add 1
      }
      //printf("%d",mySymbol);
      switch(mySymbol)
      {
      case Rat:
      printf("\nRat:blah\n");
      break;
      case Cow:
      printf("\nCow:blah blah\n");
      break;
      case Tiger:
      printf("\nTiger:\n");
      break;
      case Rabbit:
      printf("\nRabbit:\n");
      break;
      case Dragon:
      printf("\nDragon:\n");
      break;
      case Snake:
      printf("\Snake:\n");
      break;
      case Horse:
      printf("\nHorse:\n");
      break;
      case Sheep:
      printf("\nSheep:\n");
      break;
      case Monkey:
      printf("\nMonkey:\n");
      break;
      case Rooster:
      printf("\nRooster:\n");
      break;
      case Pig:
      printf("\nPig:\n");
      break;
      case Dog:
      printf("\nDog:\n");
      break;
      default:
      printf("\nSorry your number is either outta range or you dint enter a digit\n");
      }
      system("pause");
      }
      [/code:1:d9d5e66439]

    • #42583
      Anonymous
      Inactive

      @david-ok I tried to figure it out myself but i really cant get it so i just look at the answers :oops:

      anyway i got storm of questions for you if you dont mind…

      1: You 1st define zodiac using enumeration type i.e the term "zodiac" is made up of rat,cow,tiger…pig. but i dont quite get this line:
      [enum zodiac MySymbol]- you just assign another variable to zodiac??dont really get it,can you pls explain??

      2:if((int)MySymbol>1864)-can i leave the(int) part out ALL THE TIME?? so i’ll get this line instead:if(MySymbol>1864)

      3:MySymbol = (zodiac)((((int)MySymbol – 1864)%12)+1);

      what does this line really do? (zodiac)((((int)MySymbol…….+1);

      let’s say i enter 1988 into the code(which will store in MySymbol) and take the first year(rat’s year) away from 1988 and divided by 12 then add 1…i’ll get 11 something but how will the computer knows its case 5???

      sorry 4 all these questions but anyway thanks cos ur really helping, glad someone’s here to guide me :D

    • #42585
      Anonymous
      Inactive

      okey doke,

      1) Having declared the enum I am saying that MySymbol is an instance of that that enum type. So it’s like saying the value of MySymbol will be one of the values of the enum so for e.g I could write
      enum Zodiac MySymbol=Rat; //to initialise it

      enum Zodiac type declaration is same idea as saying x is of type int by
      int x;

      2) The int in round brackets is a cast operation. It means that whatever type is on the right of it will be converted to an integer value if the compiler knows how (it will let you know if it can’t). The compiler knows how to change an Emum instance to an integer when prefixed with (int) as they are standard types and actually very similar. Do you need it, here with C++ yes but some languages consider enums directly as ints so for them no but probably worth doing for clarity.

      Heres another example converting an int to a float
      int x=5;
      float y;
      y=(float)x; //casting x to a float.
      Now to be clear x is still an int after above line as x does not change to a float, compiler actually creates a temporary value of type float that is equal in value to x.

      There is also static_cast which you should look up.

      3) Ok % is not division its modulus (sometimes referred to as modulo) but is related to division though. It means divide the number on the left by the one on the right but returns the remainder. 10%2=0 divides evenly so no remainer but 10%3=1.

      I was using an (int) cast to do the maths and then casting it back at the end to type zodiac using (zodiac).

    • #42608
      Anonymous
      Inactive

      YES!! I have found a way to figure out how to keep my bank account menu to show up as long as the user dont choose to quit 8) hehe,any advice would be appreciated:

      #include<stdio.h>
      #include<stdlib.h>
      #include<ctype.h>

      int main()
      {
      —— int Selection = 0;
      —— int Balance = 5000;
      —— int Amount_To_Deposit = 0;
      —— int Amount_To_Withdraw = 0;

      —— while(Selection != 3){

      —— printf("\n\t\tWelcome To Super ATM V.12\n");
      —— printf("\n1\tDeposit Fund\n");
      —— printf("\n2\tWithdraw Fund\n");
      —— printf("\n3\tQuit\n");
      —— printf("\nPlease enter a digit ranging from 1-3 ONLY: ");
      —— scanf("%d",&Selection);

      —— if(Selection == 1){
      —— —– printf("Please enter the amount to deposit:");
      —— —— scanf("%d",&Amount_To_Deposit);
      —— —— printf("You have deposit %d, your new balance is: %d\n",Amount_To_Deposit, Balance + Amount_To_Deposit);
      —— }
      —— if (Selection == 2){
      —— —— printf("\nPlease enter the amount to withdraw:");
      —— —— scanf("%d",&Amount_To_Withdraw);
      —— —— if(Amount_To_Withdraw > Balance){
      —— —— —— printf("Sorry You do not have enough fund in you account");
      —— —— }
      —— —— printf("You have withdrawn %d from your account\n",Balance – Amount_To_Withdraw);
      —— }
      —— }
      —— if(Selection == 3)
      —— —— printf("\nThank you for using Super ATM\n");
      }

      back to figure out how to use date of birth
      please dont consider this as a show off or waste of space now…
      last thing, thanks omen and david

    • #42610
      Anonymous
      Inactive

      Good work. I would make only minor changes.

      if (Selection == 2)

      to "else if (Selection == 2)"

      that way if Selection == 1 is true there is no need to test if Selection == 2 which it could not be.

      also you don’t need "if(Selection == 3)" at the end as you know that it is as you have exited the loop based on that condition.

      Using 3 as the value to end input is fine I guess but it is often suggested to use the EOF character to end input like this:

      while(Selection != EOF)

      EOF stands for "end of file" and is entered by typing control and z keys and then return. (Ctrl-z windows, Ctrl-D on unix).

    • #42611
      Anonymous
      Inactive

      thanks david :)

      anyway i got my other questions as usual:

      Task: Create a six-sided dice game that uses 2 six sided dice. Each time the program runs, use random numbers to assign value to each die variable. Output a "Player wins" msg to the user if the sum of the 2 dice is 7 or 11. Otherwise output the sum of the 2 dice and thanks the user for playing.

      code:
      #include<stdio.h>
      #include<stdlib.h>
      #include<ctype.h>
      #include<ctime>

      int main()
      {
      —— int Dice_1;
      —— int Dice_2;
      —— int Decision;
      —— int Result;
      —— srand(time(0));

      —— Dice_1 = (rand()%6)+1;
      —— Dice_2 = (rand()%6)+1;
      —— Result = Dice_1 + Dice_2;

      —— printf("Welcome to a simple Dice game!!\n");
      —— printf("If you are able to get the number 7 or 11, You win!!\n");
      —— printf("If you dont…Well that’s too bad, better luck next time then\nSo let’s get started!!\n");

      —— if(Result == 7){
      —— —— printf("Congratulations!!You Won!!\n");

      —— }

      —— if(Result == 11){
      —— —— printf("Wow you won!!\n");
      —— }

      —— else
      —— —— printf("Sorry you lose, the correct number is %d\nThanks for playing\n",Result);

      }

      This code works only like 70% of the time. sometimes the output says: You have won, sorry you lost the number was 7…
      any tips?? cos the code looks pretty fine to me :shock:

    • #42612
      Anonymous
      Inactive

      I bet it never says:
      "Wow you won!!
      "Sorry you lose, the correct number ….

      The error in the code is your if statements are not connected.

      if(Result == 7) is tested

      then you are separately testing if(Result == 11) and if its not then output "Sorry you loose"

      Do you see the logic error there? If result is 7 the first test passes and the second test will be false meaning the else code is run.

      Fix it with an else if
      "else if(Result == 11){ "
      or combine tests with an OR statement:
      if ((Result == 7)||(Result == 11)){

    • #42616
      Anonymous
      Inactive

      Something you might want to think about doing ( something I never did when I was learning ) is to think about using coding standards too. Get used to it now and its less of a burden when you get a job and you have to start using them. Most common form of coding standards is Hungarian. Basically you’re naming your variables in relationg to the Type they are, so for instance in your previous program, you would declare your int Result variable as int iResult instead. The ‘i’ at the start indicates its an int for future reference for yourself or anyone else reading your code. A float variable would be prefixed with ‘f’, bools with ‘b’, and so on.
      Just do a search for Hungarian Notation for more info.

    • #42619
      Anonymous
      Inactive

      @ david-

      so let’s say the result is 7 and the computer will see it like this:

      "Oh its number 7, so i’ll just print out ("congratulations you won")"

      then it move on to the next condition and see:

      "oh its not number 11, i’ll just ignore the line("Wow you won")"–so does the computer just ignore the first if statement completely after evaluated it?

      after that the computer just see the else statement and compare it to the second if statement[the if(result == 11)] and see: oh since the result is not 11 i’ll just print out ("Sorry you lose, the correct number is 7",Result)–again, ignoring the very 1st if statement and it ends up contradicting itself…hope i’m right

      btw the compiler actually does say: "wow you won" and "sorry you lose the correct number is…", but not all the time, only happens when the result is 7…thanks for the help anyway :)

    • #42620
      Anonymous
      Inactive

      @ omen-

      yea in the book i used, the author also used the same coding tat u just showed me, i never thought of it being very useful, but thanks for the advice, i’ll definitely start getting used to it TODAY, ok go back to practise my skills now :D

    • #42621
      Anonymous
      Inactive

      hey david-

      just a small question
      how u know bout the chinese zodiac?? u used wikipedia?? anyway just wonder

    • #42622
      Anonymous
      Inactive

      "so does the computer just ignore the first if statement completely after evaluated it? "
      Yes your program runs sequentially so after the first if statement is evaluated it does not go back to check or rely upon the result.

      The key thing to get though is that currently your else condition is linked only to "if(Result == 11)" so if the result does not equal 11 the "Sorry you lose, …" statement will be printed regardless of any tests already performed. i.e. your testing if(Result == 7) in isolation.

      I think you got it but perhaps examples will hammer it home.
      [code:1:12b18781b1]
      The problem:
      If the number were 7
      if(Result == 7) gets tested and is true is prints: Congratulations!!You Won!!

      Then program moves on to test if(Result == 11) which is false so the else is run: "Sorry you lose, the correct number is 7.
      ————————
      If the number were 11
      if(Result == 7) gets tested and is false so no print.

      Then program moves on to test if(Result == 11) which is true so prints Wow you won!! and else is not run as test was not false.
      ————————
      If the number were 8 or any number that is not 7 or 11
      if(Result == 7) gets tested and is false so no print.

      Then program moves on to test if(Result == 11) which is false so the else is run: "Sorry you lose, the correct number is…
      [/code:1:12b18781b1]

      I know it might say "Congratulations!!You Won!!" followed by "Sorry you lose, the correct number is 7" as shown above
      but can never say "Wow you won!!" followed by "Sorry you lose, the correct number is 7".

      "How u know bout the chinese zodiac?" Yep good old internet.

    • #42630
      Anonymous
      Inactive

      yea i tend to assume the program to do certain things sometimes, but looks like i gotta get rid of that habit of assuming…

      sorry my bad yea i wan meant to say it can print"Congratulations!!You Won!!" followed by "Sorry you lose, the correct number is 7" if the result is 7
      and also print "wow you won" but cant have "sorry you lose…" afterwards since the else statement would be ignored if the result is 11

      guess i’ll call it a day for now

      cya soon david, VERY soon :lol:

    • #42633
      Anonymous
      Inactive

      Once your code gets a bit larger, its can get harder to remember what exactly a variable actually is (no matter how good the naming). Adding the type into the name can help your debugging. It will also help other people who are reading your code as they won’t know what your variables actually are. And also, when you start in the workplace, the company will more than likely have a coding standard that you’ll need to adher to. :)

    • #42637
      Anonymous
      Inactive

      @ omen- wow i never know that, thanks for the infos, really hope i’ll get a chance to work in some great company like capcom, insomniac etc :)

      anyway i have a question for you experts, very short:
      int main()
      {
      int ix = 0;
      int iy = 1;

      ix = iy++ * 2;
      printf("\nThe value of x is %d\n",ix);

      }

      Does the computer sees this line like:"ix = iy++ * 2, so i’ll take the value of iy(which is 1) and multiply it by 2 and make it the value of ix."

      then, it sees this line like:"printf("\nThe value of x is %d\n",ix);- ok i’ll just print out the value of %d as the value of ix(which is 2 by now)…

      after the printf() function it increases the value of iy by 1(bcos of iy++) but since thers no other printf function so the value of 4 wont be displayed.

      …right??

    • #42638
      Anonymous
      Inactive

      #include<stdio.h>
      #include<ctype.h>
      #include<stdlib.h>
      #include<ctime>

      int main()
      {
      int x = 12;
      int y = 0;
      int z = 0;

      printf("\nThe following shows a multiplication table of 12\n");

      for (y = 0; y < 13; y++ ){
      printf("\n12 x %d = %d\n",z++,x * y);
      }
      }

      1st problem done within 5 minutes(no seriously)
      but is there a better way or quicker way???

    • #42639
      Anonymous
      Inactive

      int main()
      {
      int x = 0;
      int y = 1;

      x = y++ * 4;

      printf("\nThe value of x is %d\n",x);

      }

      The value of x = 4
      ———————————-
      int main()
      {
      int x = 0;
      int y = 1;

      x = y++ * 4;

      printf("\nThe value of x is %d\n",y++ * 4);

      }

      the value of x = 8 :shock:
      ———————————-
      but i thought x = y++ *4, so shouldnt it be the same result if i put in either x or y++ *4 after the comma??????

      and i realise if i put in ++y *4, i’ll get 12 instead….my head’s wrecked…

    • #42640
      Anonymous
      Inactive

      Ok let me first explain what ++ after a variable and ++ before a variable means. iy++ means post increment, so its current value gets used in your ix = iy++ * 2; statement i.e 1. Straight after that line iy gets 1 added to it. This does not effect the value of ix as it was calculated when iy equal 1 so ix equals 2, (1*2)=2.

      If you used ix=++iy *2; that is a pre increment of iy, so it takes the current value of iy and adds 1 in the current line:
      so ix = ++iy * 2; is ix=(1+1)*2=4; iy equals 2 in the line and after it.
      Same idea applies with decrements "–"

      With your code for x12 tables your including things you don’t need at the top. All you need should need is #include<stdio.h>.
      You should only include what you need as compiler will as name suggests include those files making your compiled code longer.

      You can save a few lines in the code but that does not mean the complier will produce better / faster code. Code below is shorter but not necessarily much better.

      #include<stdio.h>
      int main()
      {
      printf("\nThe following shows a multiplication table of 12\n");

      for (int y = 0; y < 13; y++ ){
      printf("\n12 x %d = %d\n",y,12 * y);
      }
      }

    • #42643
      Anonymous
      Inactive

      Something you might want to think about doing ( something I never did when I was learning ) is to think about using coding standards too. Get used to it now and its less of a burden when you get a job and you have to start using them. Most common form of coding standards is Hungarian. Basically you’re naming your variables in relationg to the Type they are, so for instance in your previous program, you would declare your int Result variable as int iResult instead. The ‘i’ at the start indicates its an int for future reference for yourself or anyone else reading your code. A float variable would be prefixed with ‘f’, bools with ‘b’, and so on.
      Just do a search for Hungarian Notation for more info.[/quote:287d17194f]Yuck. :P (Systems) Hungarian Notation and Coding Standards can’t be used interchangeably… One is an utterly essential tool for developers to improve the quality of their code, the other just makes code ugly. :wink:

      For anyone looking for what Coding Standards at developers should be like, here is the Lockheed Martin Corporation’s Joint Strike Fighter C++ Coding Standards: http://www.research.att.com/~bs/JSF-AV-rules.pdf

      Alternatively, with the addition of some rules on formatting of code, and a few rules relating to best practice on consoles, one could just propose Scott Meyers’ indispensable Effective C++ and More Effective C++ books as a de-facto coding standard on large projects.

      And for Systems Hungarian versus Apps Hungarian, Joel Spolsky has a blog entry that makes a good read: http://www.joelonsoftware.com/articles/Wrong.html

    • #42647
      Anonymous
      Inactive

      Hi all,

      This is probably going to turn into the long rant, so maybe we should consider migrating to a stand-alone thread on coding standards.

      I think Omen is correct when he advises new programmers to employ a coding standard.

      Hungarian notation is a good place to start.

      As for System vs. Application, whatever. Like most things in CompSci its important to understand both sides of the argument, and make up your own mind, (or the company you work for will make it up for you).

      There is a little bit about the debate here:

      http://en.wikipedia.org/wiki/Hungarian_notation#Systems_vs._Apps_Hungarian

      and there is even a dedicated book on the subject:
      http://www.amazon.com/Coding-Standards-Guidelines-Practices-Depth/dp/0321113586

      Just my 2 cents…

      Regards,
      Brendan.

    • #42667
      Anonymous
      Inactive

      so david- can you pls explain this code to me:

      int main()
      {
      int x = 0;
      int y = 1;

      x = ++y * 4;

      printf("\nThe value of x is %d\n",++y * 4);

      }

      [ x = ++y * 4]–so if the value was increased by 1 first( then y = 2 at the moment), shouldnt i get 8??but i get 12 instead, does the [++y * 4] in the printf() adds another 1 to y(which will make y = 3 now)??

    • #42668
      Anonymous
      Inactive

      You’re incrementing y again in the print statement. You should only use the formula once and print y rather than "++y*4"

    • #42672
      Anonymous
      Inactive

      Nifty is right, before your print statement x would equal 8 as you were expecting.
      y+1=(2)
      x=(2)*4=8

      But then in your print statement : printf("\nThe value of x is %d\n",++y * 4);

      You are adding 1 to y which is already equal to 2 and multiplying by 4.
      y=2+1=(3)
      (3)*4=12. So 12 would be printed. What you wanted was
      printf("\nThe value of x is %d\n",x); to have 8 printed

      Here are more examples.

      int A=0;
      int B=0;

      int C=0;
      int D=0;

      //post increment
      B=A++; //B now equals the value of A so B=0.
      //after above line A gets 1 added to it so A now =1. B has not changed still 0.

      B=A; //now B=1 as A has just been incremented to equal 1.

      //———————————

      //pre increment
      D=++C; //C is incremented before assigned to D so now D and C will equal 1

      same statement repeated
      D=++C; //C was 1 and is pre-incremented again by one so D and C now equal 2;

    • #42673
      Anonymous
      Inactive

      I think Omen is correct when he advises new programmers to employ a coding standard.

      Hungarian notation is a good place to start.

      As for System vs. Application, whatever. [/quote:e2a68dea26]

      Yup, chances are you’re going to have to follow a custom company standard anyway, so as long as you are used to using a Standard, all’s good. Its a bugger when you have to change your stardard to match the company, but you soon get used to it.

    • #42674
      Anonymous
      Inactive

      thanks david and nifty,

      i’m pretty sure i get the picture now.

      so let’s take:
      int c = 0;
      int d = 0;

      d = c++;

      [d = c];

      printf("\nValue of d is %d\n",d);

      if i run the code i’ll get d = 1 BECAUSE of the line [d = c]; , but IF i leave out [d = c]; , i’ll get zero since d is still equal to zero(even the value of c has been increased to 1 but i leave out the line [d = c] ie. dont initialised it, i’ll still get d = 0), that’s right…right?

    • #42675
      Anonymous
      Inactive

      int main()
      {
      —— int x, iNumberOfQuestions, iResponse, iRndNum1, iRndNum2;
      —— srand(time(0));

      —— printf("\nPlease enter the number of questions to ask:\n");
      —— scanf("%d",&iNumberOfQuestions);

      —— for(x = 0; x < iNumberOfQuestions; x++){
      —— —— iRndNum1 = rand () % 12 + 1;
      —— —— iRndNum2 = rand () % 12 + 1;

      —— —— printf("\nWhat is %d x %d??\n", iRndNum1,iRndNum2);
      —— —— scanf("%d",&iResponse);

      —— —— if(iResponse = iRndNum1 * iRndNum2 )
      —— ———— printf("Yes your right!\n");
      —— —— else
      —— —— —— printf("Sorry the correct answer is %d\n",iRndNum1 * iRndNum2);

      —— }

      }

      ok the printf() function never print out(Sorry the correct answer is %d\n), even if i purposely put in the wrong answer…i’m sure i have gone wrong somewhere, anyone spot it??yes?no?maybe?

    • #42676
      Anonymous
      Inactive

      Hi jin
      Yes you are right. don’t used the square brackets "[]" though.

      If statement is your problem.
      When doing comparisons use == not one =.

      = means an assignment rather than a test for equality ==

    • #42677
      Anonymous
      Inactive

      ahh david, u’ve made my day 10x better now, where would i be without u… on the other hand, well spot!! thanks again :)

    • #42688
      Anonymous
      Inactive

      #include<stdio.h>
      #include<stdlib.h>

      int main()
      {
      —— int x;

      —— for(x = 10; x > 2; x–){

      —— —— if(x == 7)
      —— —— —— continue;

      —— —— —— printf("\n%d\n",x);
      —— }
      }

      ok i cant seem to run the code normally, i can run it but the compiler says:"UNC paths are not supported", anything seems wrong here??

    • #42689
      Anonymous
      Inactive

      Challenge:

      write a program tat reads integers from the user and prints the average of numbers that have been entered so far.

      Problem: the user ‘s allowed to enter alot of digits without any restrictions, so will i use char type to store the numbers read through scanf??????

      its meant to be quite simple but i cant seemed to get the picture, anyone guide this lost sheep here :)

    • #42690
      Anonymous
      Inactive

      int main(int argc, char *argv[])
      {
      int a = 0;
      int b = 0;
      int c = 0;
      int d = 0;

      do{
      printf("\nPlease enter digits;\n");
      scanf("%d%d%d%d",&a,&b,&c,&d);
      printf("\nthe sum of the values is: %d\n",a + b +c +d);

      }while(a != -1);
      }

      this is all i can came up with…..

    • #42692
      Anonymous
      Inactive

      Your earlier code looks fine. UNC path message is most likely a result of directories you have set . If you made changes to your compiler environment then I would recheck them. If you haven’t I don’t know why your getting that message.

      Average Problem:
      Put your scanf in a loop testing for end of input.
      You need to have a running total to which you add each entry during each iteration of the loop and also keep a count of how many numbers have been entered. Then when the loop is ended you simply divide.

      Try get that working. Good practice to work off a worded description as above. Answer done below but I really suggest you don’t look at it till you have tried again.

      How I would do it:

      [code:1:c8567e7c04]
      #include<stdio.h>
      #include<stdlib.h>

      int main()
      {
      int entry;
      int runningTotal=0;
      int countofEntries=0;

      while(scanf("%d",&entry) != EOF)
      {
      runningTotal+=entry;
      countofEntries++;
      }

      if (countofEntries>0)
      {
      printf("\nSum is: %d, Average is: %f\n",runningTotal,(float)runningTotal/countofEntries);
      }
      else
      {
      printf("\nSum is: 0, Average is:0");
      }
      }
      [/code:1:c8567e7c04]

    • #42693
      Anonymous
      Inactive

    • #42696
      Anonymous
      Inactive

      Well not sure if "without any restrictions" is ready to be tacked just yet if you mean discounting letters and symbols as not numbers.

      The code I gave does allow numbers to be entered in a single line if separated by spaces and so can take the maximum input scanf can cope with. I can show how to discount letters and symbols if you want.

      Thane: think you would need to set total to zero after each average calc if further input was to be added and also be careful of zero divides.

    • #42699
      Anonymous
      Inactive

      david- yea i’m working on the mathemathical concept of the average now, i’ll try 2 resist looking at ur answer. Thanks very much

    • #42702
      Anonymous
      Inactive

    • #42703
      Anonymous
      Inactive

      Hi Thane: Yep I am more used to using cin and cout as well but tried to follow code style.

      Plus with cin you don’t get those "’scanf’ was declared deprecated" warnings clogging up the build output.

    • #42711
      Anonymous
      Inactive

      #include<stdio.h>
      #include<stdlib.h>

      int main()
      {
      int input = 0;
      int sum = 0;
      int counter = 0;//counts the amount of numbers entered
      int average = 0;

      do
      printf("\nPlease enter a number:\n");
      scanf("%d",&input);

      sum += input;
      counter += 1;
      average = sum % counter;

      printf("The average is: %d\n",average);
      while(input != -1);

      }

      ok parse error b4 scanf…but everything seems fine, imust’ve made some silly mistakes somewhere :cry:but i cant seem to spot it!!!

    • #42712
      Anonymous
      Inactive

      At quick glance you need to bracket your do statements "{}" and don’t use "%" where you mean "/" for division.

    • #42715
      Anonymous
      Inactive

      yes!! it works!!!!!!!! 8)

      i cant believe i spent nearly 2 hours on this thing……

      btw thank thane i’ll try out ur way to wats the story is.

      @david- thanks as usual

    • #42716
      Anonymous
      Inactive

      hey david and thane

      can you tell me how to use the white box that you used to display code, its a pain in the ass for me everytime i put a long code and have to put in loads of "——-" to make the code readable.

    • #42717
      Anonymous
      Inactive

      nvm found it already

      so after that here’s my small problem

      [code:1:8a0145d0af]//A concentration game

      #include<stdio.h>
      #include<stdlib.h>
      #include<ctype.h>

      int main()
      {
      char cYesNo =”;
      int iResponse1 = 0;
      int iResponse2= 0;
      int iResponse3 = 0;
      int iElapsedTime = 0;
      int iCurrentTime = 0;
      int iRandNum = 0;
      int 1 = 0;
      int 2 = 0;
      int 3 = 0;
      int iCounter = 0;

      srand(time(0));

      printf("Play a game of concentration (y or n):");
      scanf("%c",&cYesNo);

      if(cYesNo == y)||(cYesNo == Y){

      1 = rand()% 100;
      2 = rand()% 100;
      3 = rand()% 100;

      printf("\nConcentrate on the next three numbers: %d\t%d\t%d\n",1,2,3);

      iCurrentTime = time(0);

      do{
      iElapsedTime = time(0);
      }
      while((iElapsedTime – iCurrentTime) < 3);

      system("clear");

      printf("Enter each# separated with one space:");
      scanf("%d%d%d",&iResponse1,&iResponse2,&iResponse3);

      if(1 == iResponse1 && 2 == iResponse2 && 3 == iResponse3 &&){
      printf("\nCongratulations!\n");

      else
      printf("Sorry the correcet number was %d %d %d\n",1,2,3);
      }
      }
      }
      [/code:1:8a0145d0af] lots of error…help??

    • #42719
      Anonymous
      Inactive

      umm if this is C++ why are you using printf and scanf, instead of cout and cin ?

    • #42721
      Anonymous
      Inactive

      @supermario- i dunno? i got a book called c programming for beginners. and i’m a erm…..noob?think tats how they called newbie now xD

    • #42722
      Anonymous
      Inactive

      Okey doke. Yeah there is a bunch of errors, where did you get this code? You should look at the line numbers of errors and try to solve each one at a time – compiler messages seem cryptic but are quite informative. If writing your own code compile constantly to check for errors and that way it will be lines you have just written and will be fresh in your mind as to what you were trying to do.

      Ok the errors:
      int 1 = 0; Don’t do that…. ever. Don’t start a variable with a number or symbol even if compiler were to allow it. Plus just using a number would make code impossible to read.

      Use letters followed by a number if you want: int number1=0;

      if using time you need #include<ctime>

      system("clear"); does not work for me. Use system("cls") if you have too.

      Check () bracketing on if statements and {} around code.
      Characters need single quotes. ‘A’ ‘a’

      [code:1:185c61f6f0]
      #include<stdio.h>
      #include<stdlib.h>
      #include<ctype.h>
      #include<ctime>

      int main()
      {
      char cYesNo =”;
      int iResponse1 = 0;
      int iResponse2= 0;
      int iResponse3 = 0;
      int iElapsedTime = 0;
      int iCurrentTime = 0;
      int iRandNum = 0;
      int num1 = 0;
      int num2 = 0;
      int num3 = 0;
      int iCounter = 0;

      srand(time(0));

      printf("Play a game of concentration (y or n):");
      scanf("%c",&cYesNo);

      if((cYesNo == ‘y’)||(cYesNo == ‘Y’)){

      num1 = rand()% 100;
      num2 = rand()% 100;
      num3 = rand()% 100;

      printf("\nConcentrate on the next three numbers: %d\t%d\t%d\n",num1,num2,num3);

      iCurrentTime = time(0);

      do{
      iElapsedTime = time(0);
      }
      while((iElapsedTime – iCurrentTime) < 3);

      //system("clear");
      system("cls");//clears the screen

      printf("Enter each# separated with one space:");
      scanf("%d%d%d",&iResponse1,&iResponse2,&iResponse3);

      if(num1 == iResponse1 && num2 == iResponse2 && num3 == iResponse3)
      {
      printf("\nCongratulations!\n");
      }
      else
      printf("Sorry the correcet number was %d %d %d\n",num1,num2,num3);
      }
      }
      [/code:1:185c61f6f0]

    • #42728
      Anonymous
      Inactive

    • #42744
      Anonymous
      Inactive

      @ david-

      yea when i have int 1 =0;, the compiler says missing ; before constant, and left operand must be 1-value, i was so confused until l put it in ur way, " int num1 = 0;"…and i made stupid mistakes again by not including the #include<ctime> header…anyway i got it sorted now, thanks.

    • #42746
      Anonymous
      Inactive

      @ david-

      yea when i have int 1 =0;, the compiler says missing ; before constant, and left operand must be 1-value, i was so confused until l put it in ur way, " int num1 = 0;"…and i made stupid mistakes again by not including the #include<ctime> header…anyway i got it sorted now, thanks.[/quote:e122260ccc]

      Its not 1-value, its L-value. In this case it meant you hadn’t set the type.

    • #42818
      Anonymous
      Inactive

      yea i had a pretty good week, i used my nephew and niece(one is 7 other one is 2) to trick or treat and i got 2 FULL BAGS OF FOODS(candy, crisps,biscuits, anything,u name it), yea thats gonna las me for 2 months at least :D …n i think its time for me to get back to my programming skill, think i’m getting bit rusty already…anyway hope everyone had a great halloween cause i sure enjoyed it!!

    • #42830
      Anonymous
      Inactive

      [code:1:01cd5f0610]#include<stdio.h>
      #include<stdlib.h>
      #include<iostream>
      #include<ctime>
      #include<ctype.h>

      int main()
      {
      char cSelection = ”;
      int iRandNum1 = 0;
      int iRandNum2 = 0;
      int iRandNum3 = 0;
      int iResponse1 = 0;
      int iResponse2 = 0;
      int iResponse3 = 0;
      int iCurrentTime = 0;
      int iElapsedTime = 0;
      srand(time(0));

      iRandNum1 = rand()%100;
      iRandNum2 = rand()%100;
      iRandNum3 = rand()%100;

      printf("\n\t\tWould u like to play a game(y/n)\n");
      scanf("%c",&cSelection);

      if((cSelection != ‘y’)||(cSelection != ‘Y’)){
      printf("\nHave a nice day!!\n");
      }

      if((cSelection == ‘y’)||(cSelection == ‘Y’)){
      printf("\nPlease memorise the 3 numbers:\t%d\t%d\t%d\n",iRandNum1,iRandNum2,iRandNum3);
      iCurrentTime = time(0);
      do{
      iElapsedTime = time(0);
      }while((iElapsedTime – iCurrentTime) < 3);
      system("cls");
      printf("\nPlease enter the 3 numbers that u saw wit space after each other:\n");
      scanf("%d%d%d",&iResponse1,&iResponse2,&iResponse3);

      if(iResponse1 == iRandNum1 && iResponse2 == iRandNum2 && iResponse3 == iRandNum3){
      printf("\nCongrats\n");
      }
      else{
      printf("\nSorry the correct number was:\t%d\t%d\t%d\n",iRandNum1,iRandNum2,iRandNum3);
      }

      }

      }
      [/code:1:01cd5f0610]

      ok i’m just trying to put in a msg where it says have a nice day if the user puts in other letter than n, but it doesnt really work, n my logic seems fine right???

    • #42831
      Anonymous
      Inactive

      problem: create a counting program tat counts from 1 – 100 in increment of 5

      does this mean i have to do a 5’s multiplication table out

      or like this: 1, 6, 11 ,16….100??

      anyway my code is here:
      [code:1:536d5a6282]
      #include<stdio.h>
      #include<stdlib.h>

      int main()
      {
      int i = 1;
      int x = 5;

      printf("\n1\n",i);
      for(i = 1; i < 20; i++){
      printf("\n%d\n",(x * i)+ 1);
      }
      printf("\n100\n");
      }
      [/code:1:536d5a6282]

      this is the one which i think is correct…

    • #42834
      Anonymous
      Inactive

      if((cSelection != ‘y’)||(cSelection != ‘Y’))[/quote:545d7348d0]

      That’s your problem, you should have && not ||

    • #42842
      Anonymous
      Inactive

      @omen- so i take it as:

      ||– same meaning as "or"

      &&– same m,eaning as "and" right?

      anwyay thanks 4 the help appreciate it

    • #42843
      Anonymous
      Inactive

      Yup, || is or. So what your statement said was
      if cSelection not equal to ‘y’ or ‘Y’, then fail.
      If you press ‘y’, that means you’ve not pressed ‘Y’ so that statement would fail. If you say if you haven’t pressed ‘y’ and ‘Y’, then you’re good.
      Multiple Nots, Ands and Ors in conditional statements can get confusing :)

    • #42850
      Anonymous
      Inactive

      @omen- yea i got confused for a while there with my and and or statements but i’m pretty sure i got the hang of it now… :D

      problem: Create a counting program that prompts the user for 3 inputs(shown next) that determine how and wat to count. Store the user’s answers in variables.Use the acquired data to build ur counting program wit a for loop and display the results to the user.

      –Beginning number to start counting from

      –Ending number to start counting at

      –increment number

      The way i see this question: Ask the user for 3 inputs(let’s say 1,2 and 3). Then ask them again how how they like those numbers to be counted(like from smallest to largest or from largest to smallest digit),OR ask the user if they would like to add those numbers together(or multiply or divide or subtract)…the latter thought seemed wrong so i presume the first thought was right??

      Can someone PLEEEEASE kindly put the question in an easier way :D

    • #42851
      Anonymous
      Inactive

      Programmers only do what their asked (and even then.. :) ), so don’t worry about multiplication and division etc.

      Take in the numbers something like this

      "Enter starting number:"
      "Enter finishing number:"
      "Enter increment (can be minus to do a count down):"

      Eg.
      Start 0, finish 10, increment 2 :
      0,2,4,6,8,10

      Or Start 10, finish 0, increment -2:
      10,8,6,4,2,0

      Can easily be done with a for loop. Which you have used before in the following format:
      int i;
      for(i=0; i<=10, i+=1)

      Just think variables rather than hard coded numbers.

      You should put in checks to ensure you don’t get infinite loop though.

    • #42852
      Anonymous
      Inactive

      thank you david!!! :lol:

    • #42853
      Anonymous
      Inactive

      [code:1:577523ba82]#include<stdio.h>
      #include<stdlib.h>

      int main()
      {
      int iBeginningNum = 0;
      int iEndingNum = 0;
      char cIncrementType = ”;
      int iIncrementPlus = 0;
      int iIncrementMinus = 0;

      printf("\nPlease enter the the beginning num: \n");
      scanf("%d",&iBeginningNum);

      printf("\nPlease enter the the ending num: \n");
      scanf("%d",&iEndingNum);

      printf("\nPlease enter the Increment type(P(plus)/M(minus)): \n");
      scanf("%c",&cIncrementType);

      if(cIncrementType == ‘P’ ){
      printf("\nPlease enter the number to increase each time:\n");
      scanf("%d",&iIncrementPlus);
      for(iBeginningNum = 0; iBeginningNum < iEndingNum; iBeginningNum++){
      printf("\n%d\n",iBeginningNum);
      }
      }
      }[/code:1:577523ba82]

      ok i run the program but it ends after the third printf(); function…help!!!

    • #42854
      Anonymous
      Inactive

      Well your using C style printf and scanf so I would suggest putting flushall(); before reading your char. Read up on why you would need this (Remember /n is a character that equals a keyboard return).

      Thinking about it more though I wouldn’t let the user choose if program is counting up or down, or set increment sign as should be based on whether iBeginningNum is less than iEndingNum or not.

      Here is how I would do it. Meant to ask are you doing a programming course? If so I ignore below as not a good idea to get solutions if these are assignments.

      [code:1:04d990c92c]
      #include<stdio.h>
      #include<stdlib.h>

      int main()
      {
      int iBeginningNum = 0;
      int iEndingNum = 0;
      int iIncrementNum = 0;

      printf("\nPlease enter the the beginning num: \n");
      scanf("%d",&iBeginningNum);

      printf("\nPlease enter the the ending num: \n");
      scanf("%d",&iEndingNum);

      printf("\nPlease enter the Increment num (sign ignored): \n");
      scanf("%d",&iIncrementNum);
      iIncrementNum=abs(iIncrementNum); //Remove minus if negative number

      printf("——————–\n"); //Just to seperate input from output

      if (iBeginningNum<iEndingNum)
      {
      printf("\n Counting up \n");

      for(iBeginningNum; iBeginningNum <= iEndingNum; iBeginningNum+=iIncrementNum)
      {
      printf("%d\n",iBeginningNum);
      }
      }else
      {
      //Could have made this else if (iBeginningNum>iEndingNum)
      //and then a final else would be a check to see if BeginningNum and iEndingNum were equal

      printf("\n Counting down \n");

      for(iBeginningNum; iBeginningNum >= iEndingNum; iBeginningNum-=iIncrementNum)
      {
      printf("%d\n",iBeginningNum);
      }
      }
      }
      [/code:1:04d990c92c]

    • #42856
      Anonymous
      Inactive

      to be honest i’m doing computer engineering, and yea computing/programming is part of this course for this year BUT all the questions i’ve asked werent my assignments at all, i just wanna bump up my knowledge in programming so i can eventually program my own game…and it actually feels pretty good to stay well ahead of the class 8) …anyway thanjks s usual david

    • #42873
      Anonymous
      Inactive

      ok here’s a program tat prompts the user to type in 10 numbers, store them in the array then prints them out in reverse order n i was given this code which i still dont really understand after readin the explanation.After this i need to display the read in input(the 10 numbers) in order so if i enter : 1,3,5,7,9,2,4,6,8,10, i need to print it out as:1,2,3,4,5,6,7,8,9,10. I found this quite hard anyway here’s the code

      [code:1:bff4eb17f0]#include<stdio.h>
      #define i 10
      int main ()
      {

      int a[i], j;
      printf("Please enter ONLY 10 numbers:\n");
      for (j = 0; j < i; j++)
      scanf("%d", &a[j]);//stores data into a
      printf("In reverse order:\n ");

      for (j = i – 1; j >=0; j–)
      printf("\n%d\n", a[j]);

      return 0;

      }[/code:1:bff4eb17f0]

      can someone explain the logic behind this code pls ?? the main thing i dont really get is the use of int j and a[j]:)

    • #42880
      Anonymous
      Inactive

      #include<stdio.h>[/quote:c37919a59b]
      library for printf/scanf , standard input output

      #define i 10[/quote:c37919a59b]
      This is a temp variable really. Defines the Size of the array. Used up here for easy alteration of the array size. That’s its typical use.

      int main ()
      {

      int a
      defines array "a" and variable "j" then prints message to screen to enter numbers.

      for (j = 0; j < i; j++)
      scanf("%d", &a[j]);//stores data into a
      printf("In reverse order:\n ");[/quote:c37919a59b]
      Loop that has the user enter ten numbers which is the size of the array. "j=0" sets it to zero at the first iteration/run through of the loop only. "j<i" is the same as "j<10" because i is 10, this means the loop finishes when j isn’t less then 10. "j++" adds 1 to j each iteration meaning the loop runs from 0-9. "j" is also used as the slot in the array meaning the array has ten slots numbered 0 to 9, arrays always start with 0. As "j" counts up each iteration the user is putting a number in each slot and not rewriting over the same slot in the array

      for (j = i – 1; j >=0; j–)
      printf("\n%d\n", a[j]);

      return 0;

      }[/quote:c37919a59b]
      same as above really but "j" starts as "i-1" and i is 10 so that means it starts at 9, the last slot in the array. "j>=0" means the loop runs until "j" is less then zero as the expression reads run loop while j is greater then 0. "j–" means that ""j" is minus 1 each iteration meaning it counts down instead of up. This means the last number gets printed first and the first number last, or it runs in reverse!

    • #42924
      Anonymous
      Inactive

      hello everybody,
      i’ve been experiencing a bit of trouble wit my visual basic 2008 express edition, the bloody thing wont compile any code!! it says something like: "rsc.exe cant be located", something along that line n i havent done any programming for nearly 3 weeks(been REAL busy) anyway anyone recommend a good one(n free too:lol:) for me to use? or would it be easier if i download the program n install it again??

    • #42930
      Anonymous
      Inactive

    • #42951
      Anonymous
      Inactive

      thanks thane i’ll give it a try

      anyway back to the real topic, pls check the code out below:

      [code:1:b7ffc0c655]for(x = 0; x < iQuestions; x++){

      iRandNum1 = rand()%100;
      iRandNum2 = rand()%100;
      printf("\nWhat’s the answer of:%d + %d?\n",iRandNum1,iRandNum2);
      scanf("%d",&iResponse);

      iAnswer = iRandNum1+iRandNum2;
      if (iResponse == iAnswer){
      printf("\nWell Done\n");
      printf("\nYou have answered %d questions right.\n",++iCounter);
      iCounter = iStore;
      }
      else
      printf("\nSorry the correct answer is %d\n",iAnswer);

      }[/code:1:b7ffc0c655]

      ok the problem occurs when i include [code:1:b7ffc0c655]iCounter = iStore;[/code:1:b7ffc0c655] otherwise it works fine when i excluded this GOD DAMN LINE…sorry i was a bit streesed out, just need to let it out…btw i need to store the counter, cos in the end i need to display the total number of questions answered right n wrong…i figured most of the things out already(i THINK i need), so i only included part of the codes :)help???

    • #42952
      Anonymous
      Inactive

      What’s the error (compile/run-time) message you get?

    • #42954
      Anonymous
      Inactive

      @anthony

      when i excluded that line: ++iCounter = iStore, my code does fine, let’s say i put in 3 questions, then the compiler will display how many questions i have answered right. but when i included that code, the compiler will says i only answer 1 question right, even if i got 3 right…

    • #42955
      Anonymous
      Inactive

      @anthony

      when i excluded that line: ++iCounter = iStore, my code does fine, let’s say i put in 3 questions, then the compiler will display how many questions i have answered right. but when i included that code, the compiler will says i only answer 1 question right, even if i got 3 right…[/quote:24bd51ef2e]

      What value are you setting iStore to at the start, 1? I think that line of code should be:

      [code:1:24bd51ef2e]iStore = iCounter;[/code:1:24bd51ef2e]

      This way you are storing the value of iCounter in iStore.

      [code:1:24bd51ef2e]variable = valueToStoreInIt;[/code:1:24bd51ef2e]

      Btw, try to comment your code as you go it will make it easier to debug stuff when you find a bug.

      I hope that’s right, it’s been a long day so I hope I’m not messing this up!

    • #42956
      Anonymous
      Inactive

      hmm…i was using the college’s computer to do the thing n saved it in there, i’m home now so i cant get my code, i’ll show the full code tommorow, thanks anthony, it’s a long day for me s well, cya tomorrow then.

    • #42957
      Anonymous
      Inactive

      Most likely

      iStore = iCounter;

      Also indention in your code is essential for helping with debugging.

    • #42959
      Anonymous
      Inactive

      nvm i think i got it right now, i was over-thinking yesterday, drink too much coke i guess….anyway here’s the code n it does pretty well so i’m a happy man once again:

      [code:1:e2e01b51d0]#include<stdio.h>
      #include<stdlib.h>
      #include<ctype.h>
      #include<ctime>

      int main()
      {
      int x = 0;
      int iQuestions = 0;
      int iRandNum1 = 0;
      int iRandNum2 = 0;
      int iAnswer = 0;
      int iResponse = 0;
      int iCounter = 0;
      int iStore = 0;
      srand(time(0));

      system("cls");

      printf("\n\t\tWelcome to a Math Quiz\n");
      printf("\nPls enter the amount of questions you would like to answer:\n");
      scanf("%d",&iQuestions);

      for(x = 0; x < iQuestions; x++){

      iRandNum1 = rand()%100;
      iRandNum2 = rand()%100;
      printf("\nWhat’s the answer of:%d + %d?\n",iRandNum1,iRandNum2);
      scanf("%d",&iResponse);

      iAnswer = iRandNum1+iRandNum2;
      if (iResponse == iAnswer){
      printf("\nWell Done\n");
      printf("\nYou have answered %d questions right.\n",++iCounter);

      }
      else
      printf("\nSorry the correct answer is %d\n",iAnswer);

      }

      printf("You have answered %d questions right\n",iCounter);
      printf("\nYou have answered %d questions wrong\n",iQuestions – iCounter);
      }[/code:1:e2e01b51d0]

      the question dint specify i have to ask different type questions like: multiplication, subtraction etc…so i just make them all addition….hehe, programmers are meant to be lazy right? think david told me tat b4…

    • #42961
      Anonymous
      Inactive

      programmers are meant to be lazy right? think david told me tat b4…[/quote:c2638a72f9]
      I like to phrase is as "time efficient in the extreme" :)

    • #42962
      Anonymous
      Inactive

      Virtues of a programmer

      Laziness
      The quality that makes you go to great effort to reduce overall energy expenditure. It makes you write labor-saving programs that other people will find useful, and document what you wrote so you don’t have to answer so many questions about it. Hence, the first great virtue of a programmer.
      Impatience
      The anger you feel when the computer is being lazy. This makes you write programs that don’t just react to your needs, but actually anticipate them. Or at least that pretend to. Hence, the second great virtue of a programmer.
      Hubris
      Excessive pride, the sort of thing Zeus zaps you for. Also the quality that makes you write (and maintain) programs that other people won’t want to say bad things about. [Also, the thing that makes you write programs to do something that’s already been done, because you believe you can do it better — Wim.] Hence, the third great virtue of a programmer. [/quote:74792e141c]

    • #43030
      Anonymous
      Inactive

      YES!!!!! it works, it WORKS!! my visual c++ works again yes!!! i’m burning with the desire of being a programmer that surpass david’s skills again…yes!!

    • #43091
      Anonymous
      Inactive

      stumble across this while practising my c programming(even though i’m doing matlab now, not too bad so far), n here’s the problem
      [code:1:f2a82fd264]#include<stdio.h>
      #include<stdlib.h>
      #include<ctype.h>
      #include<ctime>

      int main()
      {
      char cYesNo = 0;
      int iDifficulty1 = 0;
      int iResponse1 = 0;
      int iResponse2 = 0;
      int iResponse3 = 0;
      int iResponse4 = 0;
      int iResponse5 = 0;
      int iCurrentTime = 0;
      int iElapsedTime = 0;
      int iRandNum = 0;
      int iNum1 = 0;
      int iNum2 = 0;
      int iNum3 = 0;
      int iNum4 = 0;
      int iNum5 = 0;
      int iCounter = 0;
      srand(time(0));

      system("cls");

      printf("Would u like to play a concentration game(y or n)??");
      scanf("%c",&cYesNo);

      if((cYesNo == ‘y’) || (cYesNo == ‘Y’)){

      printf("\nPls choose a difficulty that suits u the most:\n");
      printf("1:Easy(remember 3 numbers in 5 seconds)\n2:Medium(remember 5 numbers in 5 seconds)\n3:Hard(remember 5 numbers in 2 seconds)\n4:Quit\n");
      scanf("%d",&iDifficulty1);

      if(iDifficulty1 == 1){
      iNum1 = rand()%100;
      iNum2 = rand()%100;
      iNum3 = rand()%100;

      printf("\nPlease concentrate on these 3 numbers:%d\t%d\t%d\n",iNum1,iNum2,iNum3);
      iCurrentTime = time(0);
      do {
      iElapsedTime = time(0);
      }while((iElapsedTime – iCurrentTime) < 6);

      system("cls");

      printf("\nPls enter each number with one space separated with each other:\n");
      scanf("%d%d%d",&iResponse1,&iResponse2,&iResponse3);

      if((iResponse1 == iNum1) && (iResponse2 == iNum2) && (iResponse3 == iNum3))

      printf("\nWell Done!!\n");

      else
      printf("\nSorry the correct numbers are: %d\t%d\t%d\n",iNum1,iNum2,iNum3);
      }
      }

      if(iDifficulty1 == 2){
      iNum1 = rand()%100;
      iNum2 = rand()%100;
      iNum3 = rand()%100;
      iNum4 = rand()%100;
      iNum5 = rand()%100;

      printf("\nPlease concentrate on these 5 numbers:\t%d\t%d\t%d\t%d\t%d\n",iNum1,iNum2,iNum3,iNum4,iNum5);
      iCurrentTime = time(0);
      do {
      iElapsedTime = time(0);
      }while((iElapsedTime – iCurrentTime) < 6);

      system("cls");

      printf("\nPls enter each number with one space separated with each other\n");
      scanf("%d%d%d%d%d",&iResponse1,&iResponse2,&iResponse3,&iResponse4,&iResponse5);

      if((iResponse1 == iNum1) && (iResponse2 == iNum2) && (iResponse3 == iNum3) &&(iResponse4 == iNum4)&&(iResponse5 == iNum5))

      printf("\nWell Done!!\n");

      else
      printf("\nSorry the correct numbers are:\t%d\t%d\t%d\t%d\t%d\n",iNum1,iNum2,iNum3,iNum4,iNum5);
      }

      if(iDifficulty1 == 3){
      iNum1 = rand()%100;
      iNum2 = rand()%100;
      iNum3 = rand()%100;
      iNum4 = rand()%100;
      iNum5 = rand()%100;

      printf("\nPlease concentrate on these 5 numbers:%d\t%d\t%d\t%d\t%d\n",iNum1,iNum2,iNum3,iNum4,iNum5);
      iCurrentTime = time(0);
      do {
      iElapsedTime = time(0);
      }while((iElapsedTime – iCurrentTime) < 2);

      system("cls");

      printf("\nPls enter each number with one space separated with each other:\n");
      scanf("%d%d%d%d%d",&iResponse1,&iResponse2,&iResponse3,&iResponse4,&iResponse5);

      if((iResponse1 == iNum1) && (iResponse2 == iNum2) && (iResponse3 == iNum3) &&(iResponse4 == iNum4)&&(iResponse5 == iNum5))

      printf("\nWell Done!!\n");

      else
      printf("\nSorry the correct numbers are:\t%d\t%d\t%d\t%d\t%d\n",iNum1,iNum2,iNum3,iNum4,iNum5);
      }

      }
      [/code:1:f2a82fd264]

      ok the book said i’ll need to do a loop which ask the user if they wanna play the game everytime after they completed the game. i thought of simply put the line: while(iDifficulty1 != 4) after the system("cls");line but it dint work very well, so anyone kind enough to gimme a hint :)

    • #43093
      Anonymous
      Inactive

      1) It asks if you want to play the game again, you want to encompass the entire game with your loop.
      2) Why would you test your test loop against the difficulty level of the game…try using something else for the play again flag.

    • #43101
      Anonymous
      Inactive

      [code:1:3fd550f559]#include<stdio.h>
      #include<stdlib.h>
      #include<ctype.h>
      #include<ctime>

      int main()
      {
      char cYesNo = ”;
      int iDifficulty1 = 0;
      int iResponse1 = 0;
      int iResponse2 = 0;
      int iResponse3 = 0;
      int iResponse4 = 0;
      int iResponse5 = 0;
      int iCurrentTime = 0;
      int iElapsedTime = 0;
      int iRandNum = 0;
      int iNum1 = 0;
      int iNum2 = 0;
      int iNum3 = 0;
      int iNum4 = 0;
      int iNum5 = 0;
      int iCounter = 0;
      srand(time(0));

      do{
      system("cls");

      printf("Would u like to play a concentration game(y or n)??");
      scanf("%c",&cYesNo);

      if((cYesNo == ‘y’) || (cYesNo == ‘Y’)){

      printf("\nPls choose a difficulty that suits u the most:\n");
      printf("1:Easy(remember 3 numbers in 5 seconds)\n2:Medium(remember 5 numbers in 5 seconds)\n3:Hard(remember 5 numbers in 2 seconds)\n4:Quit\n");
      scanf("%d",&iDifficulty1);

      if(iDifficulty1 == 1){
      iNum1 = rand()%100;
      iNum2 = rand()%100;
      iNum3 = rand()%100;

      printf("\nPlease concentrate on these 3 numbers:\t%d\t%d\t%d\n",iNum1,iNum2,iNum3);
      iCurrentTime = time(0);
      do {
      iElapsedTime = time(0);
      }while((iElapsedTime – iCurrentTime) < 6);

      system("cls");

      printf("\nPls enter each number with one space separated with each other:\n");
      scanf("%d%d%d",&iResponse1,&iResponse2,&iResponse3);

      if((iResponse1 == iNum1) && (iResponse2 == iNum2) && (iResponse3 == iNum3))

      printf("\nWell Done!!\n");

      else
      printf("\nSorry the correct numbers are:\t%d\t%d\t%d\n",iNum1,iNum2,iNum3);

      do {
      iElapsedTime = time(0);
      }while((iElapsedTime – iCurrentTime) < 3);
      }

      if(iDifficulty1 == 2){
      iNum1 = rand()%100;
      iNum2 = rand()%100;
      iNum3 = rand()%100;
      iNum4 = rand()%100;
      iNum5 = rand()%100;

      printf("\nPlease concentrate on these 5 numbers:\t%d\t%d\t%d\t%d\t%d\n",iNum1,iNum2,iNum3,iNum4,iNum5);
      iCurrentTime = time(0);
      do {
      iElapsedTime = time(0);
      }while((iElapsedTime – iCurrentTime) < 6);

      system("cls");

      printf("\nPls enter each number with one space separated with each other\n");
      scanf("%d%d%d%d%d",&iResponse1,&iResponse2,&iResponse3,&iResponse4,&iResponse5);

      if((iResponse1 == iNum1) && (iResponse2 == iNum2) && (iResponse3 == iNum3) &&(iResponse4 == iNum4)&&(iResponse5 == iNum5))

      printf("\nWell Done!!\n");

      else
      printf("\nSorry the correct numbers are:\t%d\t%d\t%d\t%d\t%d\n",iNum1,iNum2,iNum3,iNum4,iNum5);

      do {
      iElapsedTime = time(0);
      }while((iElapsedTime – iCurrentTime) < 3);
      }

      if(iDifficulty1 == 3){
      iNum1 = rand()%100;
      iNum2 = rand()%100;
      iNum3 = rand()%100;
      iNum4 = rand()%100;
      iNum5 = rand()%100;

      printf("\nPlease concentrate on these 5 numbers:\t%d\t%d\t%d\t%d\t%d\n",iNum1,iNum2,iNum3,iNum4,iNum5);
      iCurrentTime = time(0);
      do {
      iElapsedTime = time(0);
      }while((iElapsedTime – iCurrentTime) < 2);

      system("cls");

      printf("\nPls enter each number with one space separated with each other:\n");
      scanf("%d%d%d%d%d",&iResponse1,&iResponse2,&iResponse3,&iResponse4,&iResponse5);

      if((iResponse1 == iNum1) && (iResponse2 == iNum2) && (iResponse3 == iNum3) &&(iResponse4 == iNum4)&&(iResponse5 == iNum5))

      printf("\nWell Done!!\n");

      else
      printf("\nSorry the correct numbers are:\t%d\t%d\t%d\t%d\t%d\n",iNum1,iNum2,iNum3,iNum4,iNum5);
      do {
      iElapsedTime = time(0);
      }while((iElapsedTime – iCurrentTime) < 3);
      }
      }
      else
      printf("\nhave a nice day\n");

      }while(cYesNo = ‘y’);

      }[/code:1:3fd550f559] hmm… i think i got it out here, it works pretty well but the compiler cant seem to terminate itself when i type in ‘n’ in the beginning, it simply shows have a nice day and rerun the whole thing instead of quitting, i thought the whole thing will only run again if cYesNo = y 0_0? i kno i can put in :while(cYesNo == ‘y’); instead of "cYesNo=y", i tried it n it will terminate itself but wont run the program repeatedly :(

    • #43105
      Anonymous
      Inactive

      Your final while should be giving you a warning in the compiler…you’ve got an assignment operator ( = ) rather than an equals operator ( == )

    • #43339
      Anonymous
      Inactive

      Cleaning off my desktop, and thought this link may be of use to the locals who are starting down the path of learning C++.

      http://www.codesampler.com/miscsrc.htm

      B.

    • #43416
      Anonymous
      Inactive

      ok just some nooby questions regarding function call as usual

      [code:1:b8cc3cfbfe]
      /*Function Prototypes*/
      int SportQuestions(void);
      int GeographyQuestions(void);
      void pause(int);
      /*End of function prototypes*/

      int giResponse = 0;//global variable

      int main()
      {
      do{
      system("cls");
      printf("\nA trivia Game\n");
      printf("\n1\tSports\n");
      printf("\n2\tGeography\n");
      printf("\n3\tQuit\n");
      printf("\nEnter ur selection:");
      scanf("%d",&giResponse);

      switch(giResponse){

      case 1:

      if(SportQuestions() == 4)
      printf("\nWell Done!!!\n");
      else
      printf("\nIncorrect!!\n");
      pause(2);
      break;

      case 2:

      if(GeographyQuestions() == 4)
      printf("\nCorrect!!!\n");
      else
      printf("\nIncorrect\n");
      pause(2);
      break;
      }//end switch
      }while(giResponse != 3);
      }//end main function

      //function definition of SportQuestions
      int SportQuestions(void)
      {
      int iAnswer = 0;
      system("cls");
      printf("\nSport Questions\n");
      printf("\nWhich university did Deon Sanders go to??\n");
      printf("\n1\t\tSpu University\n");
      printf("\n2\t\tSkyfall University\n");
      printf("\n3\t\tBlack Rock University\n");
      printf("\n4\t\tFlorida University\n");
      printf("\nPls enter ur selection(1-4):");
      scanf("%d",&iAnswer);
      return iAnswer;
      }//end of sportQuestions

      //function definition of GeographyQuestions
      int GeographyQuestions(void)
      {
      int iAnswer = 0;
      system("cls");
      printf("\nGeography Questions\n");
      printf("\nWhich is the capital of Malaysia??\n");
      printf("\n1\t\tPulau Pinang\n");
      printf("\n2\t\tKuala Perlis\n");
      printf("\n3\t\tBatu Pahat\n");
      printf("\n4\t\tKuala Lumpur\n");
      printf("\nPls enter ur selection(1-4):");
      scanf("%d",&iAnswer);
      return iAnswer;
      }//end of GeographyQuestions

      //function definition of pause
      void pause(int inNum)
      {
      int iCurrentTime = 0;
      int iElapsedTime = 0;
      iCurrentTime = time(NULL);
      do
      {
      iElapsedTime = time(NULL);
      }while((iElapsedTime – iCurrentTime)< inNum);
      }//end of pause[/code:1:b8cc3cfbfe]

      erm…the part that i dont fully understand is the pause function part,where (iElapsedTime – iCurrentTime)< inNum, me see this as:

      iCurrentTime is the same as iElapsedTime, so when take iElapsedTime away from iCurrentTime, it will be 0, n since inNum = 2, this makes the end of either sport/geography function wait 2 secs b4 the whole thing loops back to the int main() functions again?? thats how i see it, am i right, i got some kinda feeling tat i might miss something…
      [code:1:b8cc3cfbfe]void pause(int inNum)
      {
      int iCurrentTime = 0;
      int iElapsedTime = 0;
      iCurrentTime = time(NULL);
      do
      {
      iElapsedTime = time(NULL);
      }while((iElapsedTime – iCurrentTime)< inNum);
      }//end of pause[/code:1:b8cc3cfbfe]

    • #43421
      Anonymous
      Inactive

      erm…the part that i dont fully understand is the pause function part,where (iElapsedTime – iCurrentTime)< inNum, me see this as:

      iCurrentTime is the same as iElapsedTime, so when take iElapsedTime away from iCurrentTime, it will be 0, n since inNum = 2, this makes the end of either sport/geography function wait 2 secs b4 the whole thing loops back to the int main() functions again?? thats how i see it, am i right, i got some kinda feeling tat i might miss something…
      [code:1:74164aab32]void pause(int inNum)
      {
      int iCurrentTime = 0;
      int iElapsedTime = 0;
      iCurrentTime = time(NULL);
      do
      {
      iElapsedTime = time(NULL);
      }while((iElapsedTime – iCurrentTime)< inNum);
      }//end of pause[/code:1:74164aab32][/quote:74164aab32]

      That code just waits for the number of time units passed in.
      (Approximately).

      The only thing that might be confusing is the naming of ‘iElapsedTime’ and ‘iCurrentTime’.

      iCurrentTime might be better called ‘iStartTime’ – as it’s where the time that the loop starts to wait at is stored.
      iElapsedTime might be better called iCurrentTime – as it’s where the current time, which is compared to the starting time (+the delta/wait) is stored.

      The variable names are wrong, so that’s probably why it’s confusing.

      Do you understand it all now?

      When the function runs, it simply stores the starting time, and then keeps looping until (the_current_time subtract the_starting_time) is greater than the amount of time to pause.

      In other words, the algorithm by be:
      Hey, I want you to wait for a few seconds.

      Ok, I’ll write down what time it is now.
      And then I’ll check if the difference between the time on my watch at the moment, and the time I wrote down, is still less than how long you told me to wait.
      I’ll keep doing this, until the difference is greater than how long you told me to wait.
      Then I’ll go do something else!

      It’s just like if you decide to wait 15 minutes for someone you are expecting to meet.
      You know when they were supposed to arrive, and you just keep checking your watch to see if they were supposed to arrive more than 15 minutes ago – and as soon as the time on your watch, minus the time they said they’d meet you at, is greater than 15 minutes (inNum), well, you stop waiting, and go do the next thing.

      The variable names above are bad though – programming error.

    • #43423
      Anonymous
      Inactive

      When the function runs, it simply stores the starting time, and then keeps looping until (the_current_time subtract the_starting_time) is greater than the amount of time to pause.

      [/quote:19d3189ae3]

      AHA!! You nailed it right there man(i think)!!
      So…let’s say as soon as the function starts, it stores the actual time(say 5:15) in iStartTime, then when it gets to iCurrentTime(say 5:15 but .1 sec longer), the iCurrentTime will subtract iStartTime and compare to inNum. The function will keep repeating itself until the difference in time is bigger than inNum which is 2 secs in my case :D

      By the way how does the computer stores the time, i presume it stores it in 8421BCD style right?? so if the time is 5:15, it stores it as 0101:00010101???

      P.S I like the way you put it as if i’m waiting for some1, that makes things alot clearer to me n it makes everything simpler, big thanks :lol:

    • #43425
      Anonymous
      Inactive

      Thanks for the nice feedback :-)

      By the way how does the computer stores the time, i presume it stores it in 8421BCD style right?? so if the time is 5:15, it stores it as 0101:00010101???
      [/quote:08d37528d5]

      Erm…
      Thats a hard question to answer. Not 100% sure what you’re asking, so will try cover the area…

      First off, what do you mean by when the computer (as opposed to your program) ‘stores’?

      If you are referring to the current time, the computer doesn’t store it as such, it’s always changing.

      Instead the computer (depending on the hardware) probably interrogates some sort of system device for the current time – often a system device whose sole job is timekeeping – and it is this time that eventually gets returned as a result of the system call you make to get the current time.

      Sometimes, the time returned by the device may be interpolated or sampled somehow first, depending on operating system, and hardware in question.

      The exact mechanics of this process are very hardware dependent, but in general you have to realise that the running program as such doesn’t track time – it can’t – instead the current time has to be gotten from somewhere – generally some sort of clock thats in the hardware.

      Computers generally have some piece of hardware called the system clock whose job it is to track time. It usually has a little battery too, so that the time is kept when the computer is off. Eventually, at some level, it’s this clock that’s providing the time when you make a system call to get the time. (sometimes other stuff happens in between, for more accuracy – it’s a complicated area – but in general this clock is the ultimate source of broad grained time on the system)

      This clock might be something as simple as a crystal oscillating at a certain frequency, due to an electric current supplied to it by the battery – like in your digital watch – or could be something like a 555 chip, in a simple microprocessor. It all depends on the hardware you are talking about.

      This ‘system clock’ might have been set to the right time manually by the user when the computer was first turned on, or set in the factory when the bios is installed, and could also be regularly updated, due to synching via a protocol like NTP – where you get the current time from a server.

      But anyway, the main point is that there’s some hardware mechanism by which the computer can access the time, and it’s this time, in some form or other, that’s eventually provided by whatever call you make in your programming language.

      In what format exactly the time arrives into your program, when you make a call like ‘time(NULL)’ depends completely on your implementation language, environment, operating system, etc.

      What format this time is generally returned in, and what time it’s generally moved around in the operating system, under the hood, very much depends.

      One thing to mention, is that it’s highly unlikely, to be BCD in the format you suggested.

      That representation would be extremely hard and inefficient to work with programatically. If you think about it, it’s quite hard to subtract too dates in the time you provided. Imagine writing code to try to get how many second between one timestamp and another, so encoded in BCD? It’s pretty complex.

      One timely (heh) example of how time is represented in a real world computer would be Unix epoch time.

      In Unix, time is typically stored as a signed offset in seconds since midnight utc jan 1st 1970.
      This was in the past usually stored as a 32bit int. They’re moving to 64bit to avoid overflow later this century. (Easy to see why if you do some multiplication!)

      But different operating systems, and environments might store it differently internally. Read the API documentation of the call you make to see what format time is returned to you in. Making false assumptions about this is a potential source of bugs – eg if you have to make systems that work across timezones, work in local time, then in UTC etc.

      I said discussing Unix to give you a flavour was timely, because tomorrow, around 23:30 (utc – watch those bugs, especially in summer), epoch time is:

      1234567890

      woo!

    • #43426
      Anonymous
      Inactive

      :shock:
      Wow, i never thought that time could be stored in so many ways, i’ve always thought it’s the same way to store time in a computer. Sorry i will be more specific with my question next time.

      About the unix time thing, yea i’ve heard of that too, cos i read up some hackers net that some websites used the unix time conversion(as a security measure) as their websites’ url, i mean if somebody set up an account with an album locked and passwords are required to access the album, it’s possible to guess the URL if you know what time the user put up his album :D

      thanks for the unix time thing, i’ll check it out tonight 8)

    • #43444
      Anonymous
      Inactive

      help!!

      [code:1:f45f4949aa]
      int main()
      {

      int l = 0;
      int r = 0;

      for(l = 0; l < 7; l++){
      r = 0;
      while(r < 7){
      printf("\n%d,%d\n",l,r);
      r++;

      }
      }

      }
      [/code:1:f45f4949aa]

      ok i need to alter this program so it prints out the following(but the code above is the furthest i can get…):
      0,0
      0,1
      0,2
      0,3
      0,4
      0,5
      0,6
      1,1
      1,2
      1,3
      1,4
      1,5
      1,6
      2,2
      2,3
      .
      .
      .
      .
      .
      .
      .6,6

      and i dunno how to…can somebody kinda give a hint?? :oops:

    • #43447
      Anonymous
      Inactive

      Look at the value you initially assign to ‘r’

      What would the effect of changing it to a different value be?

    • #43448
      Anonymous
      Inactive

      Its an unusual pattern as if you start from "0,0" you usually have "1,0" "2,0" etc otherwise the pattern doesnt repeat.

      If you really have to print 0,0 at the start might be worth hardcoding that part.

    • #43449
      Anonymous
      Inactive

      Its an unusual pattern as if you start from "0,0" you usually have "1,0" "2,0" etc otherwise the pattern doesnt repeat.
      [/quote:9c370013a9]
      It’s still extremely simple to code algorithmically. The answer should be fairly obvious at a glance to an intermediate coder. I’m not going to say what it is, as the original post asked for hints.

      If you really have to print 0,0 at the start might be worth hardcoding that part.[/quote:9c370013a9]
      I think this is bad programming advice.

      There’s clearly a simple pattern underlying the numbers, and so this would imply (not necessarily, but usually) that there’s simple code that would generate them.

      This is the case in this instance.

      In general, spend a some time thinking about a problem – do not give up and hard code things, when it looks like a simple algorithm may be present – in general, it’s a poor coding pattern to learn.

      In this specific example, hard coding 0,0 doesn’t even buy you anything. It doesn’t simplify the problem at all, or take care of an anomalous starting case – it just defers the start of the algorithm one step. Hardcode either the whole thing (which is clearly not what you need) or none of it at all.

      In this case, I’d suggest you read my hint again, and try work forward from there.
      Try model in your head what would be the effects of the question I asked.

      If this is hard, change what I said in the code, and look at the effect on output, and use this to figure out analytically the results of the change, and then deduce the correct solution.

    • #43450
      Anonymous
      Inactive

      Yes I know hard coding is bad practice but this is probably just a simple college exercise.

      As for hardcoding the 0,0 value, this means you can initialise your counter variables at 0 and 1 respectively which solves the lot. I left out that part to be intentionally vague (hints) but you called my hand feral.

      You could use an if/else statement but thats almost overkill for one value.

    • #43451
      Anonymous
      Inactive

      My tip: move the "r = 0" assignment, and change the value. Might be making it a bit too obvious though

    • #43452
      Anonymous
      Inactive

      Ahh.. yes, disregard my advice.. thats much better

    • #43453
      Anonymous
      Inactive

      Yes I know hard coding is bad practice but this is probably just a simple college exercise.
      [/quote:c6eca0998c]

      If this is a simple college exercise, then surely the focus should be on good programming practice, rather than just getting it done?
      In which case the use of a bad solution is doubly wrong.

      As for hardcoding the 0,0 value, this means you can initialise your counter variables at 0 and 1 respectively which solves the lot. I left out that part to be intentionally vague (hints) but you called my hand feral.
      [/quote:c6eca0998c]

      I don’t agree with that statement.

      First off, I don’t really see how ‘initialising the counter variables at 0 and 1’ solves the problem. This would seem to imply changing the initialisation of the outer counter variable as well, which doesn’t make sense to me.

      Do you mean initialising the inner counter variable at 0 the first pass, and 1 the second pass? This only solves the problem for the first two passes – as I read it, what needs to happen to solve the problem (extrapolating from the pattern the OP provided) is to initialise the inner counter variable to the value of the outer counter variable each iteration.

      Maybe you deduced a different pattern from the original query, where it only had to be different for the first two passes? If so, then I’d disagree with your reading of the pattern, but I would see where you are coming from.

      You could use an if/else statement but thats almost overkill for one value.[/quote:c6eca0998c]
      I would not have considered using if/else statements here.

      Seeing as we’ve dissected the exercise anyway, to state it in code, all that needs to happen is "r = 0" (as opposed to ‘int r = 0’) needs to change to "r = l". (and you could remove a \n too, if you want to be pedantic)
      No statement moving necessary, again, as far as I can tell.
      This is what I was getting at in my initial response.

      Hopefully jinkazama99 will learn more from the resulting discussion than would have been learned from figuring this out on their own…

    • #43454
      Anonymous
      Inactive

      If you hard code to print 0,0 before the for/while loops and set the values they are initialised at in the loops to 0 and 1 it solves it if the only anomaly is 0,0.

      But yes I did misread the pattern to begin with and yes you are right. Apologies feral, my bad.

    • #43455
      Anonymous
      Inactive

      If you hard code to print 0,0 before the for/while loops and set the values they are initialised at in the loops to 0 and 1 it solves it if the only anomaly is 0,0.

      But yes I did misread the pattern to begin with and yes you are right. Apologies feral, my bad.
      [/quote:e088d5d0b1]

      No apologies necessary. I misread it when I looked at it first too, got as far as making a post saying ‘eh, it looks fine’ before spotting it said "1,1" as opposed to "1,0", and had to quickly edit :P

    • #43456
      Anonymous
      Inactive

      No statement moving necessary, again, as far as I can tell. [/quote:671989ed2a]

      You’re correct, I too misread the pattern. I blame early mornings, late nights, and lack of coffee

    • #43459
      Anonymous
      Inactive

      ok to avoid any confusion i’ll type out the full pattern:

      For set 0: 0,0
      ————-0,1
      ————-0,2
      ————-0,3
      ————-0,4
      ————-0,5
      ————-0,6

      For set 1: 1,1
      ————-1,2
      ————-1,3
      ————-1,4
      ————-1,5
      ————-1,6

      For set 2: 2,2
      ————-2,3
      ————-2,4
      ————-2,5
      ————-2,6

      For set 3: 3,3
      ————-3,4
      ————-3,5
      ————-3,6

      For set 4: 4,4
      ————-4,5
      ————-4,6

      For set 5: 5,6
      ————-6,6

      For set 6: 6,6

      And yea, i need to print out all the sets :(

    • #43460
      Anonymous
      Inactive

      What I said will do this for you – the answer is literally spelled out there – but you might get more out of it if you read my hint first, and think about it, and then read each of the other posts!

      ok to avoid any confusion i’ll type out the full pattern:

      For set 0: 0,0
      ————-0,1
      ————-0,2
      ————-0,3
      ————-0,4
      ————-0,5
      ————-0,6

      For set 1: 1,1
      ————-1,2
      ————-1,3
      ————-1,4
      ————-1,5
      ————-1,6

      For set 2: 2,2
      ————-2,3
      ————-2,4
      ————-2,5
      ————-2,6

      For set 3: 3,3
      ————-3,4
      ————-3,5
      ————-3,6

      For set 4: 4,4
      ————-4,5
      ————-4,6

      For set 5: 5,6
      ————-6,6

      For set 6: 6,6

      And yea, i need to print out all the sets :([/quote:6a89d8dbb1]

    • #43464
      Anonymous
      Inactive

      I found out the solution already!!

      [code:1:80b9da6748]int main()
      {
      int l = 0;
      int r = 0;

      for (l = 0; l<7; l++){
      for(r = 0; r<7; r++)
      if(r >= l)

      printf("\n%d,%d\n",l,r);

      }

      }[/code:1:80b9da6748]

      I would not have considered using if/else statements here.
      [/quote:80b9da6748]
      Really? i mean i’m pretty sure this situation doesnt have a unique solution but how would you do it feral?????

    • #43465
      Anonymous
      Inactive

      I think feral’s way is this:

      [code:1:1f43752770]int main()
      {
      int l = 0;
      int r = 0;

      for (l = 0; l<7; l++){
      for(r = l; r<7; r++){
      printf("\n%d,%d\n",l,r);
      }
      }
      }[/code:1:1f43752770]

      No if-statement necessary

    • #43466
      Anonymous
      Inactive

      @ kentaree:

      OMG…..hey can you do me a favour by slap me at the face and smash it through a window? that’s exactly how i feel right now…

      i guess i still have a long way ahead of me…thanks a million :D

      @feral:

      sorry i failed you, but i will try my best from now on :D

    • #43469
      Anonymous
      Inactive

      @ kentaree:

      OMG…..hey can you do me a favour by slap me at the face and smash it through a window? that’s exactly how i feel right now…

      i guess i still have a long way ahead of me…thanks a million :D

      @feral:

      sorry i failed you, but i will try my best from now on :D[/quote:cb33f5e883]

      DO OR DO NOT: THERE IS –
      nah.

      Don’t be silly, it’s all a learning experience. :)
      As long as you’re learning stuff, you aren’t failing!

      Like, your way works, and you got there yourself, so you learned along the way. The rate at which you’re learning is much more important than what you know right now (and I believe that’s almost always the case!)
      dk/dt ftw

      Programming can take a long time to get the hang of – just gotta keep practicing on stuff like this as you build fluency – and not be deterred by the early parts of the learning curve which turn a lot of people off.

      What Kentaree posted is what I’d have written.

      You’d have achieved the same output if you just changed the line in the code you first posted:
      r = 0;
      to
      r = l;

      But the final version is better stylistically.

      The final version Kentaree posted, while no more correct in terms of output, than yours, is also more efficient, in terms of instructions executed.

      Can you see why?

      If not, it’d be worth your while thinking about it, or stepping through it on paper, or in a debugger.

      There’s a bit of a programming maxim from the unix world, that popped into my head looking at the different solutions:

      Make it work
      Make it good
      Make it fast

      Meaning, first make the code do the thing you intended – which yours does.

      Then, make it good – high quality, readable, maintainable. Your second version is probably better stylistically than your first, as it uses a more common pattern (for loop nested in a for loop) as opposed to a less common one (while loop, essentially functioning as a for loop, nested in a for loop).

      Finally, what Kentaree posted, works, is good – in that it’s easy to read – and is fast, in that it uses less instructions than having the if statement in there, like you did. (Again, if you don’t see why, it’s well worth your while establishing this for yourself).

      I think the maxim is mainly intended to stop people making things fast before they’ve made it work, or good, but I thought I’d mention it as an interesting way of looking at the different characteristics of the solutions, to this small example problem.

    • #43496
      Anonymous
      Inactive

      @feral

      Thanks for the encouraging words, appreciate it.

      I think i know why kentaree’s code is better, because the code has less line(ie no need for the if statement in this case), thus making the compiling process faster, it might not be obvious now but i’m sure if i’m gonna write a long code, i’ll need to be careful and cut-out-the-crap :)

      ok anyway i’m starting to take a look at array now and there’s a small bit tat i dun really get:

      [code:1:832e67f2d3]int main()
      {
      int x;

      int Array[5];

      for(x = 0; x<5; x++){
      Array[x] = x + 5;
      printf("\nNumber %d’s element is %d\n",x,Array[x]);
      }
      }[/code:1:832e67f2d3]

      See this part:

      [code:1:832e67f2d3]
      for(x = 0; x<5; x++){
      Array[x] = x + 5;[/code:1:832e67f2d3]

      The "Array[x]" means the element of the array right, n since x starts at "0" in the for loop, the first element would be seen as "0". wat i dont quite get is the fact that compiler wont complain the Array[x] statement?? i mean i’ve only declared "x" and "Array[5]", n the compiler automatically recognize Array[x]??

    • #43497
      Anonymous
      Inactive

      Ok.. here is your code with line numbers

      [code:1:b90d5733a4]
      1 int main()
      2 {
      3 int x;
      4
      5 int Array[5];
      6
      7 for(x = 0; x<5; x++){
      8 Array[x] = x + 5;
      9 printf("\nNumber %d’s element is %d\n",x,Array[x]);
      10 }
      11 }
      [/code:1:b90d5733a4]

      x is what I would call the Counter variable.
      On line 7 it decides how many times the loop should run

      [code:1:b90d5733a4]x = 0;[/code:1:b90d5733a4]
      means start the counter at 0

      [code:1:b90d5733a4]x < 5;[/code:1:b90d5733a4]
      this is the expression that must be true for the loop to continue, in this case less then 5. It cannot be equal to five ..it must be less then.

      [code:1:b90d5733a4]x++[/code:1:b90d5733a4]
      add 1 to x each loop .. this means x will eventually reach 5 meaning that x<5 will be false and the loop will stop.

      All this means the loop will run five times with x going from 0 to 4. The first slot or element in EVERY array is Zero. So a three slot array would be MyArray[0].MyArray[1],MyArray[2].

      For your example it would be Array[0],Array[0],Array[1],Array[2],Array[3],Array[4],

      And as x changes from 0 to 4 that means each slot/element gets filled.

    • #43498
      Anonymous
      Inactive

      yea i got it now, the "x" is like a"element counter" thing, thanks barry
      :D

    • #43499
      Anonymous
      Inactive

      just a nooby question:[code:1:4d985ffbb6]#include<stdio.h>
      #include<stdlib.h>

      int main()
      {
      int x;
      int Array[6];
      int Index = -1;

      for(x = 0; x < 6; x++)
      Array[x] = x * 3;
      do{
      printf("\nEnter a valid index(0-5):");
      scanf("%d",&Index);
      }while(Index < 0 || Index > 5);

      printf("\nIndex %d holds the number %d\n",Index,Array[Index]);
      }[/code:1:4d985ffbb6]

      why exactly does the author makes Index = -1???

    • #43500
      Anonymous
      Inactive

      @feral

      Thanks for the encouraging words, appreciate it.

      I think i know why kentaree’s code is better, because the code has less line(ie no need for the if statement in this case), thus making the compiling process faster, it might not be obvious now but i’m sure if i’m gonna write a long code, i’ll need to be careful and cut-out-the-crap :)
      [/quote:d3c6a8395d]

      Well, it’s not so much because it’s shorter, in terms of lines of code in the editor. I wouldn’t mind much if the code takes up more space on the screen, if this makes the code easier to read, and easier to debug.

      I was talking more from an efficiency point of view, and Kentarees code is more efficient. It will run faster.

      For example, imagine that instead of ‘7’ you were going up to ‘1000’?
      The last time the outer loop executes in the code with the ‘if’ statement, there are 1000 more evaluations of an ‘if’ statement than in Kentaree’s code.
      About half way through, there are about 500 more evaluations of an ‘if’ statement than in Kentaree’s code.

      If you decide to go as far as ‘1001’, rather than just ‘1000’, you add an extra 1001 evaluations of the if statement! ‘1002’ adds an extra ‘1002’ evaluations on top of ‘1001’. ‘1003’ an extra ‘1003’ evaluations on top of ‘1002’, and so on.

      Going as far as 1003 has an extra (1001 + 1002 + 1001 = 3006) evaluations of that if, over just going as far as 1000.

      Do you see what’s going on here? The number of times that if statement is executed is getting large!
      In other words – it doesn’t scale well. Kentaree’s code, of course, takes (nonlinearly) more time to execute for the bigger numbers – but the number of statements to be executed doesn’t explode all over the place, in quite as dramatic fashion.
      And that’s why it’s a bit better, from an efficiency point of view.

      Don’t take my word for it – sometime, when you’ve got a little time, instead of printing out the numbers, count how many times that ‘if’ statement would have got executed (put a little counter variable that’s incremented, just in front of the ‘if’) and run both programs for differing numbers of iteration.

      Of course, you’ve to be careful, as sometimes the compiler will optimise out things that are surprising, and make even code the looks less efficient run, but when your learning, it’s good to think about these things – while simultaneously remembering that in the real world, making software work, and making it good generally comes before making it fast.

    • #43501
      Anonymous
      Inactive

      just a nooby question:[code:1:032699967a]#include<stdio.h>
      #include<stdlib.h>

      int main()
      {
      int x;
      int Array[6];
      int Index = -1;

      for(x = 0; x < 6; x++)
      Array[x] = x * 3;
      do{
      printf("\nEnter a valid index(0-5):");
      scanf("%d",&Index);
      }while(Index < 0 || Index > 5);

      printf("\nIndex %d holds the number %d\n",Index,Array[Index]);
      }[/code:1:032699967a]

      why exactly does the author makes Index = -1???[/quote:032699967a]

      There’s no particular reason, actually. Any value would have done, there, because before anything else happens, scanf reads a value into the int.

      It’s probably good programming to initialise your variables to something though, in a language that doesn’t initialise them for you like C, to help in debugging – stops you making a mistake later, and assuming somethings initialised when its not.

      It might be worth noting that there is a bug in this code, or at least that it’s not very robust, in that the return value of scanf is not checked before it is used.
      Scanf does not remove the data from the buffer if the read fails (for example, in this case, if it looks for a signed decimal int and can’t find one), so this program will loop infinitely if you enter something like A or something that isn’t a decimal int.

    • #43508
      Anonymous
      Inactive

      It’s probably good programming to initialise your variables to something though, in a language that doesn’t initialise them for you like C, to help in debugging – stops you making a mistake later, and assuming somethings initialised when its not.
      [/quote:5abd5751e4]
      Well, i’ve always initialize my variables to ‘0’,i had the Index initialized as ‘-1’because i was just copying the book.

      Anyway, i’m starting to do enum now n i’m troubled by it, here’s the bit i dont get

      [code:1:5abd5751e4]int main()
      {
      int i = 0;
      enum{

      MAX_LEN = 5,
      LETTERX = ‘X’,
      NEWLINE = ‘\N’
      };

      for (i = 0; i < MAX_LEN; i++)
      printf("\n%c\n",LETTERX);
      }[/code:1:5abd5751e4]
      I’ll get to the point straight away,this code works, n i just wonder how does the enum knows the variable type of these variables:
      [MAX_LEN,LETTERX ,NEWLINE]??

      And for the variable "i" used in the ForLoop, why wont it works when i declare and initialize it within the enum function :shock: ??

    • #43510
      Anonymous
      Inactive

      Ok that does look confusing. When you say it works what is the output? ‘X’ five times? What do you think an emum is helping with for LETTERX = ‘X’, NEWLINE = ‘\N’ ?

      Anyway let me say what I think I know about C enums. All values in an enum are ints and an enum is used to just declaring names on them. If you specifically give a name an int value (like MAX_LEN = 5) then the value of the next name in the sequence will be 6 if not specified by assignment.

      e.g
      enum someNumberNames{five=5,six,seven,ten=10,eleven,twelve};

      Old chestnut:
      [code:1:0717fe5948]

      #include <stdio.h>
      int main()
      {
      enum Days{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};

      Days TheDay; //Create an instance name for enum type
      int j = 0;
      printf("Please enter the day of the week (0 to 6)\n");
      scanf("%d",&j);
      TheDay = Days(j);

      //Note Sunday is not in quotes, it is not a string / char sequence it is in effect an name for the int 0.
      if(TheDay == Sunday || TheDay == Saturday)
      printf("Hurray it is the weekend\n");
      else
      printf("Curses still at work\n");

      return 0;
      }
      [/code:1:0717fe5948]

    • #43538
      Anonymous
      Inactive

      Hello, i have a simple question, i’m studying file I/0 now, but the book i got doesnt cover anything on this topic, any1 has a good website where i can actually study, do some exercises and get familiar with it?? thanks a milllion:)

    • #43539
      Anonymous
      Inactive

      http://www.cplusplus.com have quiet good tutorials on most things.

    • #43540
      Anonymous
      Inactive

      Here is another website
      http://www.cprogramming.com/tutorial.html#c++tutorial

      Here is the direct link to file i/o
      http://www.cprogramming.com/tutorial/lesson10.html

      Yes the tutorials are c++ specific .. the site carries both c and c++ versions

    • #43541
      Anonymous
      Inactive

      thanks barry and omen :D

      anyway i’m starting to look at the codes and i’ll try to explain/or ask my questions through the comments

      [code:1:3c493f0b7f]
      //This program opens a file

      #include<stdio.h>
      #include<stdlib.h>
      #define IN_FILE_NAME "mydata.txt"

      int main()
      {
      FILE *fpIn;// is the FILE like a variable data type??
      FILE *fpOut = 0;
      int ch = 0, i = 0;;

      if((fpIn = fopen(IN_FILE_NAME, "r"))== NULL)//check if "IN_FILE_NAME"(the file i wanna open) exist or not
      {
      fprintf(stderr,"Error\n");//whats the point of using fprintf? i noticed that if i put in stdin
      //instead of stderr, i wont see the word "error"??
      }
      }[/code:1:3c493f0b7f]

      The codes above isnt the full code, i just wanna go through the thing step by step, easier to understand for me:D

    • #43542
      Anonymous
      Inactive

      i need help again…

      [code:1:6d9d9de6a6]#include<stdio.h>
      #include<stdlib.h>

      int main()
      {
      FILE *read;
      char name[10];
      char hobby[15];

      read = fopen("hobbies.dat","r");
      if(read == NULL)
      printf("\nCant open file\n");
      else
      printf("\nName\tHobby\n\n");
      fscanf(read, "%s%s",name,hobby);

      while(!feof(read)){
      printf("\n%s\t%s\n",name,hobby);
      }
      }[/code:1:6d9d9de6a6]

      First i’m using microsoft’s visual c++, and the result i’m supposed to get is like this:

      Name———Hobby

      Michael——-football
      Michelle——badminton
      Sheila——–basketball

      the"—–" is the space between those words
      ‘m pretty sure i created the file hobbies.dat already….

    • #43545
      Anonymous
      Inactive

      i think i got the problems above fixed already:)

      anyway i just came across this thing called fprintf();

      according to my knowledge,fprintf(); works like:

      fprintf(FILE POINTER,"CONVERSION SPECIFIER",VARIABLES);

      and this function is used to write datas to a file(say notepad), so in another word, this function,unlike printf();, wont print out anything in the compiler’s command screen,right?

      but i got this exercise where i have to prompt a user to enter a name, the catch is i have to use fprintf(); instead of printf();
      :shock:

      HELLLLLLLLLLLLLLLLLLLP!!!!!!!!!!!!!

    • #43547
      Anonymous
      Inactive

      It’s actually quite easy and logical once you know, maybe try and do a search on special file streams in C++

    • #43548
      Anonymous
      Inactive

      aha
      lo and behold: stderr!!!!

      ^^

      *off to program now*

    • #43549
      Anonymous
      Inactive

      Ok, since you found that, I might aswell tell you, there’s streams for stdin and stdout too. In this case, stdout is the best choice, as stderr should really only be used for error messages.

    • #43550
      Anonymous
      Inactive

      @kentaree, thanks :)

      anyway, problem as usual :(

      [code:1:bd95192be5]#include<stdio.h>
      #include<stdlib.h>

      int main()
      {
      FILE *input;
      FILE *output;
      char Inname[99];
      char Outname[99];
      char nums[13]={1.1,2,3,4.7,5,6,7,8,9.2,10,11,12,13};
      int a = 0;
      int ch = 0;

      //Initializing the input file’s name
      fprintf(stdout,"Please input the input file’s name(include extension):");
      fscanf(stdin,"%s",Inname);
      input = fopen(Inname,"w");

      //Reads in floats from the input file
      for(a = 0; a <= 12;a++){
      fprintf(input,"%s",nums[a]);
      }

      //Initializing the output file’s name
      fprintf(stdout,"Please input the output file’s name(include extension):");
      fscanf(stdin,"%s",Outname);
      output = fopen(Outname,"w");

      }[/code:1:bd95192be5]

      Here’s the real problem:
      [code:1:bd95192be5]//Reads in floats from the input file
      for(a = 0; a <= 12;a++){
      fprintf(input,"%s",nums[a]);
      }
      [/code:1:bd95192be5]
      I was trying to use fprintf() to write in all the datas(1.1,2…13) to the input file. there was no error during compiling,after i put in the input file’s name, this thing pops out saying would i like to use a debugger???, i click yes but it doesnt really solve the problem…help, please?oh and the file i created is .txt file.

    • #43551
      Anonymous
      Inactive

      My thoughts are that you are telling it you want to write a string to the file, when you’re really writing a char. This means that it starts writing the the character, and keeps going till it finds a null character, which might or might not exist in program memory.
      Get it to write a char, and it’ll probably work

    • #43553
      Anonymous
      Inactive

      should the array not be a char *

      ie

      const char * nums[13]={"1.1","2","3","4.7","5","6","7","8","9.2","10","11","12","13"};

    • #43555
      Anonymous
      Inactive

      @ kcbouli – can you actually do that? i mean "const char *nums[13]", i get a compiler error if i put that in, it says :"cannot convert from ‘int’ to ‘const char *’"so i dunno really, anyway thanks for helping :)

      @ kentaree

      yea thanks man i get it to do wat i wanted it to do earlier on, n here’s my new problem:

      [code:1:44d988f854]
      #include<stdio.h>
      #include<stdlib.h>
      #include<math.h>

      int main()
      {
      FILE *input;
      FILE *output;
      char Inname[99];
      char Outname[99];
      char nums[]={’1.1′,’2′,’3′,’4.7′,’5′,’6′,’7′,’8′,’9.2′,’10’,’11’,’12’,’13’,”};
      int a = 0;
      int ch = 0;

      //Initializing the input file’s name
      fprintf(stdout,"Please input the input file’s name(include extension):");
      fscanf(stdin,"%s",Inname);
      input = fopen(Inname,"r");

      //Initializing the output file’s name
      fprintf(stdout,"Please input the output file’s name(include extension):");
      fscanf(stdin,"%s",Outname);
      output = fopen(Outname,"w");

      //Reads in floats from the input file
      while(!feof(input)){

      ch = getc(input);
      if(ch!= EOF)
      putc(ch,output);

      }
      }[/code:1:44d988f854]
      Ok, now i’m sure all of you know wat my code does right, so i’ll just skip to the real part that i’m stuck at. I need to write the data from my input file to my output file in this form:

      1 + 2 + 3 + 4 +…..+10 = %d(answer), with the 11,12 and 13 chopped off in the end.
      So…my first guess, i’ll need to use fprintf to write the datas from input file to output file, and alter the shape/form using fprintf.

      My idea:[code:1:44d988f854]
      for(a = 0; a <= 10; a++){
      fprintf(output,"%c + %c = %c ",nums[a],nums[a+1],nums[a]+nums[a+1]);
      }
      [/code:1:44d988f854]
      Well thats probably the best i can come up with really, n i know it wont really work…unless i got some pro’s advice from the folks here!!erm… is there a math.h function that can sums all those numbers in the input file first?i guess not in c right?anyway back to the problem…

      :D So…yes? no? maybe?

    • #43556
      Anonymous
      Inactive

      yes!!
      i came up with a way to add up the numbers in an array!!

      [code:1:f1cee2059f]for(a = 0; a<=13;a++){
      total += nums[a];
      printf("%.2f\n",total);
      }[/code:1:f1cee2059f] :D still dunno how to print out the way i want it but i’m 1 step closer again!!!
      *off to program*

    • #43557
      Anonymous
      Inactive

      AHA!!
      I got it!!
      well…99% of it

      [code:1:73fa946044]
      #include<stdio.h>
      #include<stdlib.h>

      int main()
      {
      FILE *input;
      FILE *output;
      char Inname[99];
      char Outname[99];
      float nums[13]={1.1,2,3,4.7,5,6,7,8,9.2,10,11,12,13};
      int a = 0;
      int b = 0;
      int ch = 0;
      float total = 0;

      //Initializing the input file’s name
      fprintf(stdout,"Please input the input file’s name(include extension):");
      fscanf(stdin,"%s",&Inname);
      input = fopen(Inname,"r");

      //Initializing the output file’s name
      fprintf(stdout,"Please input the output file’s name(include extension):");
      fscanf(stdin,"%s",&Outname);
      output = fopen(Outname,"w");

      for(b = 0; b < 10; b++){
      fprintf(output,"%.1f+",nums[b]);
      }

      //Adding numbers in array
      for(a = 0; a<=9; a++){
      total += nums[a];
      }
      fprintf(output,"=%.2f\n",total);
      }[/code:1:73fa946044]
      A TINY problem, i got it to print 1.1+2+….10+=56.00, how exactly would i get rid of the "+" before the =56.00??

    • #43558
      Anonymous
      Inactive

      Aha, lo and behold, just use the almighty if statement!!
      Thank you people, thank you!!

      FULL CODE
      [code:1:c63c26bc19]
      #include<stdio.h>
      #include<stdlib.h>
      #define MAX_NO 9

      int main()
      {
      FILE *input;
      FILE *output;
      char Inname[99];
      char Outname[99];
      float nums[13]={1.1,2,3,4.7,5,6,7,8,9.2,10,11,12,13};
      int a = 0;
      int b = 0;
      int ch = 0;
      float total = 0;

      //Initializing the input file’s name
      fprintf(stdout,"Please input the input file’s name(include extension):");
      fscanf(stdin,"%s",&Inname);
      input = fopen(Inname,"r");

      //Initializing the output file’s name
      fprintf(stdout,"Please input the output file’s name(include extension):");
      fscanf(stdin,"%s",&Outname);
      output = fopen(Outname,"w");

      for(b = 0; b < MAX_NO; b++){
      fprintf(output,"%.1f+",nums[b]);
      }
      if(nums[9] == 10)
      fprintf(output,"%.1f",nums[9]);

      //adding numbers in array
      for(a = 0; a<=9; a++){
      total += nums[a];
      }
      fprintf(output,"=%.2f\n",total);
      }
      [/code:1:c63c26bc19]
      Now alls left is tidy up the code so it looks nice and readable!! 8)

    • #43716
      Anonymous
      Inactive

      [code:1:f92237cbc1]int main()
      {
      char *name;

      name = (char *)malloc(50 * sizeof(char));
      if(name != NULL){
      printf("\nEnter ur name:\n");
      gets(name);

      printf("\nHi %s\n",name);
      }//end if
      }//end main[/code:1:f92237cbc1]

      ok the book says the malloc will only allow 50 characters name to be stored,so i changed the 50 – 1, which means that only 1 character string can be stored right? i put in a long name and nothing happens as it still let me do it and print out the name in the cmd screen?? so wats the point of allocating the memory in the 1st pace??i’m using visual studio btw…

    • #43719
      Anonymous
      Inactive

      What happened there is that when printing out a string, it reads every character up until it finds the null character. gets() doesn’t check the bounds of the memory you’re using, so if you go over 50 chars, it might still work but you’re modifying memory that you haven’t specifically allocated for the task, so you’re probably modifying memory that’s used for something else which can cause big problems.

    • #43751
      Anonymous
      Inactive

      @ kentaree- thanks for the infos :)

      anyway i just came across calloc
      and i know calloc takes 2 arguments, the 1st argument is occupy contigous memory segments, while the 2nd argument takes in the data type.

      let’s say[code:1:3388d456ea]
      int *numbers;

      numbers = (int *)calloc(10,sizeof(int));[/code:1:3388d456ea]

      is it the same as i tell the compiler i need 10 empty boxes, and the type of the boxes have to be metal??
      i’m sorry if i caused confusion with my last statement.

    • #43754
      Anonymous
      Inactive

      calloc is essentially the same as malloc, but it does the multiplication for you. C++ doesn’t keep runtime type data, so you can use the memory for any kind of data even if you pass in sizeof(int).

    • #43769
      Anonymous
      Inactive

      Video tutorials for C++.

      http://www.3dbuzz.com/xcart/product.php?productid=30

      Don’t know how effective watching someone type would be, but I suppose there are plenty of ways to learn…

      B.

    • #43956
      Anonymous
      Inactive

      help!!!
      ok have some weird problems here
      [code:1:41f85ceb38]
      #include<stdio.h>
      #include<stdlib.h>
      #define SIZE 15

      float *initFloatArray(float a[], int noEle, float c);
      float printFloatArray(float d[], int e, float f);
      int main()
      {
      float num[SIZE];
      int *p_len;
      int x;

      printf("\nBefore initFloatArray\n");
      num[0] = num[SIZE-1] = num[SIZE/2] = 9.99;
      for(x=0; x<SIZE; x++){
      printf("\nnum[%d] = %.2f\n",x,num[x]);
      }
      initFloatArray(num, SIZE, 1.23);
      printf("\nAfter initFloatArray\n");
      for(x=0; x<SIZE; x++){
      printf("\nnum[%d] = %.2f\n",x,num[x]);
      }
      *p_len = &(initFloatArray(num, SIZE, 1.23));

      }//end main

      float *initFloatArray(float a[], int noEle, float c)
      {
      int x;
      for(x=0; x<SIZE; x++){
      a[x] = c;
      }
      return &c;
      }[/code:1:41f85ceb38]

      can some one tell me whats wrong with this line?
      [code:1:41f85ceb38]
      *p_len = &(initFloatArray(num, SIZE, 1.23));[/code:1:41f85ceb38]

      i have to assign the return value of the initFloatArray to the p_len, n i’m pretty sure i have it right(at least on the right track)…oh n the compilers complaining bout the "&" requires 1-value…??

    • #43957
      Anonymous
      Inactive

      [code:1:864240954e]int *p_len;[/code:1:864240954e]

      Above should be a pointer to a float if your going to return the address of c in initFloatArray

      [code:1:864240954e]*p_len = &(initFloatArray(num, SIZE, 1.23));[/code:1:864240954e]

      p_len is already a pointer and initFloatArray is already returning an address:
      Can you not just go
      p_len =initFloatArray(num, SIZE, 1.23);

    • #43958
      Anonymous
      Inactive

      aha!! that works thanks a million!!

      but i have a lil question

      p_len =initFloatArray(num, SIZE, 1.23);

      shouldn’t the * sign be included in front of p_len??

    • #43963
      Anonymous
      Inactive

      The asterix is called the indirection operator.
      You only use it when you want the value inside the variable the pointer points at.

      When declaring/assigning pointers you leave out the asterix as you are assigning the pointers contents to be the memory address of the variable it is pointing at.

      When you use the asterix it redirects from the pointer to the variable and grabs the value inside.

      A pointer POINTS somewhere…

    • #43993
      Anonymous
      Inactive

      ok small question

      [code:1:226887a5a4]
      #include<stdio.h>
      #include<stdlib.h>
      #define SIZE 15

      int *initFloatArray(float a[], int b, float c);

      int main()
      {
      float num[SIZE];
      int x;
      float y = 1.23;
      int *p_len;

      num[0] = num[SIZE-1] = num[SIZE/2] = 9.99;

      printf("\nArray contents BEFORE call of initFloatArray()\n");
      for(x=0; x<SIZE; x++){
      printf("\nnum[%d]=%.2f\n",x,num[x]);
      }

      initFloatArray(num,SIZE,y);

      printf("\nArray contents AFTER call of initFloatArray()\n");
      for(x=0; x<SIZE; x++){
      printf("\nnum[%d]=%.2f\n",x,num[x]);
      }

      p_len = initFloatArray(num,SIZE,y);//assign p_len to the return value
      //of the function initFloatArray()

      printf("\nThe number of initialised elements is : %d\n",*p_len);

      }//end main

      //define float *initFloatArray()

      int *initFloatArray(float a[], int b, float c)
      {
      int x;
      for(x=0; x<b; x++){
      a[x] = c;
      }
      return &b;
      }
      [/code:1:226887a5a4]

      ok i’m sure i’m using array indexing to assign value to teh array in the
      initFloatArray(), but how can i change it to assign value to the array’s element using pointer?? This is an assignment, so pleeeeease help out here guys :o

      Apparently i only need to change 1 line within the initFloatArray()…

    • #44004
      Anonymous
      Inactive

      Because it’s an assignment I don’t want to give the answer straight out, but do a google for incrementing a pointer, and that should give you some clues.

Viewing 195 reply threads
  • The forum ‘Programming’ is closed to new topics and replies.