Author Topic: C/C++ Thread  (Read 1775 times)

0 Members and 1 Guest are viewing this topic.

Offline Aaruni Kaushik

  • The Creator
  • Administrator
  • ******
  • Posts: 746
  • Gender: Male
    • View Profile
C/C++ Thread
« on: April 23, 2013, 07:25:26 am »
So you're willing to write your own code in C or C++, or simply compile someone else's code? This guide has been designed
to get you started.

References and Source for some of the content
FAQ: Compiling your first C or C++ programs - Ubuntu Forums
Welcome to FOSS Powered Wiki - FOSS Powered Wiki

Comments and correction of errors will really be appreciated.

1. Make sure the compiler is installed

Basically if you are starting, you are strongly recommended to use standard compilers, like The GNU C Compiler (gcc), LLVM,
Microsoft Visual C++, etc. Stay AWAY from antiquated compilers like Turbo C et al, with them you will NEVER learn proper
programming* and will develop really horrible practices. This thread will basically cover the GNU C Compiler.
Depending on your operating system, it depends on how to set up your GNU C Compiler. I will mainly focus on the popular
operating systems such as Linux and Windows.

Windows

In order to install MinGW, first of all download the executable and execute your downloaded executable in order to
facilitate the installation of MinGW. Download the installer from this site.
Make sure you install the packages for gcc and g++ in the installer.
Next make sure you set up the paths properly, this can be done by going to system properties (Properties of My Computer),
and set the environment variable PATH by adding the location of the compiler's path. Click on the spoiler to view:






Mac OS X

Mac OS X users need to install Xcode which you can either get from the App Store. Starting from Xcode 4.3, the Command Line

tools are not bundled by default. They can be installed by opening Xcode and going to Preferences --> Downloads -->

Components --> Command Line tools.

I'll suggest to use TextWrangler as your preferred
text editor.

Ubuntu

Make sure that the build-essential package is installed in the system.
You can install the build-essential package by running the terminal and passing the command.

Code: [Select]
sudo apt-get install build-essential
Alternatively you can use the Software Center or Synaptic Package Manager to search build-essential and install it.

OpenSUSE

Open YAST. Go to Software Management.
Change the Filter to 'Patterns' and select C/C++ Compiler and Tools.
Click Accept. And install.

Fedora

Go to terminal as root.
For running it as root, type

Code: [Select]
su
Then pass the command

Code: [Select]
yum groupinstall "Development Tools" "Legacy Software Development"
Arch Linux

The development packages for C/C++ Programming is already bundled in Arch Linux. However the package is: base-devel. You
can use the pacman package manager in case any package or library is missing.

Others

See here: Installing GCC - GNU Project - Free Software Foundation (FSF)

2(a). Write your first C Program

Kick open your IDE/text editor, make sure it is a plain text editor and not a binary editor like the Word Processors or
Wordpad in Windows. Only a plain text editor will do. Windows has Notepad, which can be used however Notepad++ or Crimson
Editor is recommended due to syntax highlighting and indention support.
Write the following code in it.

Code: [Select]
#include<stdio.h>
 
int main()
{
    printf("Hello, World!");
    return 0;

This is a very simple C program. You can save it as an ASCII text file, say myfirst.c. Make sure of the extension it should
be [dot]c, preferably lowecase c in *nix.

2(b). Write your first C++ Program
Similarly for C++ you can try the following code.

Code: [Select]
#include <iostream>

int main()
{
  std::cout << "Hello World!" << std::endl;
  return 0;

You can save the file in .cpp extension.

2(c). Compiling

For C
gcc is the C compiler
Obviously, the filaname saved with .c extension is the C source file which the compiler compiles. If you want to compile
several source files into a single executable, just list them sequentially delimited by a space.

You can compile a C program with the command in your terminal/Command Prompt.

Code: [Select]
gcc myfirst.c -o program.exe
You can replace myfield.c by whichever file you wish to compile.
The -o flag names the name of the executable created, program.exe in this case. If you don't pass that flag and just gcc

myfirst.c, then your executable will be a.out in *nix and a.exe in Windows.
Note: Linux users don't need to append .exe at all

For C++
Similarly you can compile a C++ source file by saving it as .cpp and compiling with command:

Code: [Select]
g++ myfirst.c -o program.exe
Executing
Execution can be performed by writing the name of the executable created in your Terminal/Command Prompt. Either
./programname in *nix or programname.exe in Windows.

Steps for Windows users:








Steps for Mac OS X users:





Steps for Linux users:



3. Useful Flags
Following are a few command line switches to enable some warnings and language features (check the man page for detailed
information):

-std=gnu99 (C only) This flag enforces the latest C standard (1999) i.e. C99, plus GNU Extensions (this should be
explicitely specified)
-ansi This flag checks ANSI compliance
-pedantic This flag issues warnings when strict ISO compatibility is NOT met.
-Wall This flag enables most warnings (very useful, highly recommended)
-Wextra enables more warnings (very useful)
-Wwrite-strings warns when you misuse plain old C string constants (aka. deprecated cast from const char* to char*) (very
useful, highly recommended)

I particularly recommend -Wall and -Wwrite-strings, to maximize warnings and common pitfalls. Also remember paranoid
programming is good for your code, so never try to ignore warnings.

4. Must Reads
Things to Avoid in C/C++ -- gets() , Part 1 - GIDNetwork
comp.lang.c Frequently Asked Questions
C++ FAQ

5. Some Common Questions Answered

C

Why C?

C is a standard. It is the programmers programming language. It is the standard programming language of GNU and BSD based
systems. The majority of these systems and the applications that run on them, is written in C. C was developed over thirty
years ago for writing operating systems and applications. It's small, extensible design has allowed it to evolve with the
computer industry. Because of it's age and popularity, C is a very well supported language. Many tools exist to make C
programming easier and these tools are often very mature and of a high standard. All the software we will use in this book
is written in C.
Reference: Why learn C?

C books
If you are willing to buy a printed book, it is strongly suggested to buy 'The C Programming Language by Kernighan and
Ritchie'
and 'Head First C'. Both are highly recommended. 'C Programming : A Modern Approach' is another
fantastic book but an Indian Print is not available and the international edition costs a fortune. These are not absolute
beginner guides though. If you are a total beginner, do consider a language like Python before jumping to C. Though if you
want to insist with C, go ahead with 'C for dummies'. Pretty much neophyte friendly as it gets. Keep away from books
with Non-Standard code, basically just flip through it and if you see void main() or conio.h in it, just keep it back in
the shelf.
For online resources on C check these links:
C Programming Language - Free computer books
The GNU C Programming Tutorial
ANSI C Programming: Part 1
C programming.com - Your Resource for C and C++ Programming
comp.lang.c Frequently Asked Questions

C++

Why C++?
C++ is an Object Oriented Programming Language which incorporates the execution speed of C along with OOPS development
model which makes it more suitable for large projects.

Can I learn C++ before C?
While you certainly can, however it is highly suggested to first learn sequential and procedural programming concepts in C
style, before jumping to the OOPS model of C++. C to C++ is a natural path of learning.

C++ books
There are many great books for C++, 'Thinking in C++' and 'The C++ Programming language' are pretty good books and
certainly worth learning. However there are many excellent online resources.
C++ Language Tutorial
Teach Yourself C++ in 21 Days
Bruce Eckel's MindView, Inc: Thinking in C++ 2nd Edition by
Bruce Eckel


Editors and IDEs

Editors which offer basic syntax highlighting and indention are recommended. In Windows Notepad++ is an excellent editor,
while in Linux you have gedit, kate as GUI editors, and vim, emacs as excellent text based editors.
It's advisable not to use IDEs in the beginning. Stay clear of Netbeans, Eclipse, Anjuta, Visual Studio, MonoDevelop, or
any such IDE. Of course, if you are arguing on that, you probably know better and can ignore this advice. One IDE which is
suggested is Geany which is basic enough and serves all purposes.


* - You can use them for your school/college, however know which bad practice you are using when you use such compilers and
don't depend on them.

Show content
Note: Information taken from here, with the permission of the author
« Last Edit: April 23, 2013, 07:28:22 am by Aaruni Kaushik »
HP Pavillion G6, Intel Core i5 3230M @ 2.6GHz, 4 GB RAM, 1 GB Radeon HD7670M 500 GB HDD, Linux Ubuntu 12.04.2 LTS

"Those who don't understand Unix are condemned to reinvent it, poorly." - Henry Spencer

"It is a miracle that curiosity survives formal education" - Albert Einstein

Is God willing to prevent evil, but not able? Then he is not omnipotent. ; Is he able, but not willing? Then he is malevolent. ; Is he both able and willing? Then whence cometh evil? ; Is he neither able nor willing? Then why call him God?

Me on FB, My Blog, Me on SteamMe on Twitter, About Me

Offline Anurag Jha

  • I am really an
  • Administrator
  • ******
  • Posts: 263
  • Gender: Male
    • View Profile
Re: C/C++ Thread
« Reply #1 on: July 05, 2013, 05:08:02 pm »
What is the difference between turbo c compiler and gcc. I know turbo C is old( very^100 old ) and gcc is fairly new, free, open source, multi-platform etc.. but we are being taught using turbo c in school. I would be good if you would add some differences in sintax, libraries.. etc 







- Me java guy, knows nothing about C++
Keep an open mind, but not so much that your mind falls out!!!

Useful :
Show content
Step 1 : Press ctrl + w
Step 2 : Dialouge box appears. Click options > OK
Step 3 : Go to start menu
Step 4 : control panel
Step 5 : click Keyboard
Step 5 : Open MS word
Step 6 : press ctrl + alt + m

Offline karan

  • Newbie
  • *
  • Posts: 6
    • View Profile
Re: C/C++ Thread
« Reply #2 on: July 05, 2013, 08:17:46 pm »
The main and basic difference is that GCC is compliant of the C99 standard; which is the worldwide standard for C language(and derivatives).
Turbo c++ being old doesn't support(it isn't actively developed any longer)  this standard and hence it's use is more or less limited to teaching c++ in school universities etc.

More info here: http://en.wikipedia.org/wiki/C99


Follow me on Twitter: https://twitter.com/wuodland

Offline Anurag Jha

  • I am really an
  • Administrator
  • ******
  • Posts: 263
  • Gender: Male
    • View Profile
Re: C/C++ Thread
« Reply #3 on: July 07, 2013, 12:45:15 pm »
That's helped me. Compiled my first c++ program already ( a very very simple cli calculator ) :rolleyes:
Keep an open mind, but not so much that your mind falls out!!!

Useful :
Show content
Step 1 : Press ctrl + w
Step 2 : Dialouge box appears. Click options > OK
Step 3 : Go to start menu
Step 4 : control panel
Step 5 : click Keyboard
Step 5 : Open MS word
Step 6 : press ctrl + alt + m

Offline Aaruni Kaushik

  • The Creator
  • Administrator
  • ******
  • Posts: 746
  • Gender: Male
    • View Profile
Re: C/C++ Thread
« Reply #4 on: August 10, 2013, 05:53:25 pm »
Can anyone tell me why this program only prints "<year> is not a leap year." ?

Code: [Select]
/*
Fourth problem
input -> num year
output -> if leap year -> true , else -> false (write proper interface)
conditions of leap year : divisible by 4 !by 100 but by 400
*/
#include<iostream>
using namespace std;
int main()
{
int year,limb1,limb10,limb40;
cout<<"Program to tell whether a given year is a leap year or not.\nPlease enter the year to be checked.\n\t";
cin>>year;
limb1=year%4;
if (limb1 == 0)
{
limb10 = year%100;
limb40 = year%400;
if (limb40 == 0)
{
if (limb10 > 0)
{
cout<<year<<" is a leap year.\n";
}
else if (limb10 == 0)
{
cout<<year<<" is not a leap year.\n";
}
}
else
{
cout<<year<<" is not a leap year.\n";
}
}
else
{
cout<<year<<" is not a leap year.\n";
}
return 0;
}
HP Pavillion G6, Intel Core i5 3230M @ 2.6GHz, 4 GB RAM, 1 GB Radeon HD7670M 500 GB HDD, Linux Ubuntu 12.04.2 LTS

"Those who don't understand Unix are condemned to reinvent it, poorly." - Henry Spencer

"It is a miracle that curiosity survives formal education" - Albert Einstein

Is God willing to prevent evil, but not able? Then he is not omnipotent. ; Is he able, but not willing? Then he is malevolent. ; Is he both able and willing? Then whence cometh evil? ; Is he neither able nor willing? Then why call him God?

Me on FB, My Blog, Me on SteamMe on Twitter, About Me

Offline Anurag Jha

  • I am really an
  • Administrator
  • ******
  • Posts: 263
  • Gender: Male
    • View Profile
Re: C/C++ Thread
« Reply #5 on: August 10, 2013, 07:18:50 pm »
Yes, its faulty logic...
Let us take the example of the year 800. It is a leap year, since it is divisible by 4, by 100 but also by 400;
First your program checks if the year is divisible by 4. true returned since 800 is divisible by 4.
Then it checks for divisibility by 400, which again is returned true. Then it checks for non divisibility by hundred.. which will return false for every number, since what ever is divisible by 400, is divisible by 100 tooo !!!
i.e you check if it is divisible by 400( which is true automatically means it is divisible by 100) then you check for non-divisibility by 100, which always returns false, hence your problem of only "not a leap year"

Will adds corrected code in some time..
Keep an open mind, but not so much that your mind falls out!!!

Useful :
Show content
Step 1 : Press ctrl + w
Step 2 : Dialouge box appears. Click options > OK
Step 3 : Go to start menu
Step 4 : control panel
Step 5 : click Keyboard
Step 5 : Open MS word
Step 6 : press ctrl + alt + m

Offline Anurag Jha

  • I am really an
  • Administrator
  • ******
  • Posts: 263
  • Gender: Male
    • View Profile
Re: C/C++ Thread
« Reply #6 on: August 10, 2013, 07:25:09 pm »
Code: [Select]
/*
Logical Debugging by Anurag Jha
Fourth problem
input -> num year
output -> if leap year -> true , else -> false (write proper interface)
conditions of leap year : divisible by 4 !by 100 but by 400
*/
#include<iostream>
using namespace std;
int main()
{
    int year,limb1,limb10,limb40;
    cout<<"Program to tell whether a given year is a leap year or not.\nPlease enter the year to be checked.\n\t";
    cin>>year;
    limb1=year%4;
    if (limb1 == 0)
    {
        limb10 = year%100;
        limb40 = year%400;
        if (limb10 == 0)
        {
            if (limb40 == 0)                 // This is where the change is done
            {
                cout<<year<<" is a leap year.\n";
            }
            else                             //also here and removed some line below
            {   
                cout<<year<<" is not a leap year\n";
            }   
       
           
        }
        else
        {
         cout<<year<<" is a leap year.\n"     //somehow I missed this else. Added this in a edit
         }
       
    }
    else
    {
        cout<<year<<" is not a leap year.\n";
    }
    return 0;
}

By the way, this program can be made much smaller. You want a small one ??
« Last Edit: August 11, 2013, 12:05:21 pm by Anurag Jha »
Keep an open mind, but not so much that your mind falls out!!!

Useful :
Show content
Step 1 : Press ctrl + w
Step 2 : Dialouge box appears. Click options > OK
Step 3 : Go to start menu
Step 4 : control panel
Step 5 : click Keyboard
Step 5 : Open MS word
Step 6 : press ctrl + alt + m

Offline Aaruni Kaushik

  • The Creator
  • Administrator
  • ******
  • Posts: 746
  • Gender: Male
    • View Profile
Re: C/C++ Thread
« Reply #7 on: August 10, 2013, 07:50:01 pm »
no thanks for a small program, thanks for the logic correction

--------

@Anurag, your program is giving logical errors too.
« Last Edit: August 10, 2013, 08:35:10 pm by Aaruni Kaushik »
HP Pavillion G6, Intel Core i5 3230M @ 2.6GHz, 4 GB RAM, 1 GB Radeon HD7670M 500 GB HDD, Linux Ubuntu 12.04.2 LTS

"Those who don't understand Unix are condemned to reinvent it, poorly." - Henry Spencer

"It is a miracle that curiosity survives formal education" - Albert Einstein

Is God willing to prevent evil, but not able? Then he is not omnipotent. ; Is he able, but not willing? Then he is malevolent. ; Is he both able and willing? Then whence cometh evil? ; Is he neither able nor willing? Then why call him God?

Me on FB, My Blog, Me on SteamMe on Twitter, About Me

Offline Anurag Jha

  • I am really an
  • Administrator
  • ******
  • Posts: 263
  • Gender: Male
    • View Profile
Re: C/C++ Thread
« Reply #8 on: August 11, 2013, 11:56:27 am »
I   Get no errors in my computer.. I must have not copied the code correctly here. Let me check


EDIT : corrected a missing else. Added to the code above
« Last Edit: August 11, 2013, 12:06:02 pm by Anurag Jha »
Keep an open mind, but not so much that your mind falls out!!!

Useful :
Show content
Step 1 : Press ctrl + w
Step 2 : Dialouge box appears. Click options > OK
Step 3 : Go to start menu
Step 4 : control panel
Step 5 : click Keyboard
Step 5 : Open MS word
Step 6 : press ctrl + alt + m

Offline Aaruni Kaushik

  • The Creator
  • Administrator
  • ******
  • Posts: 746
  • Gender: Male
    • View Profile
Re: C/C++ Thread
« Reply #9 on: August 11, 2013, 01:23:28 pm »
Yep, that was it. You missed an else clause.
« Last Edit: September 21, 2013, 07:38:51 am by Aaruni Kaushik »
HP Pavillion G6, Intel Core i5 3230M @ 2.6GHz, 4 GB RAM, 1 GB Radeon HD7670M 500 GB HDD, Linux Ubuntu 12.04.2 LTS

"Those who don't understand Unix are condemned to reinvent it, poorly." - Henry Spencer

"It is a miracle that curiosity survives formal education" - Albert Einstein

Is God willing to prevent evil, but not able? Then he is not omnipotent. ; Is he able, but not willing? Then he is malevolent. ; Is he both able and willing? Then whence cometh evil? ; Is he neither able nor willing? Then why call him God?

Me on FB, My Blog, Me on SteamMe on Twitter, About Me