jump to navigation

C++ September 25, 2006

Posted by metalsam in General, c / c++.
4 comments

I’ve been tinkering in C++ again. I was stuck for ideas on something to program, so G set me the task of writing a program that would swap two variables. Not too tricky, but it took me a while to get the logic right. Here it is :

// c++ that asks for two variables and then swaps them around

#include <iostream>
using namespace std;

//function to define two variables via user input

int x;
int y;

void variabledefine ()
{
cout << “Please define integer variables X and Y” << endl;
cout << “Define X: ” << endl;
cin >> x;

cout << “Define Y: ” << endl;
cin >> y;

cout << “You have defined X as: ” << x << endl << “and Y as: ” << y << endl;

}

// Now an attempt to switch the variables.
//

int variableswitch (int a, int b)
{
cout << “This function will attempt to switch the values of variables X and Y.” << endl;

a = x;
b = y;
x = b;
y = a;

}

int main ()
{
variabledefine ();
x, y = variableswitch (x, y);

cout << “X is now: ” << x << endl;
cout << “Y is now: ” << y << endl;

return 0;
}
Woop woop !

c programming April 9, 2006

Posted by metalsam in Linux, c / c++.
5 comments

So I started to learn c. C is evil, very very evil. But im still earning it anyway, figured I should try and make some maths programs to feed my university homework into =)

With some help from Gerald I made a program that multiplied two numbers together, and then using that, and some stuff off the net, I made one that asks you for two numbers, and then multiplies them together =)

This is it:

  /* Sams 1337 number timesing program */
        /* Take asks user fpr two numbers and multiplies them together */

#include <stdio.h>

int main()

{
        /* Asks user for a number */
        printf("\n enter an integre number….\n");

/* Defines variables – the two inputs and the output */

float     number1;
float     number2;
int     answer;

        /* Prompts user to input a number */
        scanf("%f", &number1);

        /* Asks user for a second number */
        printf("\n and another one….\n");

        /* Prompts user for as econd number */
        scanf("%f", &number2);

        /* Tells user what is happening to the numbers */
        printf("\n the two are multiplied together….\n");

        /* Multiplies the two numbers together */
        answer = number1 * number2;

        /* Prints the answer */
        printf("%4d\n", answer);

/* Tells system everything is ok */
return 0;
}

Notes:

  •  /* */ contains comments for someone going through the code. Isnt actually used when compiled.
  • after every argument ( i think this is the correct term, ie every variable, sum, etc ) you must have a ;
  • # include <stdio> is the libbrary that tells the computer how to interpret scanf printf
  • { } contains the function.
  • This will only work for linux (  think :S)
  • I still have a lot to learn !

Technorati: