DIGIT-ARC read-only archive · snapshot: July 23, 2026

C/C++ Beginner's Guide and Post Basic Questions here

548 posts · originally from https://geek.digit.in/community/threads/c-c-beginners-guide-and-post-basic-questions-here.132924/

Liverpool_fan
Liverpool_fan Original post #1
Oct 14, 2010 at 5:31 PM
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:
*img4.imageshack.us/img4/8531/path3.png
*img12.imageshack.us/img12/1399/path4.png
*img11.imageshack.us/img11/6822/path5.png
*img18.imageshack.us/img18/1511/path6.png

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:
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:
su

Then pass the comand.(exact as in the quotes):

Code:
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.

PHP:
#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.
PHP:
#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:
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:
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:
*img89.imageshack.us/img89/8343/program.png
*img26.imageshack.us/img26/893/savertz.png
*img530.imageshack.us/img530/4053/compile.png

Steps for Mac OS X users:
*img836.imageshack.us/img836/3885/sc1z.jpg
*img259.imageshack.us/img259/2444/sc2n.jpg

Steps for Linux users:
*img152.imageshack.us/img152/9222/screenshot2btw.png
*img2.imageshack.us/img2/3937/screenshot4ymv.png

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.
Who
Who #2
Oct 15, 2010 at 7:46 AM
It might be hard to believe (LFC_fan can do something besides trolling) but LFC_fan is right lads,

I however would like to elaborate why exactly we should avoid books by Yashavant P. Kanetkar (Let Us C,Data structures through C,etc) or most indian authors for that matter.

First of all C was actually had invented for Unix by K&R which anyone would know about , TC was made for DOS (DOS compiler) ,it wasn't even intended to be a drop-in sub for ansi-c/gcc/clang/etc, i would say it was a good compiler/IDE Dos however.It is still used in embedded system which use DOS but that's pretty rare nowadays.

So if you are using TC you are wasting time on something so outdated which won't be used beyond your class room, if you are giving interview for a standard company & have no clue of ansi-c/gcc/clang/etc then good luck finding a job.

anyway in summary i would like list out the points why you shouldn't use Yashavant P. Kanetkar or any other indian books for that matter,

1. Like i said before C was written for Unix , yet the author thinks that C was written for Windows DOS, thus your codes are non-portable.

2.Concept like Malloc , Calloc, Free are poorly explained (2 lines actually).

3.Concepts like preprocessor,macros,libraries,memory management , defensive coding etc author thought was too much for our teachers so he decided to skip it (can't hold against him , after all he is a teacher in someways).

4.The books have no history or functionality why the stuff was introduced in the first place, directly jumps to some idiotic fill the blanks , multiple choice, true or false questions (maybe he realize students here need marks so why put details in the first place ? )

5. graphics.h for the ancient turbo c/c++ compiler which enables you to make DOS graphics. programmers had moved on from it 20 years ago. the world is now using opengl and sdl for graphics.

i could go on but i hope by now you guys understand why this books are so bad , it has so many factual errors.


Lastly , i would like to mention a IDE which uses gcc compiler for windows , which served me quite well , called Code::Blocks but again like LFC_fan said it's advisable that you don't(use IDE) at least in the beginning & just stick with Notepad++.
furious_gamer
Oct 15, 2010 at 12:32 PM
Nice initiative LFC_Fan.

When i first create a new thread for Java related queries i didn't explained anything like this. You did a great job there.

And @Who, yes you are right. Yashwant Kanetkar, the one of the most worst author for C. I never suggest anyone this book, but in colleges some professors suggest this for students.

I faced the same and bought this book but never read it for exams and to learn. I always use online resource and it was more than enough to learn stuff to pass in exams. :D
Piyush
Piyush #4
Dec 12, 2010 at 9:30 PM
i have installed minGW
but i cant find any launching icon of the compiler
also i need the details of setting variable path
plz do help
thanks
cute.bandar
Dec 13, 2010 at 12:05 AM
Can someone suggest an alternative solution to puzzle number 24 from this page . there is a solution given already, but me is wondering if there is another way of solving it . anybody up for the challenge ?
Edit: nvmind i figured out a solution myself :) , using the toggle technique.
A
Dec 13, 2010 at 3:58 PM
It might be hard to believe (LFC_fan can do something besides trolling) but LFC_fan is right lads,

I however would like to elaborate why exactly we should avoid books by Yashavant P. Kanetkar (Let Us C,Data structures through C,etc) or most indian authors for that matter.

First of all C was actually had invented for Unix by K&R which anyone would know about , TC was made for DOS (DOS compiler) ,it wasn't even intended to be a drop-in sub for ansi-c/gcc/clang/etc, i would say it was a good compiler/IDE Dos however.It is still used in embedded system which use DOS but that's pretty rare nowadays.

So if you are using TC you are wasting time on something so outdated which won't be used beyond your class room, if you are giving interview for a standard company & have no clue of ansi-c/gcc/clang/etc then good luck finding a job.

anyway in summary i would like list out the points why you shouldn't use Yashavant P. Kanetkar or any other indian books for that matter,

1. Like i said before C was written for Unix , yet the author thinks that C was written for Windows DOS, thus your codes are non-portable.

2.Concept like Malloc , Calloc, Free are poorly explained (2 lines actually).

3.Concepts like preprocessor,macros,libraries,memory management , defensive coding etc author thought was too much for our teachers so he decided to skip it (can't hold against him , after all he is a teacher in someways).

4.The books have no history or functionality why the stuff was introduced in the first place, directly jumps to some idiotic fill the blanks , multiple choice, true or false questions (maybe he realize students here need marks so why put details in the first place ? )

i could go on but i hope by now you guys understand why this books are so bad , it has so many factual errors.


Lastly , i would like to mention a IDE which uses gcc compiler for windows , which served me quite well , called Code::Blocks but again like LFC_fan said it's advisable that you don't(use IDE) at least in the beginning & just stick with Notepad++.

yes, i agree with u.
I read Let Us C, but didn't liked that book. This book was preferred by our teachers in my college. But I studied Programming with C by Gottfried. Although, I already have a good background of programming in Python and Visual Basic. So, studying C was not difficult for me. But if you dont have any programming background and C is your first programming language. Then dont go with Let Us C, as you cannot find out approach of solving a problem. Instead refer foreign authors.
Piyush
Piyush #7
Dec 18, 2010 at 11:05 PM
can someone help me out?
post #5
Liverpool_fan
Dec 19, 2010 at 1:02 AM
^ Click on the Show buttons with the Spoilers. Those illustrate those very questions. And oh this is just a compiler, no launching IDE,etc. If you want IDE, Geany will couple well with MinGW - Geany - FOSS Powered Wiki
Piyush
Piyush #9
Dec 19, 2010 at 9:28 PM
thanks^^
env variables done
A
Jan 26, 2011 at 2:23 PM
Can any one tell me, how i can perform file operations copy, move in C??
shiwa436
shiwa436 #11
Jan 31, 2011 at 4:13 PM
I am unable to download the minGM compiler, please help me in this regard..
furious_gamer
Jan 31, 2011 at 4:56 PM
^^ google it buddy, google it
mohityadavx
Jan 31, 2011 at 9:09 PM
I am a student and can't understand why the author of this post is telling us not to use turbo C++ thats the compiler they teach us in school and college:shock:
arpanmukherjee1
Feb 1, 2011 at 9:25 AM
^^ because tc++ is ::>
a dinosaur compiler,
does not meet current compiling standards,
lousy memory management,
does not generate 32 bit or 64bit exe's
will provide help that has bunch of deprecated and harmful functions
the teacher(s) in colleg dont know what actual industry standards are

u on the other hand must know proper coding techniques and actually understand the standards

Standard ECMA-372
furious_gamer
Feb 1, 2011 at 11:03 AM
I am a student and can't understand why the author of this post is telling us not to use turbo C++ thats the compiler they teach us in school and college:shock:

If its been used by your staffs in college doesn't mean that TC++ is a good compiler. It has lot of loop-holes which was mentioned by @arpanmukherjee1 very well.

Still there are lot of compilers out there which literally tear TC++ into pieces by its performance and features, and whatever fact there is. That's why @OP suggested not to use TC++.

So better get MinGW or any other equivalent compiler.
Ron
Ron #16
Feb 7, 2011 at 5:45 PM
Bookmarked!

Why does the memory allocation of data type in changes with platform? What role Win 32/64 bits plays in size of data type.

In Sumita Arora the size of int is decalred as 2 bytes however in walter savich its 4 bytes. What is the cause of differnce?

I m using Win 7 64 bit window where i m able to cout the int value greater than 65535? Any reason for that
arpanmukherjee1
Feb 8, 2011 at 1:39 PM
Why does the memory allocation of data type in changes with platform? What role Win 32/64 bits plays in size of data type.

that`s a very good question.
int itself is mapped acc. to compiler. 32 bit compiler generates _int32 and 64 bit generates _int64. but after compilation it is not changed. _int32 will not run as _int64 on 64 bit machine and _int64 will be truncated on 32 bit machine.

to avoid confusion use ::> C++ Sized Integer Types

also note not all data types work in this fashion
see :
int on a 64-Bit machine
How INT_PTR datatype works between 64Bit and 32Bit
BigArray<T>, getting around the 2GB array size limit - SpankyJ - Site Home - MSDN Blogs

In Sumita Arora the size of int is decalred as 2 bytes however in walter savich its 4 bytes. What is the cause of differnce?

Data Type Ranges (C++)

int is 4 bytes. forget sumita arora.

I m using Win 7 64 bit window where i m able to cout the int value greater than 65535? Any reason for that

65535 is max for unsigned 16bit int. default is int32 hence the greater range.

*img25.imageshack.us/img25/4327/part1arc.jpg
nims11
nims11 #18
Feb 20, 2011 at 3:25 PM
Why to avoid global variables? any major reason other than code clarity and avoiding any confusion. i find it tempting to use global variables as it becomes quite easier for my functions to access and change it without the use of pointers but i try resist this temptation because people saying "global variable are bad".
Liverpool_fan
Feb 20, 2011 at 3:46 PM
Global variables are bad because every function (and class method) can change it and there may be changes to it which you didn't expect.
Ron
Ron #20
Feb 23, 2011 at 1:03 AM
Global variables are bad because every function (and class method) can change it and there may be changes to it which you didn't expect.

Bro can u elaborate with an xample

---------- Post added at 12:56 AM ---------- Previous post was at 12:55 AM ----------


2arpanmukherjee1
thnks bro

---------- Post added at 01:03 AM ---------- Previous post was at 12:56 AM ----------

Output Problem

cout<<a++<<a++<<b--<<--b<<++b<<--b;

I m havin problem in assumin the ouput of such syntax. Usullly i get unexpected results. Any reason for tht and way to encounter it?
nims11
nims11 #21
Feb 23, 2011 at 7:38 AM
[/COLOR]Output Problem

cout<<a++<<a++<<b--<<--b<<++b<<--b;

I m havin problem in assumin the ouput of such syntax. Usullly i get unexpected results. Any reason for tht and way to encounter it?

let a=1 and b=2 before this 'cout' statement.
then here is what happens when "cout<<a++<<a++<<b--<<--b<<++b<<--b;" is executed.

a++
output a; a+=1;
a is now 2, b is now 2;
output status : 1

a++
output a; a+=1;
a is now 3, b is now 2;
output status : 12

b--
output b; b-=1;
a is now 3, b is now 1;
output status : 122

--b
b-=1;output b;
a is now 3, b is now 0;
output status : 1220

++b
b+=1;output b;
a is now 3, b is now 1;
output status : 12201

--b
b-=1;output b;
a is now 3, b is now -1;
output status : 122010


Final Output- 122010.
Neuron
Neuron #22
Feb 23, 2011 at 9:18 PM
^^It depends on the compiler IMO.
Liverpool_fan
Feb 23, 2011 at 10:05 PM
^^It depends on the compiler IMO.

This. It falls under the domain what we call "Undefined Behaviour".

Ron: Try compiling your C++ code with g++ -Wall flag and see the warning. ;)

As for global variables.
c++ - Are global variables bad? - Stack Overflow
Global Variables Are Bad
mitraark
mitraark #24
Feb 24, 2011 at 4:01 PM
Any software all in one package i can use to write and compile C [ GCC ] >?? DevC++ or something ??? Something which can be installed on machines without Internet connection [ unlike MinGW which is downloading files ]

---------- Post added at 04:01 PM ---------- Previous post was at 03:49 PM ----------

MinGW is working great , will i be able to install it in Windows 7 6 Bit PC without Internet connection ?
vickybat
vickybat #25
Feb 24, 2011 at 4:09 PM
Devc++ is the best imo.
skeletor
skeletor #26
Feb 24, 2011 at 5:07 PM
I am a student and can't understand why the author of this post is telling us not to use turbo C++ thats the compiler they teach us in school and college:shock:
Let me put this straightforwardly. Indians are idiots. Not even Pakistanis use Turbo C++.

Teachers are not willing to move on. The curriculum makers are sleeping. et cetera.

---------- Post added at 05:07 PM ---------- Previous post was at 05:03 PM ----------

Any software all in one package i can use to write and compile C [ GCC ] >?? DevC++ or something ??? Something which can be installed on machines without Internet connection [ unlike MinGW which is downloading files ]

---------- Post added at 04:01 PM ---------- Previous post was at 03:49 PM ----------

MinGW is working great , will i be able to install it in Windows 7 6 Bit PC without Internet connection ?

Try this out: CodeLite IDE LiteEditor/Download

Here is the direct link: *sourceforge.net/projects/codelite/...9/codelite-2.9.0.4684-mingw4.4.1.exe/download
vickybat
vickybat #27
Feb 24, 2011 at 5:10 PM
^^ Good point made ico.We should move on. But ain't devc++ suffice?
skeletor
skeletor #28
Feb 24, 2011 at 5:13 PM
^^ Good point made ico.We should move on. But ain't devc++ suffice?
It will easily suffice but Dev C++ has not seen any development since 6 years.
vickybat
vickybat #29
Feb 24, 2011 at 5:17 PM
^^Okay, so whats widely used in development now?
skeletor
skeletor #30
Feb 24, 2011 at 5:25 PM
^^Okay, so whats widely used in development now?
Anything with which you are comfortable with.

Eclipse, Netbeans and Microsoft Visual C++ are excellent. But many of their features are unnecessary if you are only into basic programming.

Dev C++ comes with an old version of MiniGW by default.
vickybat
vickybat #31
Feb 24, 2011 at 5:32 PM
^^ eclipse and netbeans are for java only right. I'm interested only in c++. So Microsoft Visual C++ will be a good choice right?
skeletor
skeletor #32
Feb 24, 2011 at 5:35 PM
No, you can use Netbeans and Eclipse for C/C++ programming too. Microsoft Visual C++ is a good choice, no doubt.
vickybat
vickybat #33
Feb 24, 2011 at 5:39 PM
^^ Thanks for that info ico.
A
Feb 24, 2011 at 6:23 PM
^ you can use qt also.........
nims11
nims11 #35
Feb 27, 2011 at 12:58 PM
Hey guyz i have a problem...
There is an easy question at SPOJ whose answer is a set of many numbers which i have to output to stdout. the time limit is 6 sec. i used C++. The algo does the processing of these numbers in less than 2 seconds in worst case. But outputting these numbers is causing the program to exceed the time limit!! any suggestions?
Neuron
Neuron #36
Feb 27, 2011 at 3:02 PM
Instead of printing each of the number with separate output commands,use a single command to output a group of numbers at the same time.

Run following codes,the second one will be faster.

for(i=0;i<100000;i++)
printf("%d ",i);

for(i=0,j=1,k=2;i<100000;i+=3,j+=3,k+=3)
printf(" %d %d %d",i,j,k);
nims11
nims11 #37
Mar 8, 2011 at 8:16 AM
sorry for replying late...
thanx it works but i had to use a series of 10 "%d" to make it significantly faster...

Most confusing C Code.... - Fun Enclave
Neuron
Neuron #38
Apr 26, 2011 at 7:43 PM
^^Wow,great find.
RBX
RBX #39
Jun 8, 2011 at 9:20 PM
Re: Post your C/C++ Programs Here

How will this be evaluated in C and C++ ?

printf("%d",sizeof('A'));
arpanmukherjee1
Jun 9, 2011 at 12:35 AM
Re: Post your C/C++ Programs Here

Code:
Code:

#include <STDIO.H>  
 using namespace std;   
int main(char *args, int argc) 
{ 
  printf("%d float\n",sizeof(float));  
  printf("%d int\n",sizeof(int)); 
  printf("%d char\n",sizeof(char));  
  printf("%d long\n",sizeof(long));  
  return 0; 
} 

Output:

4 float
4 int
1 char  //your answer
4 long
Liverpool_fan
Jun 9, 2011 at 11:58 AM
Re: Post your C/C++ Programs Here

How will this be evaluated in C and C++ ?

printf("%d",sizeof('A'));

char is usually 1 byte. Though remember size of the fundamental data types depends on the compiler/CPU architecture.
RBX
RBX #42
Jun 9, 2011 at 9:35 PM
Re: Post your C/C++ Programs Here

'A', I think, is evaluated differently in C and C++

I use TurboC compiler, it appends cpp extension by default.

So, when using cpp (C++) : printf("%d",sizeof('A')); resulted in 1 (char)
but when I switched to .c extension, the result changed to 2.
Liverpool_fan
Jun 9, 2011 at 9:40 PM
Re: Post your C/C++ Programs Here

^ That's because in C, the character literal like 'a', etc. are of type int (4 byte usually) NOT char.
In C++, it's of type char (1 byte).

Apparently you are using a 16bit compiler (Turbo C++. eww leave that crap and use a proper compiler), so you are getting 2 byte as the size of integer.
RBX
RBX #44
Jun 9, 2011 at 9:48 PM
Re: Post your C/C++ Programs Here

^ That's because in C, the character literal like 'a', etc. are of type int (4 byte usually) NOT char.
In C++, it's of type char (1 byte).
That explains. I'm curious why there's such a difference in both languages ? Is C++ not supposed to be compatible with C ?

Turbo C++. eww leave that crap and use a proper compiler
You know what, I just switched ;)
to gcc
Liverpool_fan
Jun 9, 2011 at 9:53 PM
Re: Post your C/C++ Programs Here

That explains. I'm curious why there's such a difference in both languages ? Is C++ not supposed to be compatible with C ?
I think C has that due to historical reasons. There was a link explaining that, but I can't seem to find it now.
Regarding the second point, C++ should be considered to be a very different language to C, even though synatically they are similar but the approach of programming is very different.
RBX
RBX #46
Jun 9, 2011 at 10:27 PM
On the Compiler thing. I downloaded and installed gcc 4.6.0.

Now, I'm confused over which of the available tools should I be using.

I used gcc for compiling .c and .cpp files and it seems they both worked as intended.
I then tried g++ and compiled both .c and .cpp files and it seems they both were treated as C++ programs.

So, is gcc an extension dependent compiler and g++ a C++ specific ? And, I can use only 'gcc', keeping the extensions correct ?
Liverpool_fan
Jun 9, 2011 at 10:49 PM
What is the difference between g++ and gcc? - Stack Overflow
c++ - Difference between CC, gcc and g++? - Stack Overflow
Performance difference between gcc and g++ for C program - Stack Overflow
What's the difference between gcc and g++/gcc-c++? - Stack Overflow

I think it's pretty clear use gcc for C programs. While you can use gcc for C++ with -lstdc++ flag as well since GCC = Gnu Compiler's collection and it calls the appropriate compiler according to file extension, however g++ will directly call the C++ compiler, so your source will be compiled as a C++ program.
RBX
RBX #48
Jun 9, 2011 at 11:17 PM
The main differences:

gcc will compile: *.c/*.cpp files as C and C++ respectively.
g++ will compile: *.c/*.cpp files but they will all be treated as C++ files.

The less voted answer says what I want but gcc's unmentioned inability to pull c++ files suggest that I should use g++ for C++ and gcc for C.
Liverpool_fan
Jun 10, 2011 at 8:32 AM
The less voted answer says what I want but gcc's unmentioned inability to pull c++ files suggest that I should use g++ for C++ and gcc for C.

Code:
gcc -lstdc++ abc.cpp -o a.exe

gcc can compile C++ code, with right extension and the flag -lstdc++, since with that flag it links the standard C++ libraries. g++ uses that by default, so less typing. So stick with g++.
SlashDK
SlashDK #50
Jun 15, 2011 at 8:53 PM
Why don't you guys recommend using IDEs for beginners?
Liverpool_fan
Jun 15, 2011 at 9:34 PM
There's no black and white answers for using an IDE. It depends on the learner. However for absolute beginners, it's strongly advised to begin coding in a text editor, and step by step compile and execute rather than simply jump to an IDE. After the basics are clear, IDEs can be great.
A
Aug 26, 2011 at 11:35 AM
Starting tutions for cbse XII (C++) HELP!

I am planning to start taking C++ tutions for CBSE class XII students.The boys who have approached me told me that they are using turbo C++ as the compiler.They are also using Sumitha Arora's book as reference.

1)I need a link to download the turbo C++ compiler
2) I also need a good reference book for C++ at class XII level .
nims11
nims11 #53
Aug 26, 2011 at 12:55 PM
1. Free File Hosting & Video Downloads, Free File Sharing, Online Friends Network - Ziddu
2. sumita arora should be enough for class XII. however, you may want keep C++ : complete reference or any other good book with you.
Vyom
Vyom #54
Aug 26, 2011 at 1:19 PM
@achuthan1988: I am sorry to say this, but if you going to use Turbo C++ as the compiler, as well as the book by Sumita Arora as the book, you would be the worst teacher for any student.
I strongly recommend you to read the first post of this thread.

And use, GCC as the compiler, and Thinking in C++ as the reference book.
nims11
nims11 #55
Aug 26, 2011 at 4:37 PM
And use, GCC as the compiler, and Thinking in C++ as the reference book.

Your comment is 100% valid if the tuition was for general students/people who wanted to Learn Programming.

he teaching class XII CBSE students! for them, marks is a higher priority (sad but true). no doubt every programmer should be using the current standards but students are required to use the junk compiler at schools and practicals.
as For THINKING IN C++, it is an excellent book and i am currently reading it but i doubt if most of the topics in the book will be of much use for them.

I might sound quite stupid but the above statement was keeping the current education system and student mentality in mind. if the achutan1988 starts teaching class XII students (who have joined his tuitions for securing good marks in boards) under GCC, he will only lose them.

Anyway, from my experience, it ain't a big deal using gcc and newer standards for regular use and using the junk stuffs for school purpose. i am doing the same thing in college right now.
d6bmg
d6bmg #56
Aug 26, 2011 at 9:08 PM
For CPP, go with Complete Reference C++ by Harbart Schildt.
W
Windows #57
Sep 15, 2011 at 8:23 PM
is there a standalone c++ compiler for windows 7 64 bit?
Liverpool_fan
Sep 15, 2011 at 8:39 PM
Re: Starting tutions for cbse XII (C++) HELP!

I am planning to start taking C++ tutions for CBSE class XII students.The boys who have approached me told me that they are using turbo C++ as the compiler.They are also using Sumitha Arora's book as reference.

1)I need a link to download the turbo C++ compiler
2) I also need a good reference book for C++ at class XII level .

1. The link to You-know-what compiler cannot be provided here, since most links are unlicensed and therefore illegal. You may however get the download from "antiquated downloads" from Borland Website.
2. For a good reference book to You-know-what compiler, check out "Object Oriented Programming in Turbo C++ by Robert Lafore", the old edition.

Make sure you guide students well enough, and make them aware that what they are learning are of no use apart from getting them marks in the Class XII board examinations. Also at least you as a teacher should be able to use modern compiler, and with modern concepts, if you don't want to be ever tripped or humiliated by a slightly smart student.

is there a standalone c++ compiler for windows 7 64 bit?

Check out Code::blocks. Downloads
Make sure you download the version with bundled MinGW.

And from your thread, I can see you come from a You-know-what Compiler background, keep note you are in for a bit of a shock.
If it's school/college stuff you want to manage, dual work with MinGW/Code::blocks and You-know-what compiler running under DOSBOX.
Neuron
Neuron #59
Sep 15, 2011 at 9:31 PM
Actually running it under DOSBOX isn't a good idea.Some programs give incorrect outputs or may malfunction under DOSBOX.
W
Windows #60
Sep 15, 2011 at 9:48 PM
hmm, i downloaded the one without MinGW yesterday. Downloading Win8 atm.
gonna try it tommorow
Neuron
Neuron #62
Sep 16, 2011 at 8:22 PM
I do remember some programs showing wrong output when run through DOSBOX.Don't remember which one though.
vickybat
vickybat #63
Sep 17, 2011 at 6:11 PM
Dev c++ or microsoft visual c++ are the best IDE'S for c and c++. I recon they should be used by both novice and experienced programmers.
nims11
nims11 #64
Sep 17, 2011 at 8:58 PM
^^ + codeblocks
A
Sep 18, 2011 at 12:55 AM
Dev-C++ is old. Use Codeblocks and Microsoft Visual C++.
mitraark
mitraark #66
Sep 23, 2011 at 7:24 PM
I know this isn;t a C++ related question but i use Codeblocks for C++ , what to use for Python /? Ina tutorial they told to use "Eclipse SDK" PyDev but i cannot understand how to get that.
Liverpool_fan
Sep 23, 2011 at 7:45 PM
Which OS?
For beginners' just use IDLE, and/or a simple text editor like vi/gedit/kate/notepad++ etc.
Yeah you can use Eclipse with PyDev but if will be an overkill for learning. If you want help with that, create a new thread. :)

EDIT: This will help *www.rose-hulman.edu/class/csse/resources/Eclipse/eclipse-python-configuration.htm
Neuron
Neuron #68
Sep 23, 2011 at 7:49 PM
Download Eclipse SDK.Then install the PyDev plugin.
Download Eclipse SDK 3.7 fromhere

Then go to 'Help' -> 'Install New Software' and put '*pydev.org/updates' in the 'workwith' box and press enter.Wait a while and the Pydev plugins will be listed.Select and install them.

EDIT:Nevermind :mrgreen:
A
Sep 24, 2011 at 12:36 PM
I would say use IDLE, it is simple and good for beginners. Eclipse is for advanced users.
T
tasamono #70
Sep 26, 2011 at 1:26 PM
^Actually i would say that depends on why are you learning the language, if you are learning to pass a school/college test or just to build a basic competency then IDLE might be the preference.
However if you are trying to learn industry level app development, then you can directly try for eclipse or other advanced IDEs, particularly when you already have a brief idea of any other language or already have a clear understanding of "object" orientation.
The best and easiest way will be to install a good linux distribution, most of them have inbuilt gcc complilers and you can make use of some powerful text editors like VIM, emacs etc. This will not only build your programming skills but also provide you familiarity with Unix tool chains which is very essential in the industry today.
A
Sep 30, 2011 at 1:43 PM
I want to buy a good book for c++ as reference\
The books i have seen are
1) thinking in c++ vol 1
2) c++: the complete reference

Which of the above books would you recommend ? Is there any other good book which i can follow? I am at intermediate level in c++.
Neuron
Neuron #72
Sep 30, 2011 at 2:38 PM
C++,The Complete Reference is a great book.It's is preferable for both beginners as well as experienced programmers.
A
Sep 30, 2011 at 6:44 PM
Hey thanx man for replying to my query..:-o
A
Sep 30, 2011 at 11:04 PM
For Beginners go for Programming in ANSI C by Denis M. Ritchie and Brian W. (didn't remember full name of second author). It is a very, very good book, no one can refuse this fact. First of all read this book twice. Then go for other ones. Good Luck!! :)
Liverpool_fan
Sep 30, 2011 at 11:35 PM
^ He's asking about the C++ book.
I would suggest Thinking in C++.
thetechfreak
Oct 1, 2011 at 7:18 AM
This is a usefull thread @liverpool_fan
Even I am learning c++ and my knowledge on it is very limited :(
A
Oct 3, 2011 at 12:17 PM
^ He's asking about the C++ book.
I would suggest Thinking in C++.

ooppss!! My mistake.
I would suggest, The C++ Programming Language by Bjourne Stroustrup (err... didn't remember his name's spelling). I think, it is a very good book. A must read.
clmlbx
clmlbx #79
Oct 17, 2011 at 9:12 PM
Hey guys I am learning c++ on my own I have few questions..

1. How can I store two different data Into two variables but from Single Input..

example:-

Cout<<"Enter YOU Name";
cin>>'First Name' 'Middle Name' 'Last Name' // user enters name

Now how do I store this in 3 Varibles.. 'Fn' ,' Mn' , 'Ln' Respectively


Example 2.

Cout<<"enter your Screen Rsolution :";
cin>> 1280 x 720

How do I store this in 2 Variables,.. Width and Hegiht


I know how to store this in Single variable .. guys pls reply ASAP


2. How can I store Two data types values in Single Array if not then what is alternate to store two different types of data in Single Variable

Example:
I wish to store string on first Element and Integers in Second Element..
sriharsha_madineni
Oct 17, 2011 at 9:28 PM
Hey guys I am learning c++ on my own I have few questions..

1. How can I store two different data Into two variables but from Single Input..

example:-

Cout<<"Enter YOU Name";
cin>>'First Name' 'Middle Name' 'Last Name' // user enters name

Now how do I store this in 3 Varibles.. 'Fn' ,' Mn' , 'Ln' Respectively


Example 2.

Cout<<"enter your Screen Rsolution :";
cin>> 1280 x 720

How do I store this in 2 Variables,.. Width and Hegiht


I know how to store this in Single variable .. guys pls reply ASAP


2. How can I store Two data types values in Single Array if not then what is alternate to store two different types of data in Single Variable

Example:
I wish to store string on first Element and Integers in Second Element..

cout<<"Enter your Name";
cin> > fn> > mn> > ln;

While giving data, press enter after giving first name & enter again for second & enter again for third. This stores data in respective variables.

2) Take two variables width & height.

cout<<" Enter width & height";
cin> > width> > height;
//if you prefer showing it as 1280x720
cout<<width<<"x"<<height;

Second option, you can use array to store dimensions, like an array for eg dim[2].

dim[0] = //width
dim[1] for height.

3) No you can't since array is a collection of items of similar type, you can't use two data types in an array, but in a string array it still accepts numbers, but considers them as strings.

For encapsulating variables of several data types, you have structures & classes.
clmlbx
clmlbx #81
Oct 17, 2011 at 9:34 PM
^^ well First Question It will only work if user Press Enter after Every Input . That I don't want ..

User should/can write in single line With Just pressing Enter at end of it. But it should store in 2-3 variables.


Edit :: sorry I replied without checking, it is working, no need to press Enter..But what to do Second Examlpe.. If I have to skip 'x' in it (if user writes "1280 x 720")
sriharsha_madineni
Oct 17, 2011 at 9:45 PM
It's been a long time since I worked on Cpp, so I'm not sure of other codes that would explicitly take data into several variables from single line. If I'm not wrong, leaving a space between each variable will work too.

Try the book "Practical Cpp programming" for variations in syntax.

Edit:
Not sure if user inputs 1280x720, it is possible if the variable is a single string, I'm not sure, but it is not possible for integer variables afaik.
Liverpool_fan
Oct 17, 2011 at 10:08 PM
In C, the scanf format specifier can be used for format specifiers directly.

Code:
scanf("%dx%d", &var1, &var1)

Not really a C++ programmer, so i don't really remember the equivalent for C++. You can use scanf in C++ by cstdio, though.
clmlbx
clmlbx #84
Oct 17, 2011 at 10:10 PM
Yes, spaces are working . Is their way to Eliminate one word from it.. I mean If user writes three words with spaces .. I just want First and third word . ..so just eliminate second Word or one I desire..(1280 x 720)

Yes, I do have practical c++ programming (2002), and also pls some one can share a site where I can get few beginners-intermediate assignments for practicing c++..

thanx for help
Vyom
Vyom #85
Oct 18, 2011 at 12:10 AM
Yes, spaces are working . Is their way to Eliminate one word from it.. I mean If user writes three words with spaces .. I just want First and third word . ..so just eliminate second Word or one I desire..(1280 x 720)

Yes there is a way. You can use 3 different variables to input 3 words. And just don't use the 2nd variable!
Simple, isn't it?

It's like taking a temporary variable to grab 2nd word, which in your case would be X.
clmlbx
clmlbx #86
Oct 18, 2011 at 1:04 AM
^^Yes, I already thought about that. I was just looking for some alternate better way to do it..

Well I was practicing my c++ skills. so WAP to find out PPI of screen.. So user need to enter resolution.. I already did that with old school Way but again I was looking for better alternative.

I will post that programme in this section, "post ur c++........" thread tomorrow morning.
mitraark
mitraark #87
Oct 18, 2011 at 7:03 PM
I am going to do some work on Image Processing , which would require analysing a .pbm file and converting it into a .bin Binary file. I will be using C , file handling for the job , have to pass the file name and output file name as parameters [ in main , argc argv .. ] .

Anyone has any good suggestions of e-books for C File Handling operations ?
A
Oct 19, 2011 at 8:38 PM
^^^ if you are using Linux then read
Beginning Linux Programming or Linux System Programming Handbook. Both of them are very good books. You will find everything related to Linux Programming in C and yes File Handling is also explained.
Also you can go for Programming in ANSI C by Denis Ritchie.
krishnandu.sarkar
Nov 11, 2011 at 12:22 PM
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\Krishnandu>cd Desktop

C:\Documents and Settings\Krishnandu\Desktop>gcc helloworld.c -o helloworld.exe
c:/mingw/bin/../lib/gcc/mingw32/4.6.1/../../../../mingw32/bin/ld.exe: cannot fin
d -ladvapi32
c:/mingw/bin/../lib/gcc/mingw32/4.6.1/../../../../mingw32/bin/ld.exe: cannot fin
d -lshell32
c:/mingw/bin/../lib/gcc/mingw32/4.6.1/../../../../mingw32/bin/ld.exe: cannot fin
d -luser32
c:/mingw/bin/../lib/gcc/mingw32/4.6.1/../../../../mingw32/bin/ld.exe: cannot fin
d -lkernel32
collect2: ld returned 1 exit status

C:\Documents and Settings\Krishnandu\Desktop>

I'm getting this error on Windows.
Vyom
Vyom #90
Nov 11, 2011 at 6:48 PM
^^ Looks like a gcc installation problem.

Try Codeblocks.
krishnandu.sarkar
Nov 11, 2011 at 7:51 PM
Ya, the error is generating from linker.
A
akash_roy #92
Jan 11, 2012 at 5:45 PM
Its a huge discuss about c,c++. Thanks for sharing lots of knowledge about it..
pramudit
pramudit #93
Jan 13, 2012 at 1:48 AM
didn't understand that windows variable thing....
can somebody tell it step by step.....! :noob:
Liverpool_fan
Jan 13, 2012 at 1:54 AM
^^ Click on the Show Button in Spoiler to see the steps.
pramudit
pramudit #95
Jan 13, 2012 at 2:51 AM
done..... :)
just 1 question, why we dont have to include .h with iostream but with other libraries like math and conio .h have to be included????
Liverpool_fan
Jan 13, 2012 at 2:59 AM
<iostream> vs <iostream.h>

And oh math.h et al are used in C, in C++ you use the STL libraries (so no .h and for C libs in C++ its #include<cmath>). And oh forget about conio.h, et al they are non-portable and antiquated.

P.S: Have a thorough reading of this thread. Don't skim the posts.
Reaper_vivek
Jan 17, 2012 at 8:08 PM
@Liverpool_fan and other programmers..I have to ask for my assurance :p Did u guys know this much about coding when u were students or when u started working..

I ask because, I am in my final year and I am interested into coding, but i just know the basics of languages like C, C# and java..like, right NOW my skills aren't enough for making a complete program/project by myself..I am still learning about it, but I just want to know whether I am lagging behind much or not..You may call it a comparative thing but I just want to know, whether to start working really really hard or just continue with my current pace...
Vyom
Vyom #98
Jan 17, 2012 at 8:59 PM
^^ You wouldn't have ask that question, if you were "interested" in learning any language.

People are not born as experts (or knowledgeable). They become one by learning. And learn they do because they have "interest".

There's no point in working hard, if you are doing it for the lack of heart. That would just seem "a task". A task which would be just unsurmountable.
Liverpool_fan
Jan 17, 2012 at 9:30 PM
If you're following Indian education (that includes NIIT and such stuff), then yes you are lagging behind big time and not even close to a respectable standard and can't even begin to compare with International standards.
Mind you, you require good communication skills, and just being half decent for a job as a fresher rather than technical excellence.
Reaper_vivek
Jan 17, 2012 at 10:17 PM
@Vyom..I AM interested, and thus have been reading a lot of books...I needed the assurance because every1 tells me that my coding isn't at the same level as others..And then I see it here on tdf..that you guys know a lot about coding and it fascinates me...So i just wanted to know..But sadly I didn't get the answer...

I have good communication skills but it's the TECHNICAL part I'm currently not good at...I know I don't have to be a genius to land a job at any software developing firm..But I DO need deep understanding of the concepts..

I hadn't been coding for a while now..started again few days ago..But I was always interested and intrigued by how programs solve complex problems..:D
nims11
nims11 #101
Jan 18, 2012 at 12:08 AM
keep practicing and remain dedicated, try your hands at some online judge to polish your language and algo skills.
krishnandu.sarkar
Jan 18, 2012 at 12:19 AM
From my experience I'd say, keep your concepts clear. On interview generally people doesn't ask you to write programs, but mainly focuses on concepts and logic.

Though you may need to give machine test / may get asked for writing programs but that won't be tricky and all, it's just to test your logic.

You may not know everything, but what you know should be perfect.
Liverpool_fan
Feb 10, 2012 at 3:16 PM
Few posts have been moved to *www.thinkdigit.com/forum/programming/136185-turbo-c-c-other-junk-compilers-discussions-here.html

Kindly keep your queries relating to ANSI standards code and only differences with antiquated code if required. Other junk can be posted in the above thread. Thanks.
Faun
Faun #105
Feb 15, 2012 at 5:32 PM
Learning double pointer linked lists. Gotta code soon with explanation.
Liverpool_fan
Feb 15, 2012 at 6:34 PM
^ That takes me back. [C]Why do we need double pointers for inserting in a link list - Ubuntu Forums :p
pratik385
pratik385 #107
Mar 20, 2012 at 3:50 PM
Hey guys!!!
Im working in C++ i was so disappointed when Company gave me Java Track, i just hate it, now im using C++ - Multithreading and STL :)
pratik385
pratik385 #108
Mar 22, 2012 at 12:29 PM
.

Hey guys,
Tell me one thing, does Dev C++ supports Multi-threading using POSIX i.e. pthreads?
If not then which IDE will support, Cygwin?
In company we have Web sense so we cant download it too :(
A
abhijangda #109
Mar 23, 2012 at 12:17 PM
mingw is a gcc port for windows, and it includes POSIX library. Moreover, do not use Dev C++ use Code Blocks. Dev C++ is old and outdated.
CommanderShawnzer
Mar 24, 2012 at 9:23 PM
hi,can anyone post a link to a site which has an auto installing minGW compiler?
A
abhijangda #112
Mar 25, 2012 at 12:13 AM
tdm-gcc.tdragon.net/
download it or download Code::Blocks.
utkarsh73
utkarsh73 #113
Mar 30, 2012 at 8:41 PM
I read the first post today and came to know that I was going the wrong way till now(Using Turbo C compiler :oops:).
So I downloaded MS Visual C++ express edition and installed it, but it looks more complex than what I have used till now. Header files are defined in different section, source code is written in other etc etc.
That's not an issue but I noticed we have to prefix "std::" before "cout" and "cin" and some header files a bit different and there will many other such modifications which I want to learn(I learned from some Sumita Arora book :oops: so you can understand what I mean).
Are there any tutorials which can help me in migrating from Turbo C to this new compiler?? I don't want to go through that 1000 page "C++ the complete reference" or "thinking in C++" if I can avoid.
Liverpool_fan
Mar 30, 2012 at 9:36 PM
You don't need to read the complete book to pick on the basics. :|
utkarsh73
utkarsh73 #116
Mar 31, 2012 at 10:07 AM
You don't need to read the complete book to pick on the basics. :|

I am trying to implement every concept separately in this new compiler to learn the modifications. Till now, I have tried simple loops(for, while, do-while), switch statement, string functions, class and constructors etc. all separately. Initially they were giving errors which I solved after some googling(like using "_getch()" instead of "getch()", using "using namespace std;" etc).
I am trying a file handling program now(writing characters to a file) which is giving errors. Looking forward to rectify that.

^Same issue for me :(

Which compiler are u using now(Assuming by your statement that you were using turbo C earlier)???
Liverpool_fan
Mar 31, 2012 at 12:10 PM
You shouldn't be using _getch() either. It is a non-standard function as well and it is as bad as using the compiler you used. Use getchar or cin.get to read characters (Note input is buffered). And there's no point of either clearing a screen or trapping a keyboard output. Console programs aren't supposed to behave like that. And an IDE like Geany does that job for you automatically.

Forget about whatever you did in the you-know-what compiler. Read your book (yes thinking in C++) as if it's a new language you're learning.
skeletor
skeletor #119
Mar 31, 2012 at 12:21 PM
@utkarsh73

Buy a proper C++ book and read it. Think this way - your knowledge in C++ is zero.

Sumita Arora doesn't teach anyone anything. It only transforms one into -

*i.imgur.com/MMOHt.jpg

You don't need to read the complete book to pick on the basics. :|
I guess everyone missed your sarcasm.
utkarsh73
utkarsh73 #120
Mar 31, 2012 at 2:29 PM
I think I better start from scratch now......:oops:
clmlbx
clmlbx #121
Mar 31, 2012 at 3:40 PM
I read some where that best books to start learning c++ is "Thinking In C++ 2nd Ed. - Vol 1 & vol 2".. should I start from that..

what do I know in c+.., I can say confidently that I should know at least 40% of c++, I believe so.. By self learning now I am thinking to start reading book which I have left.. But I wish start from scratch..

I have OBJECT-ORIENTED PROGRAMMING WITH C++ third edition by E BALAGURUSAMY..

which is best book for c++ between those two or any other to learn c++
A
abhijangda #122
Mar 31, 2012 at 4:40 PM
Thinking in C++ by Bruce Eckel is wonderfull book. It takes you to the depth of C++. I have read that book twice and really it is an awesome one. It is not only for beginners but for experts also. After it go for The C++ Programming by Bjarne Stroustrup, this one is relatively some what harder to understand as compare to Thinking in C++, but is an excellent reference. You will find everything in this book. Also,you can read C++ Primer it is a good one too. But, mostly reading Thinking in C++ will make you a good C++ programmer. Also, just throw Balaguruswami, Yashwant Kanetkar, Sumita Arora etc. book's in dustbin. Also, use a modern compiler like gcc or msvc++.
clmlbx
clmlbx #123
Mar 31, 2012 at 4:47 PM
well I am using codeblocks, I bought that book when I started to learn then when I knew it is not good I kept aside and started learning from internet but after learning-practicing a lot I feel I have missed some basic core concepts so thinking to start from basic..

so was looking forward for thinking in c++ second edition volume one and two
utkarsh73
utkarsh73 #124
Mar 31, 2012 at 8:43 PM
Starting reading Thinking in C++ volume-1 2nd edition today. Almost finished first 2 chapters. A fantastic book, as is always the case with PHI/Pearson publication books.
dashing.sujay
Mar 31, 2012 at 8:53 PM
Starting reading Thinking in C++ volume-1 2nd edition today. Almost finished first 2 chapters. A fantastic book, as is always the case with PHI/Pearson publication books.

Author ?
Liverpool_fan
Apr 1, 2012 at 8:54 PM
Trapping Keyboard to make your output window "hang"? No I am NOT having that here. Posts deleted.

For all my efforts, great way of ignoring it.
You shouldn't be using _getch() either. It is a non-standard function as well and it is as bad as using the compiler you used. Use getchar or cin.get to read characters (Note input is buffered). And there's no point of either clearing a screen or trapping a keyboard output. Console programs aren't supposed to behave like that. And an IDE like Geany does that job for you automatically.

Forget about whatever you did in the you-know-what compiler. Read your book (yes thinking in C++) as if it's a new language you're learning.
skeletor
skeletor #128
Apr 1, 2012 at 8:57 PM
Things to Avoid in C/C++ -- system("pause"), Part 4 - GIDNetwork
utkarsh73
utkarsh73 #129
Apr 1, 2012 at 9:03 PM
Ok, My mistake, I understand now. But then, how do I see my output?? There must be a way to see that output window. I m not able to figure it out.

What I use as "cin.get()" or "cin.getline(<string name>,<size>) " is correct then??
Liverpool_fan
Apr 1, 2012 at 9:04 PM
The OP has clearly mentioned everything. And use an IDE like Geany.

What I use as "cin.get()" or "cin.getline(<string name>,<size>) " is correct then??
Why are you insisting on "trapping" your keyboard input to see output. How hard it is for you to run a couple of commands for every program or use an IDE like Geany.
nims11
nims11 #132
Apr 1, 2012 at 9:15 PM
Things to Avoid in C/C++ -- system("pause"), Part 4 - GIDNetwork

hmm, no idea about it as i always code under Linux and using terminal is butter compared to windows Command Line
utkarsh73
utkarsh73 #133
Apr 1, 2012 at 9:17 PM
Why are you insisting on "trapping" your keyboard input to see output. How hard it is for you to run a couple of commands for every program or use an IDE like Geany.

I just want to see what output my program is producing, thats all. I don't intend to trap my keyboard input. It is not at all hard for me "run a couple of commands for every program" but I really don't know what are those "couple of commands" which can help me see my output(Downloading Geany now).

I think I better start reading the book: maybe I can find something in there.
Liverpool_fan
Apr 1, 2012 at 9:25 PM
I just want to see what output my program is producing, thats all. I don't intend to trap my keyboard input. It is not at all hard for me "run a couple of commands for every program" but I really don't know what are those "couple of commands" which can help me see my output(Downloading Geany now).

I think I better start reading the book: maybe I can find something in there.

You didn't read my original post of this thread did you?

hmm, no idea about it as i always code under Linux and using terminal is butter compared to windows Command Line

You can always use cygwin in Windows, if you wish. vim + gcc can work for you there.
skeletor
skeletor #135
Apr 1, 2012 at 9:26 PM
I just want to see what output my program is producing, thats all. I don't intend to trap my keyboard input. It is not at all hard for me "run a couple of commands for every program" but I really don't know what are those "couple of commands" which can help me see my output(Downloading Geany now).

I think I better start reading the book: maybe I can find something in there.
I would say - get rid of that thought. Start using Geany.
Vyom
Vyom #136
Apr 1, 2012 at 10:39 PM
I just want to see what output my program is producing, thats all.

I don't know what's the fuss all about.
In the *that which shall not be named* compiler, you can always view the output by going to Window -> Output OR Alt + F5. So no use of getch() there.

In Code::blocks in windows, you don't need something akin to getch() since, the the compiler does automatically for you.
So on and so forth for every compiler. So, problem?
utkarsh73
utkarsh73 #137
Apr 1, 2012 at 11:22 PM
^^The problem is I don't know the Alt+F5 equivalent in MS Visual C++. Only this I want to know. Now I am using MinGW which has no such fuss. But if you know any such "Alt+F5 equivalent", please tell me.

P.S.:-Now I m not using system("pause") or cin.get() or any such thing to trap keyboard input.
dashing.sujay
Apr 1, 2012 at 11:36 PM
^^The problem is I don't know the Alt+F5 equivalent in MS Visual C++. Only this I want to know. Now I am using MinGW which has no such fuss. But if you know any such "Alt+F5 equivalent", please tell me.

P.S.:-Now I m not using system("pause") or cin.get() or any such thing to trap keyboard input.

I also have not been able to find a solution for this. :confused:
utkarsh73
utkarsh73 #139
Apr 2, 2012 at 12:05 AM
^^I suggest u start using MinGW. Compiling and executing is done by commands in the command prompt so the problem will never arise.
Liverpool_fan
Apr 2, 2012 at 12:42 AM
How to: Compile a Native C++ Program from the Command Line
Writing and Compiling C Program using Microsoft Visual C++ 2010 Express Edition TechnoZeal
$$Lionking$$
Apr 29, 2012 at 12:50 AM
so nobody here using dj delories?? thats pretty good too u know... and probably less intimidating too for people coming from older Borland IDE's...

^^I suggest u start using MinGW. Compiling and executing is done by commands in the command prompt so the problem will never arise.

heheh... :twisted:
nbaztec
nbaztec #143
May 4, 2012 at 9:39 PM
^^The problem is I don't know the Alt+F5 equivalent in MS Visual C++. Only this I want to know. Now I am using MinGW which has no such fuss. But if you know any such "Alt+F5 equivalent", please tell me.

P.S.:-Now I m not using system("pause") or cin.get() or any such thing to trap keyboard input.

I also have not been able to find a solution for this. :confused:

Whenever I use Visual Studio for console apps (like never, unless absolutely required), I tend to use a blocking input statement like cin.get()/Console.Read() while debugging only.

The reason being, console apps are meant to be
  1. Fired.
  2. Parse args or read input.
  3. Give output, if any.
  4. Die.

Or when I'm feeling lazy, I run sans the debugger (Shortcut Ctrl+F5). This gives me a "Press a key to continue..." prompt.

But that's rarely the case, since most of what I do are services meant to run indefinitely until a exit character appears.

PS: Remove these blocking statements in your Release builds since it comes to bite you in the hiney. Forking the programs having blocking input statements as their last one's, are every programmer's nightmare when the I/O streams are redirected. Trust me.
A
May 17, 2012 at 12:33 AM
Re: C/C++ IDE for windows 7 starter.

Is it for 32 bit? or for 64 bit? I need for 64 bit OS. Can anyone help me please.
Liverpool_fan
May 17, 2012 at 1:30 AM
Re: C/C++ IDE for windows 7 starter.

Moved this post from other thread.

Is it for 32 bit? or for 64 bit? I need for 64 bit OS. Can anyone help me please.

Doesn't matter 32bit applications run fine in Windows (WoW64).
T
May 17, 2012 at 2:58 PM
Please suggest a c++ ide for windows 7 64 bit. The Turbo c++ ide doesn't work on it. Is there any emulator available that can run it on windows 7 64 bit ?
nbaztec
nbaztec #147
May 17, 2012 at 3:01 PM
Please suggest a c++ ide for windows 7 64 bit. The Turbo c++ ide doesn't work on it. Is there any emulator available that can run it on windows 7 64 bit ?

This thread

PS: DosBox can emulate TC.
T
May 17, 2012 at 3:08 PM
please give a download link.

PS: too tired to google it :wink:
skeletor
skeletor #149
May 17, 2012 at 3:14 PM
please give a download link.

PS: too tired to google it :wink:
And you expect him to Google that for you and then post the link?

Stop procrastinating and Google yourself. Or even better, read the link which was given to you.
nbaztec
nbaztec #150
May 17, 2012 at 3:16 PM
I got ninja'd by ico.

P.S. @the_conqueror I already gave the thread link :/
T
May 17, 2012 at 5:01 PM
And you expect him to Google that for you and then post the link?

Stop procrastinating and Google yourself. Or even better, read the link which was given to you.

Sorry mate !
D
dingdong #152
May 17, 2012 at 5:48 PM
i used to have balgurusamy c++ book.I dont know i could hardly understand anything from it.
Vyom
Vyom #153
May 17, 2012 at 6:41 PM
Please suggest a c++ ide for windows 7 64 bit. The Turbo c++ ide doesn't work on it. Is there any emulator available that can run it on windows 7 64 bit ?

I should give you a free advice. Don't ever discuss "Turbo C++" here. You may get banned. Seriously.

For more information read the first page of this thread. Or if you still feeling, "Lazy", just refer, post no#26.
P
parjanya #154
May 28, 2012 at 9:23 AM
i am new to c/C++
where can i get useful books and code writing softwares

parjanya
P
parjanya #155
May 28, 2012 at 9:28 AM
c help

i want tutorials for c/c++ programming
and how get compliers which will run my system
pentium 4 @2.4Ghz
512 ram
windows xp 32 bit sp 3
parjanya
krishnandu.sarkar
May 28, 2012 at 10:08 AM
Re: c help

Check *www.thinkdigit.com/forum/programming/132924-c-c-beginners-guide-post-basic-questions-here.html
nims11
nims11 #157
May 28, 2012 at 12:05 PM
C - C programming by dennis ritchie.
C++ - thinking in C++
blademast3r
May 30, 2012 at 12:15 AM
Re: c help

Its great that you want to learn C. Please dont have the impression that C and C++ are closely related. Even though basic syntax is similar the programming paradigm is different. This is not emphasized enough in most Indian courses/colleges.

Stick to C. I would suggest you buy "programming in c" by kernighan and Ritchie (the inventors of C) . It is a ~200 page book but dont underestimate its size. Should cost you about Rs 150.

About compiler, I would highly recommend installing a flavour of linux such as ubuntu. This comes with all the tools you need to start off coding and then some!

Happy coding
T
Jun 3, 2012 at 3:23 PM
I read somewhere on this forum that C++ books by Indian authors(like Sumita Arora) are not good for proper learning of the language. I'm a beginner so please suggest a book(with the name of the author) which is perfect for learning C++. I have no experience with other languages. If the suggested book is available on flipkart then please give its link also. I shall be highly obliged.
Vyom
Vyom #160
Jun 3, 2012 at 5:07 PM
I read somewhere on this forum that C++ books by Indian authors(like Sumita Arora) are not good for proper learning of the language. I'm a beginner so please suggest a book(with the name of the author) which is perfect for learning C++. I have no experience with other languages. If the suggested book is available on flipkart then please give its link also. I shall be highly obliged.

Quoted from the first post of this thread itself:

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
tech_boy
tech_boy #161
Jun 6, 2012 at 10:40 AM
For beginners, i would suggest
C++ - "C++ for Dummies"
C - "C for Dummies"
These books are excellent for beginners and concepts r explained with concrete examples.
T
Jun 6, 2012 at 1:14 PM
Quoted from the first post of this thread itself:

Is 'Thinking in C++' good for a beginner. It is my first ever language so i want that the book teaches me all the basic concepts clearly.
nims11
nims11 #163
Jun 6, 2012 at 1:49 PM
^^ Thinking in C++ is helpful for those who are already familiar with 'C' or little 'C++'.
you may learn 'C' from "C programming by dennis ritchie"
Liverpool_fan
Jun 6, 2012 at 2:26 PM
Is 'Thinking in C++' good for a beginner. It is my first ever language so i want that the book teaches me all the basic concepts clearly.

C++ is not for a beginner. One should learn C before C++. For that I would +1 nims' suggestion and you to get Head First C as well and learn from both.
Though ideally I would recommend Python as a first language.
Desmond
Desmond #165
Jun 6, 2012 at 2:34 PM
You can code in C++ in a normal, structured fashion. So, it doesn't make much difference if you learn C++ first. Since C++ is compatible with C code to a large extent, you can learn C++ first in a structured manner then move on to OOP.

Though personally it would be better to learn C first.
digit.sh
digit.sh #166
Jun 6, 2012 at 3:31 PM
Anyone know where I can find pdf or text documents containing all the built in function(of C language) declaration like following:

Declaration:

size_t strlen(const char *str);

Computes the length of the string str up to but not including the terminating null character.

Returns the number of characters in the string.
nims11
nims11 #167
Jun 6, 2012 at 4:08 PM
Anyone know where I can find pdf or text documents containing all the built in function(of C language) declaration like following:

C Library - C++ Reference
T
Jun 6, 2012 at 5:30 PM
C++ is not for a beginner. One should learn C before C++. For that I would +1 nims' suggestion and you to get Head First C as well and learn from both.
Though ideally I would recommend Python as a first language.

Actually, C++ is in my school syllabus. They have started from C++. And the book they've prescribed is a crap Sumita Arora one. Teachers aren't that good too. Can't understand the basics of OOP. That is why, I'm in need of a proper book for C++. And now, due to huge pressure of science and maths, i can't learn both C and C++.
I remember I've studied GW-BASIC, in 6th-7th standard, and I don't think that'd be enough for me.
Liverpool_fan
Jun 6, 2012 at 5:32 PM
Well none of those books will help you then, since you won't be able to cope up with them either. In that case either drop CS, it's useless anyway or just rote and vormit that crap book. If for anything it's useful to get marks in your board examinations.
T
Jun 6, 2012 at 5:59 PM
CS is the only optional subject in which I can score good. I will surely fail in other optional subjects(hindi, music and art). :p
I want to learn those languages, and since I'm not preparing for the ISEET right now, so I can devote a little time to C and C++ everyday.
S
SahilAr #171
Jun 6, 2012 at 6:51 PM
Heyy Techies,i want to start programming from scratch,i wanna build and boost my Fundamentals in Programming,i should start with C or Python?
(I heard Python is a Server Side Programming Language)
Liverpool_fan
Jun 6, 2012 at 8:14 PM
Heyy Techies,i want to start programming from scratch,i wanna build and boost my Fundamentals in Programming,i should start with C or Python?
(I heard Python is a Server Side Programming Language)

Python.
Python can be used as a Server Side Programming Language but it is not restricted to it.
S
SahilAr #173
Jun 6, 2012 at 8:23 PM
So you mean i should start learning Python without any fundamentals/knowledge/experience with Programming?If yes,please refer me the source where to start with Python?
Also,please mention the reason not choosing C/C++ as starter?
Liverpool_fan
Jun 6, 2012 at 8:46 PM
Links, Resources, and a hotly contested debate. *www.thinkdigit.com/forum/programming/156195-book-beginner.html
This should be enough for you to take your decision.
S
SahilAr #175
Jun 6, 2012 at 9:25 PM
Links, Resources, and a hotly contested debate. *www.thinkdigit.com/forum/programming/156195-book-beginner.html
This should be enough for you to take your decision.

I asked you why Python over C?
Also,what are the resources for learning python,resources include:books,compilers etc...book is not sufficient!
Vyom
Vyom #176
Jun 6, 2012 at 9:30 PM
I asked you why Python over C?
Also,what are the resources for learning python,resources include:books,compilers etc...book is not sufficient!

Dude! At least "try" to read that thread which has been quoted for you.
Also, world has something so awesome for you! Google!
I will give you the keywords to give you a jump start. "Compiler for Python".

There. Now, happy learning! :doublethumb:
S
SahilAr #177
Jun 6, 2012 at 9:47 PM
Hmm...
I have not only tried tried,instead I have "Gone" with that thread!!
Everyone is just supporting python as a base for programming but i can't see why c over python,everyone saying c/c++ as being complicated..and they end up supporting Python.
Google can't answer my question:why python over c as a base for programming!
Liverpool_fan
Jun 6, 2012 at 9:59 PM
There is no universal answer. Basically you have to trust others to make your choice. You don't have the necessarily knowledge or experience to know the difference.
S
SahilAr #179
Jun 6, 2012 at 10:05 PM
There is no universal answer. Basically you have to trust others to make your choice. You don't have the necessarily knowledge or experience to know the difference.

Hmm..
Ico and You deserve a gReaT thanks for solving my problem,i will start with Python now,rather than c/c++.
That Debate thread actually answered my question..You guys are really Dedicated,once again thanks a lot :)
krishnandu.sarkar
Jun 6, 2012 at 11:01 PM
That's right, Sahil. How can you know (understand) the differences if you don't know anything about language.??

As LFC said, you have to trust others. And I guess you already answered your query. Peoples saying C is complicated over Python. So that's the answer..!!

Now, google won't recommend you Python / C / C++ / Something else. Because every language has it's own perspective and each one is best in it's own way and domain.

Anyway, leave these theories for now, be practical and get into practical.

Just go to Download Python and download the appropriate installer.

Now, get a book, for get *files.swaroopch.com/python/byte_of_python_v192.pdf and get started. :D

Happy Programming. :D
T
Jun 6, 2012 at 11:47 PM
I have a few questions :
How much time would I require to learning the basics of C ?
Can I switch to C++ after that ? Would it be harmful if I step on C++ directly without learning C ?
Please suggest a book of C and C++ with all the beginner stuff.

PS-please go through my previous posts before answering so you can understand my situation.
Liverpool_fan
Jun 7, 2012 at 12:00 AM
1. As much time as basics of C++ will.
2. No. Particularly the way C++ is set in Indian education, it is basically outdated C programming in C++ with classes.
3. You've been recommended already. But I'll say again: The C Programming Language and Head First C both. You don't need to complete both books either just go as far as you can. For C++, then continue with Thinking in C++.
T
Jun 7, 2012 at 12:09 AM
So head first C and thinking in c++ would be the perfect combo for me.
Thanks for help.
A
abhijangda #184
Jun 13, 2012 at 11:17 PM
After reading both volumes of Thinking in C++, read The C++ Programming Language by Bjarne Stroustrup and C++ Primer.
bijay_ps
bijay_ps #185
Jun 18, 2012 at 7:28 PM
I wrote a simple hello world program but not stored it in Ubuntu's home directory, instead i stored it in one of the windows drive. (I am using ubuntu 12.04 alongside of windows)When I compiled the program it worked just fine but when I tried to execute it I got an error message "Permission denied". And When I store the program in Ubuntu's home directory I can perfectly compile and execute the program. So please tell me how to overcome this problem??

I even tried sudo command, but it didn't helped
nims11
nims11 #186
Jun 18, 2012 at 8:02 PM
you need to make the compiled file executable, do this by
Code:
chmod +x a.out

if you want the compiled file to be always executable, then in /etc/fstab, add an entry for your windows drive like this
Code:
/dev/sda2 /media/xyz ntfs defaults,ntfs-3g,user,exec 0 1
Baker
Baker #187
Jun 24, 2012 at 7:44 PM
need to install gcc on my suse 10..... tell me where i can down load the package and how to install
Liverpool_fan
Jun 25, 2012 at 11:16 AM
need to install gcc on my suse 10..... tell me where i can down load the package and how to install
Mentioned in the OP.

OpenSUSE

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

And why are you using SuSE 10? That thing is old.
Baker
Baker #189
Jun 25, 2012 at 10:23 PM
hmm actually i am using Suse 10 in vmware..... so i need to download gcc package and install
cyber
cyber #190
Jul 1, 2012 at 5:36 PM
c program error

Code:
#include<stdio.h>
typedef struct uttam
{
        int a;
        struct uttam *next;
}test;
main()
{
test c1,*p;
p->a=2;
printf("%d",p->a);
}

~
~
~
~
when i run the program it says segmentation fault...:-(
Desmond
Desmond #191
Jul 1, 2012 at 5:46 PM
Re: c program error

What compiler you using?
Posted via Mobile Device
gforz
gforz #192
Jul 1, 2012 at 10:01 PM
Re: c program error

In your case,the pointer p is a variable of struct uttam "aliased" by test.
Problem is this pointer doesnt point anywhere and the moment you try to access the member of the struct using this pointer ,it throws segmentation error.
Using typedef ,you cannot assign any address "In this case" ,AFAIK.

So "in this case",the code would be:

#include<stdio.h>
struct uttam
{
int a;
struct uttam *next;
}test;
main()
{
struct uttam c1,*p;
p=&test;
p->a=2;
printf("%d",p->a);
}

hope this helps:razz:


It should work with typedef:

In your code:

p=(test*)malloc(sizeof(test));
X
x64 #193
Jul 7, 2012 at 3:49 AM
Anything with which you are comfortable with.

Eclipse, Netbeans and Microsoft Visual C++ are excellent. But many of their features are unnecessary if you are only into basic programming.

Dev C++ comes with an old version of MiniGW by default.

I find Code::Blocks to be the best IDE for me as a basic programmer. It is very simple yet very efficient IDE for C/C++
K
Jul 7, 2012 at 10:15 PM
Re: c program error

segmentation fault comes when you try to access invalid memory or the memory which doesn't exist in your program yet.

in your code you have not initialized the pointer p with address of some memory location .

Try to initialize p pointer with malloc or new before using it to access a memory location and your code will work fine.
K
Jul 7, 2012 at 10:21 PM
Re: c help

"programming in c" by kernighan and Ritchie is a good book .

But according to my experience indian writers like yashwant also has good expertise in this subject but sometimes they mess up with the basic concepts.So choose wisely .:oops:

for compiler i would recommend you to go with bloodshed dev c++ .For beginners it is best gui based compiler and is integrated with almost every feature.

installing ubuntu will be a trouble for you if you are a windows user which you are .
nbaztec
nbaztec #196
Jul 8, 2012 at 12:34 PM
Re: c program error

segmentation fault comes when you try to access invalid memory or the memory which doesn't exist in your program yet.

in your code you have not initialized the pointer p with address of some memory location .
This.

Try to initialize p pointer with malloc or new before using it to access a memory location and your code will work fine.
new operator is specific to C++
nbaztec
nbaztec #197
Jul 8, 2012 at 12:42 PM
Re: c help

"programming in c" by kernighan and Ritchie is a good book .

But according to my experience indian writers like yashwant also has good expertise in this subject but sometimes they mess up with the basic concepts.So choose wisely .:oops:

for compiler i would recommend you to go with bloodshed dev c++ .For beginners it is best gui based compiler and is integrated with almost every feature.

installing ubuntu will be a trouble for you if you are a windows user which you are .

I suggest you read the C/C++ Beginner Thread before suggesting a compiler which has had no new official release since 2005, over Code::Blocks, Eclipse or even a simple GEdit/Notepad++ ; and thinking that Yashwant Kanetkar has expertise in C in spite of the fact that his Let Us C is a waste of our natural resources.

@OP Just use gcc as the compiler collection and you'd be fine with any text-editor/IDE.

MOD EDIT: Threads merged.
rahul_c
rahul_c #198
Jul 17, 2012 at 8:59 PM
I'm a newb in the programming arena :), just joined a 4 yr (classes not started yet) CSE course. I have some queries:

> What books should I buy for C (first yr course only has C), giving that I've no experience of programming what so ever?

> Which compiler is the best, I've turbo C but it does not work in windows 7? Even though its not recommended everyone still uses it! :|

> How long does it take to reach a level where I can develop my own apps from the scratch? I mean proper GUI apps.

> Do programmers require powerful PCs, I have a old 3 yr laptop (Dell Vostro 1510) would this suffice?

> A silly one: If one wants to learn everything about programming how long is it gonna take? I don't want C/C++ can never be learned entirely crap!
nbaztec
nbaztec #199
Jul 17, 2012 at 9:17 PM
> What books should I buy for C (first yr course only has C), giving that I've no experience of programming what so ever?
Read the starting threads it has aplenty suggestions on the likes of Kernighan & Ritchie. Just don't go for Indian authors.

> Which compiler is the best, I've turbo C but it does not work in windows 7? Even though its not recommended everyone still uses it! :|
Use gcc. Avoid TC at all costs.

> How long does it take to reach a level where I can develop my own apps from the scratch? I mean proper GUI apps.
Depends on you.

> Do programmers require powerful PCs, I have a old 3 yr laptop (Dell Vostro 1510) would this suffice?
No. Only determination.

> A silly one: If one wants to learn everything about programming how long is it gonna take? I don't want C/C++ can never be learned entirely crap!
No programming language can ever be learned entirely. If it can, it might as well cease to exist.
rahul_c
rahul_c #200
Jul 18, 2012 at 8:01 AM
Read the starting threads it has aplenty suggestions on the likes of Kernighan & Ritchie. Just don't go for Indian authors.

Use gcc. Avoid TC at all costs.

No programming language can ever be learned entirely. If it can, it might as well cease to exist.

So the 'can never learn C/C++ entirely' is true, just sounded bull when seniors from college say it.

I'm buying these books: C Programming Language by Kernighan & Ritchie (The Bible :mrgreen:) and Head First C#.

Too bad about the computer though, now need a new reason to tell dad for buying a powerful PC. :-(

For compilers I'm going to use either code::blocks or GCC, gotta try them both.
Liverpool_fan
Jul 18, 2012 at 11:00 AM
Each and every of your question has been covered in the FIRST page itself. Are you that lazy not to actually read the thread? How do you expect others not be equally lazy as you?
rahul_c
rahul_c #202
Jul 18, 2012 at 12:36 PM
^I'm sorry, read the posts from starting and they do answer my questions. Thanks.
akii17kr
akii17kr #203
Jul 19, 2012 at 5:19 PM
"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"

man dis is true ???
I mean previous year I joined aptech computer education centre for learning c language as I m in 2nd yr btech cse NW and previous year I m in 1st year and join aptech for learning basics of c dat will help me in my fcpc subject(computer subject)

and they hv taught me in dis way -

#include<studio.h>
#inlcude<conio.h>
void main()
{
clrscr();
print.........and so on and after writing all codes it ends with..

getch();
}


and after reading da 1st thread I m shocked by dose lines and also shocked by da advice given by u dat to don’t read let us c by yasahvant kanetkar


bcz in my college day teacher also suggested all students let us c and also teaching way of c is da same way of void main and conio which I HV been guided by aptech and and and also we r doin c in TC BOTH IN COLLEGE AND APTECH


so man wtf is dis goin on wid US ???
if college and aptech centre is guiding wrong to us ??......in fact in most of engineering colleges its been taught in dis way....


so who is correct and who is wrong ??

after graduation in which way we hv 2 do programming in jobs ??
nbaztec
nbaztec #204
Jul 19, 2012 at 5:22 PM
"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"

man dis is true ???
I mean previous year I joined aptech computer education centre for learning c language as I m in 2nd yr btech cse NW and previous year I m in 1st year and join aptech for learning basics of c dat will help me in my fcpc subject(computer subject)

and they hv taught me in dis way -

#include<studio.h>
#inlcude<conio.h>
void main()
{
clrscr();
print.........and so on and after writing all codes it ends with..

getch();
}


and after reading da 1st thread I m shocked by dose lines and also shocked by da advice given by u dat to don’t read let us c by yasahvant kanetkar


bcz in my college day teacher also suggested all students let us c and also teaching way of c is da same way of void main and conio which I HV been guided by aptech and and and also we r doin c in TC BOTH IN COLLEGE AND APTECH


so man wtf is dis goin on wid US ???
if college and aptech centre is guiding wrong to us ??......in fact in most of engineering colleges its been taught in dis way....


so who is correct and who is wrong ??

after graduation in which we we hv 2 do programming in jobs ??

Sorry, I don't speak gangsta. Try English.
nbaztec
nbaztec #206
Jul 19, 2012 at 8:06 PM
even a kid can tell dat its English words
not "gangsta"
u can try asking ....

Dat stff rite dere is no English. dat is no make ny snse. dis is English if dat is too.
akii17kr
akii17kr #207
Jul 19, 2012 at 8:14 PM
Dat stff rite dere is no English. dat is no make ny snse. dis is English if dat is too.



I m saying dat u r recommended da foreign author books for learning c ...
OK. datz gud
but in my college teachers suggested for let us c by yashavant kanetkar and according to u dat book is bad... isn't ???


and also

there is also written in first post of page that "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"


but in coaching centre where I learn c they have taught me in dis way in which way u r telling to avoid..


so who rite and who wrong ??
nbaztec
nbaztec #208
Jul 19, 2012 at 8:15 PM
TDF is right.
akii17kr
akii17kr #209
Jul 19, 2012 at 8:25 PM
TDF is right.

rite in wat ??

btw in every engineering colleges c is being taught in dis way....
so .... it means all colleges r wrong.. ?
Liverpool_fan
Jul 20, 2012 at 9:25 AM
No we are all liars working for illuminati and want to put a bad name to Indian colleges. :lol:

Enough. We are not sitting here to reply to stubborn idiotic crap. No more of this shite here. Next please.
skeletor
skeletor #211
Jul 20, 2012 at 10:04 AM
but in coaching centre where I learn c they have taught me in dis way in which way u r telling to avoid..


so who rite and who wrong ??
The whole of India, all colleges and coaching centres are wrong.

The first post is right.

Secondly, stop posting in SMS lingo. "dis" "u" "r" "datz"... replace them with proper English words.

No more discussion on this in this thread. :)
akii17kr
akii17kr #212
Jul 20, 2012 at 10:39 AM
The whole of India, all colleges and coaching centres are wrong.

The first post is right.

Secondly, stop posting in SMS lingo. "dis" "u" "r" "datz"... replace them with proper English words.

No more discussion on this in this thread. :)


chill its fine....

No we are all liars working for illuminati and want to put a bad name to Indian colleges. :lol:

Enough. We are not sitting here to reply to stubborn idiotic crap. No more of this shite here. Next please.

well dude I only asked this because teachers taught in different way..
just clarifying and nothing else...

don"t take it to your heart..

chill and work on your spellings..
rahul_c
rahul_c #213
Jul 23, 2012 at 4:27 PM
Is C# and C same?
rahul_c
rahul_c #215
Jul 23, 2012 at 5:12 PM
OK, thanks I had never heard of C# earlier so it got me confused.
Desmond
Desmond #216
Jul 23, 2012 at 6:02 PM
Sorry, but I've been out of touch with C for a long time now. Can anyone tell me what's wrong with conio.h? I mean, I know that its hard to use it in gcc (you have to use ncurses or something like that instead, if I am not wrong).

Also, what's wrong with "void main()"?
nbaztec
nbaztec #217
Jul 23, 2012 at 6:23 PM
Sorry, but I've been out of touch with C for a long time now. Can anyone tell me what's wrong with conio.h? I mean, I know that its hard to use it in gcc (you have to use ncurses or something like that instead, if I am not wrong).

Also, what's wrong with "void main()"?

conio.h in itself isn't bad but being a non-standard library of obsolete functions, it is highly discouraged to use it.

void main(), while being non-standard too, can cause run-time errors if the underlying system is expecting the return value.
S
SahilAr #218
Jul 23, 2012 at 7:09 PM
@Ico,why don't you close this thread?
rahul_c
rahul_c #219
Jul 31, 2012 at 8:55 PM
So I read Head First C thanks to my friend and I really liked its format, presentation. But it says that "This book assumes you have seen things like loops and variables in some other language, if not we suggest you to start with Head First Programming."

I've no experience whatsoever, will it cause any problems? Should I get both Head first books?
krishnandu.sarkar
Jul 31, 2012 at 9:08 PM
^^Yes it clearly states that "I assume you are new to C, but not new to Programming".
Liverpool_fan
Jul 31, 2012 at 9:44 PM
Well I don't recommend C for a beginner programmer but if you insist go for "C for Dummies", it does begin from scratch.

Sorry, but I've been out of touch with C for a long time now. Can anyone tell me what's wrong with conio.h? I mean, I know that its hard to use it in gcc (you have to use ncurses or something like that instead, if I am not wrong).

Also, what's wrong with "void main()"?
Good that your query has been answered but again, how difficult is actually reading the thread?
rahul_c
rahul_c #222
Jul 31, 2012 at 9:59 PM
Well I don't recommend C for a beginner programmer but if you insist go for "C for Dummies", it does begin from scratch

B. Tech in CS begins programming with C, so I don't have a choice. Do I really need to buy a separate book? Does Head First C starts with that much high level? Which language do you suggest for a absolute beginner anyways?

A separate thing, I need GCC compiler but the one I downloaded (MinGW-get) does not work offline. From where can I get the offline version of GCC?
Liverpool_fan
Jul 31, 2012 at 10:04 PM
HFC does require *some* programming experience. Not advanced but a basic familiarity with programming will do. Either you can learn online (links are there in the OP) and then begin with it, or buy C for dummies if you don't find them right for your needs.

As far as "offline compiler" is concerned, get Codeblocks IDE which bundles MinGW itself.
rahul_c
rahul_c #224
Jul 31, 2012 at 10:15 PM
I do have Code::blocks but HFC uses GCC through out the book, I'm not sure if they are different or same.
krishnandu.sarkar
Jul 31, 2012 at 10:19 PM
Code::Blocks uses gcc as it's compiler. Don't worry.

Genrally the path to GCC in your case would be : C:\Program Files (x86)\CodeBlocks\MinGW\bin.

You can add this path to PATH variable and use gcc and g++ from Command Line too :)
rahul_c
rahul_c #226
Jul 31, 2012 at 10:22 PM
^Thanks then, I will just use Head First C with code::blocks and refer to internet or "you guys" if I've any *fundamental* problem. :)
A
Anurup #227
Aug 4, 2012 at 12:07 AM
Guyz...want to know if Dev-C++ will work on win7 64bit....and also can any1 provide me with the link to the download of Dev -C++(the latest version).......and is programming on it similar to Borland C++?
Some of my classmates r saying that its better to use Eclipse ...is this true..if so what dvantages does it hv?

many say that "Dev-C++ is a crappy old buggy and unsupported IDE" ...is this true...if so which compiler should i opt for...os is win 7 64bit
RBX
RBX #228
Aug 4, 2012 at 10:25 PM
Using GCC 4.7.0 on Fedora 17. I'm getting following error while trying to execute the output file -
Code:
bash: ./Play_Remember_The_Name.out: Permission denied

I've tried chmod / chown.

Edit:
Apparently , it has something to do with the output being on a non Linux partition. Can something be done while compiling, or later to allow the file to run even when it is on NTFS partition ?

Edit:
found solution here
*askubuntu.com/questions/18052/exe-file-permission-fail/18053
sling-shot
sling-shot #229
Aug 4, 2012 at 11:06 PM
So what is Qt w.r.t. to this thread? Qt - Cross-platform application and UI framework &mdash; Qt - A cross-platform application and UI framework

I have read so many glowing tributes about it being very easy to write beautiful cross-platform applications with.

NOTE : Was unable to search this thread because qt is too short for the search bot.
nims11
nims11 #230
Aug 5, 2012 at 2:26 AM
So what is Qt w.r.t. to this thread? Qt - Cross-platform application and UI framework — Qt - A cross-platform application and UI framework

I have read so many glowing tributes about it being very easy to write beautiful cross-platform applications with.

NOTE : Was unable to search this thread because qt is too short for the search bot.
What do you want to know about Qt?
sling-shot
sling-shot #231
Aug 5, 2012 at 10:50 AM
I was thinking if Qt would be a good place to begin programming?
And I did not grasp the concept of what is Qt exactly... Is it a programming language or IDE or a library or what?
W
way2jatin #232
Aug 13, 2012 at 12:14 AM
Is C# a good language to learn along with .net ???
Vyom
Vyom #233
Aug 13, 2012 at 12:28 AM
Is C# a good language to learn along with .net ???

C# is one of the main languages to learn along with .net.
And knowledge of C / C++ will be an added advantage, before you attempt to study C#.net.
nbaztec
nbaztec #234
Aug 13, 2012 at 6:30 PM
Yes, If you have prior knowledge of VB, you can instead go with VB.NET. C#.NET & VB.NET are isomorphic.
T
Aug 26, 2012 at 4:24 PM
I installed codeblocks with the MinGW compiler. Ran it and selected gcc as the default compiler. When I run a C program , it runs fine. But a C++ program gives error that iostream not found. How can an important header file appear missing in library. Whats going wrong ?
rajatGod512
Aug 26, 2012 at 6:19 PM
^^ Simple and easy way : Did You download CodeBlock mingw-setup or not as mingw setup contains the GCC Compiler and GDB Debugger , if you have done that make sure to use GNU GCC Compiler when you maker a program of C++.
krishnandu.sarkar
Aug 26, 2012 at 6:54 PM
I installed codeblocks with the MinGW compiler. Ran it and selected gcc as the default compiler. When I run a C program , it runs fine. But a C++ program gives error that iostream not found. How can an important header file appear missing in library. Whats going wrong ?

^^ Simple and easy way : Did You download CodeBlock mingw-setup or not as mingw setup contains the GCC Compiler and GDB Debugger , if you have done that make sure to use GNU GCC Compiler when you maker a program of C++.

Well he says that he downloaded Codeblocks with MinGW Compiler. Also he clearly states that C Program runs fine. So it's not a problem of Compiler or the Package that he downloaded.

@the_conqueror Can you please provide the piece of C++ program you are trying to run?
T
Aug 26, 2012 at 9:35 PM
*i.imgur.com/ZA7Rw.png
nims11
nims11 #239
Aug 26, 2012 at 9:40 PM
^^ The world has changed a lot since Turbo C++,
Code:
#include<iostream>
using namespace std;
int main()
{
  int x,y;
  cin>>x;
  cout<<x;
  cin>>y;
  cout<<y;
  return 0;
}
krishnandu.sarkar
Aug 26, 2012 at 10:23 PM
@the_conqueror That's what I thought you'd have been using. That's why I asked to post the code. Refer ^^his code.
T
Aug 26, 2012 at 10:39 PM
^ I knew that already bro, and even tried that once, didn't work. I wasn't in a mood of typing so picked up an old file lying around. See what happens when I try it your way:

*i.imgur.com/fnfxh.png
nims11
nims11 #242
Aug 26, 2012 at 11:33 PM
^^ goto Settings-> compiler and debugger, select GNU GCC compiler (if not set), then under the toolchain executable tab, make sure the path to the compiler installation is correct. eg, mine is "C:\Program Files (x86)\CodeBlocks\MinGW"
rajatGod512
Aug 28, 2012 at 7:20 PM
^^ Sorry ... I was in a hurry :-(

^ I knew that already bro, and even tried that once, didn't work. I wasn't in a mood of typing so picked up an old file lying around. See what happens when I try it your way:
On CodeBlocks FAQ I got this :
Q: My simple C++ program throws up lots of errors - what is going on?

If you have a C++ program like this:

#include <iostream>
int main() {
std::cout << "hello world\n";
}

and when you compile it you get errors like this:

fatal error: iostream: No such file or directory

then you have probably given your source file a .c extension. If you do that, the GCC compiler (and others) will probably attempt to compile the file as a C program, not as C++. You should always give your C++ source files the extension .cpp to make sure the compiler handles them correctly.

also try and save the .cpp file in the same directory where you have installed mingw/Codeblocks. See if it works
chavanshashank
Sep 4, 2012 at 10:02 PM
Hey please help me to solve this question. Can anybody give me the source code which is executing and giving right output.
Shown in question below.? I am using DEV C++ and TURBO C 5.5 for compiling.

*Spaceman Spiff

Our super-hero, the fearless Spaceman Spiff, finds himself on the
planet closest to Star X-35 in his quest to wipe out the evil, vicious,
flagitious, heinous alien species that threatened to invade our planet! An
alien approaches...But in the blinding light, our hero can hardly make out
if its hostile. By the way it attacked Spiff's spaceship, he definitely was
hostile!
Spaceman Spiff, captured by vicious Zogwargs, is about to be
transported to the labor camp! But our hero hatches a bold plan!
At the last second, Spiff makes a break! Taking advantage of the planet's
weaker gravity, our hero is away like a shot... towards the infinite galaxy.
Finally away from the planet, only after planting a bomb powerful
enough to eradicate the entire Zogwargs species, Spiff wanders around,
head held high in victory. But wait, what does he notice? His star-o-meter showed him Star X-35's close and strange position relative to Star
Y-40!
He found that the level of a star was an amount of the stars that are
not higher and not to the right of the given star. He wanted to know the
distribution of the levels of the stars.
5
*
4
*
1 * 2 * 3

For example, look at the screenshot of Spiff's space-o-meter. Level of the
star number 5 is equal to 3 (it's formed by three stars with a numbers 1, 2
and 4). And the levels of the stars numbered by 2 and 4 are 1. At this map
there are only one star of thelevel 0, two stars of the level 1, one star of
the level 2, and one star of the level 3.
You are to write a program that will count the amounts of the stars of
each level on a given map and help Spaceman Spiff in cracking the code!
Input
The first line ofthe input contains a number of stars N (1 = N = 15000).
The following N lines describe coordinates of stars (two integers X and Y
per line separated by a space). There can be only one star at one point of
the plane. Stars are listed in ascending order of Y coordinate. Stars with
equal Y coordinates are listed in ascending order of X coordinate. Output
The output should contain N lines, one number per line. The first line
contains amount of the level 1 and level N-1.
Example Input: 5
1 1
5 1
7 1
3 3
5 5
Output: 1
2
1
1


Please reply.! Thanks.
TheSloth
TheSloth #246
Oct 21, 2012 at 10:44 PM
hi, i am new to open Source world. Using Fedora 17. I tried to install gcc complier given on first page, somthing started to download and then a error came like " Mo mirror to try".I need compilers of c and c++ urgently.I have Win7 too and tried in that too but failed there also. But first i want compilers in Linux
dashing.sujay
Oct 21, 2012 at 11:09 PM
^For windows gcc/VStudio is good.
TheSloth
TheSloth #248
Oct 21, 2012 at 11:34 PM
For windows i tried doing things given on first page but i don't understand the problems i am facing. Infact I didn't understand things i was doing. I installed MinGW then set variable path to something something then tried compiling a cpp program but "command not found".
ud0103
ud0103 #249
Oct 30, 2012 at 6:46 PM
I installed codeblocks with the MinGW compiler. Ran it and selected gcc as the default compiler. When I run a C program , it runs fine. But a C++ program gives error that iostream not found. How can an important header file appear missing in library. Whats going wrong ?

Try this code:-

using namespace std;
#include<iostream>

int main()
{
cout<<"Hello!";
}

Good Luck!
A
abhijangda #250
Dec 7, 2012 at 3:50 PM
hi, i am new to open Source world. Using Fedora 17. I tried to install gcc complier given on first page, somthing started to download and then a error came like " Mo mirror to try".I need compilers of c and c++ urgently.I have Win7 too and tried in that too but failed there also. But first i want compilers in Linux
This error occurs, when yum is not able to connect to any of the mirrors available in list.
If you have any proxy settings then add them in /etc/yum.conf file.
TheSloth
TheSloth #251
Dec 9, 2012 at 7:22 PM
@abhijangda: i'll try it. Thanks. But i already installed devc++. Working good except sometimes.
SlashDK
SlashDK #252
Dec 19, 2012 at 11:22 PM
Hi people,

I need help installing GCC for practicing c++ for Indian Olympiad of Informatics. I already have vc++ but GCC is the official compiler. I tried to follow the instructions at Installing GCC - GNU Project - Free Software Foundation (FSF) but failed miserabely at every step :D Is there any automated installer for GCC for c++? (I havn't been able to find any).

EDIT: For Windows.

EDIT: Finally found a preper tutorial on youtube. Downloading from Codeblocks with MinGW now
RBX
RBX #254
Dec 25, 2012 at 12:17 PM
C was first semester subject, but I didn't buy a book and never actually learned it, somehow passed with lab knowledge (with Turbo C).
So, now I'm looking to formally learn it with a book that illuminates most aspects of C language - not looking for an introduction to programming book, neither a very old book.
So could anyone suggest a book that gives detailed knowledge of pointers, typedef etc with illustrations and follows at least C99 ?
krishnandu.sarkar
Dec 25, 2012 at 6:16 PM
C was first semester subject, but I didn't buy a book and never actually learned it, somehow passed with lab knowledge (with Turbo C).
So, now I'm looking to formally learn it with a book that illuminates most aspects of C language - not looking for an introduction to programming book, neither a very old book.
So could anyone suggest a book that gives detailed knowledge of pointers, typedef etc with illustrations and follows at least C99 ?

Go for Head First C. You'd enjoy the learning with Head First
Harsh Pranami
Feb 5, 2013 at 7:01 PM
Wrote my first program today. :hyper:. It was the same Hello world as given on the firsr page. Can anyone post some more basic programs like that?? Or better suggest a book that begins from root level.
krishnandu.sarkar
Feb 6, 2013 at 7:33 AM
Wrote my first program today. :hyper:. It was the same Hello world as given on the firsr page. Can anyone post some more basic programs like that?? Or better suggest a book that begins from root level.

Head First C as suggested above.
vickybat
vickybat #259
Feb 6, 2013 at 12:06 PM
I'd like to disagree. The book is not for someone who is about to start his programming journey.

Why not mate ? Can you please justify?

Head first series has helped me a lot and i was a complete noob in programming. I've read "head first java", "head first sql" , "head first html5" and i was completely new to those technologies.
Those books gave me a broad understanding of various concepts and head first c should be no different.

That is miles ahead than books like venugopal, yashvant kanetkar and the likes that most students read.
dashing.sujay
Feb 6, 2013 at 12:51 PM
Why not mate ? Can you please justify?

Head first series has helped me a lot and i was a complete noob in programming. I've read "head first java", "head first sql" , "head first html5" and i was completely new to those technologies.
Those books gave me a broad understanding of various concepts and head first c should be no different.

That is miles ahead than books like venugopal, yashvant kanetkar and the likes that most students read.

There's a difference between a noob programmer and a starter programmer. One is acquainted enough but unclear, one is in complete darkness. Head first C is a but high level for latter.
vickybat
vickybat #261
Feb 6, 2013 at 1:43 PM
There's a difference between a noob programmer and a starter programmer. One is acquainted enough but unclear, one is in complete darkness. Head first C is a but high level for latter.


Ok i'm starting to get what you're trying to put here. But i don't think head first c is that much complicated for beginners.
I mean its fairly simply and easy to understand than books i stated in my previous post. I would even go on to say that the book is even simpler than Dennis Ritchie's "The C Programming language", the creator of C.

So you have any better suggestion here for newbies?
dashing.sujay
Feb 6, 2013 at 3:37 PM
Ok i'm starting to get what you're trying to put here. But i don't think head first c is that much complicated for beginners.
I mean its fairly simply and easy to understand than books i stated in my previous post. I would even go on to say that the book is even simpler than Dennis Ritchie's "The C Programming language", the creator of C.

So you have any better suggestion here for newbies?

Well I couldn't find a book as good as head first C. It is simple, but only for those, who know even a bit of programming, or have good born-grasping of programming. I'm saying this as I've tested this personally on some of my friends. It may differ for others. :)
krishnandu.sarkar
Feb 6, 2013 at 3:39 PM
Well yeah, Head First C is not for starters. It for programmers who atleast know what programming is.

For those type of readers, I suggest Head First Programming and then Head First C.

Head First Programming introduces programming language concepts with Python, which is the best language for starters (in my and various other members opinion).

See, there's no point in learning a language if you can't cover the tricks. C has many tricks and the main tricks lies on pointer and structure (we all know that). HFC makes those areas clear by keeping the base strong.

So no point in learning C first.

Finally..
1. If anyone have previous programming experience go for Head First C.
2. If not, then get Head First Programming and move to Head First C.
Harsh Pranami
Feb 10, 2013 at 10:06 PM
Well yeah, Head First C is not for starters. It for programmers who atleast know what programming is.

For those type of readers, I suggest Head First Programming and then Head First C.

Head First Programming introduces programming language concepts with Python, which is the best language for starters (in my and various other members opinion).

See, there's no point in learning a language if you can't cover the tricks. C has many tricks and the main tricks lies on pointer and structure (we all know that). HFC makes those areas clear by keeping the base strong.

So no point in learning C first.

Finally..
1. If anyone have previous programming experience go for Head First C.
2. If not, then get Head First Programming and move to Head First C.

Since I am a complete :noob: I'm going for head first programming.

Well yeah, Head First C is not for starters. It for programmers who atleast know what programming is.

For those type of readers, I suggest Head First Programming and then Head First C.

Head First Programming introduces programming language concepts with Python, which is the best language for starters (in my and various other members opinion).

See, there's no point in learning a language if you can't cover the tricks. C has many tricks and the main tricks lies on pointer and structure (we all know that). HFC makes those areas clear by keeping the base strong.

So no point in learning C first.

Finally..
1. If anyone have previous programming experience go for Head First C.
2. If not, then get Head First Programming and move to Head First C.

Since I am a complete :noob: I'm going for head first programming.
Desmond
Desmond #265
Feb 26, 2013 at 7:37 PM
Learn BASIC first to get programming fundamentals right. There are many online BASIC interpreters to get you started or you can find GWBASIC and run it on Dosbox.
Vyom
Vyom #266
Feb 26, 2013 at 7:51 PM
^^ Basic is not at all necessary even if you are a complete noob in programming! :|
mitraark
mitraark #267
Feb 27, 2013 at 12:43 PM
Learn BASIC first to get programming fundamentals right. There are many online BASIC interpreters to get you started or you can find GWBASIC and run it on Dosbox.

I understand what you are trying to say, BASIC probably has the most similarities with real world languages, but BASIC is defunt now, you can start with Python though, although i believe one should have the sense to grasp C fundamentals from the beginning.
Desmond
Desmond #268
Feb 27, 2013 at 1:45 PM
BASIC might be defunct but I am suggesting to learn its fundamentals. It's the easiest language I know, therefore very appropriate for utter noobs to get a grasp of programming. I would suggest python next.

PS: BASIC is not as defunct as you think. Visual Basic uses a syntax similar to Basic.

Edit: Indeed one should have some fundamentals in C since it is still relevant in low level coding and embedded systems programming.
omega44-xt
omega44-xt #269
Mar 13, 2013 at 7:13 PM
Can someone please explain me these programs ??

#include<stdio.h>
void main()
{
int i=5, j;
j=++i+(++i)+(++i);
printf("%d %d",i, j);
}
Can someone explain why j=22 ? I'm clear about i=8....

#include<stdio.h>
void main()
{
int n; // assuming int to be 32 bit long
printf("Enter a number : ");
scanf("%d", &n);
//shift it right 31 times so that MSB comes to LSB's position
//and then and it with 0x1
if ((n>>31) & 0x1 == 1) {
printf("Negative number\n");
} else {
printf("Positive number\n");
}
}
This one checks if a number is positive or negative. What is 0x1 == 1 ?
dashing.sujay
Mar 13, 2013 at 7:48 PM
Can someone please explain me these programs ??


Can someone explain why j=22 ? I'm clear about i=8....

You're initiating j from garbage value, which is a bad programming practice, that's why the wrong result. Try with j =0.
dashing.sujay
Mar 13, 2013 at 7:52 PM
I can't get your second program though. If you want to check a number if it's positive or not, then it's very easy.
omega44-xt
omega44-xt #272
Mar 13, 2013 at 8:13 PM
You're initiating j from garbage value, which is a bad programming practice, that's why the wrong result. Try with j =0.

So what ? Answer will be same if I initialize "j" with garbage value or user defined value........ I'm not a noob

I can't get your second program though. If you want to check a number if it's positive or not, then it's very easy.

I want to check it without using relational & conditional operators i.e. like using if(n<0) printf(.....)
nims11
nims11 #273
Mar 14, 2013 at 12:04 AM
Can someone please explain me these programs ??

This one checks if a number is positive or negative. What is 0x1 == 1 ?

For a 32 bit signed integer, the 32nd bit denotes the sign, so (n>>31)&1 is 1 if the number is negative(i.e. the sign bit is set)
harshilsharma63
Mar 14, 2013 at 5:13 PM
I want to check it without using relational & conditional operators i.e. like using if(n<0) printf(.....)

Check this link: can we compare two integers without using relational operators - C / C++
reddick
reddick #275
Mar 16, 2013 at 7:11 PM
Hi Friends!

I want to learn basic programming but I have done B.A only. So Is it necessary to pursue B.Tech (Computer Science) for learning programming. Actually I did not know the basics though that is Difference between Programmers and Developers? How to make Applications? About JavaScript, C or C++ etc.?
Please suggest me any books or links so that I can learn and practice all this at home...Thanks a lot :)

P.S - I have downloaded Notepad++ today :rolleyes:
harshilsharma63
Mar 16, 2013 at 8:11 PM
Hi Friends!

I want to learn basic programming but I have done B.A only. So Is it necessary to pursue B.Tech (Computer Science) for learning programming. Actually I did not know the basics though that is Difference between Programmers and Developers? How to make Applications? About JavaScript, C or C++ etc.?
Please suggest me any books or links so that I can learn and practice all this at home...Thanks a lot :)

P.S - I have downloaded Notepad++ today :rolleyes:

> B.Tech. is not at all required for learning programming. Besides, if you join some average college, the only things you'll learn are college's map, authors of various books, which teacher knows what, and a few other useless stuff.

> Programmer is one who codes. He eats code, he shits code, he walks code, he talks code, he lives in code. Programmer is one who knows how to code, ALONG with how to design a good UI, how to organize a project, and basically everything related to creation of a software. According to Time magazine, Software Engineering is the number 1 job as per pay-per-stress levels. there are many many other stuffs than coding in SE.

> To create an application, you need a paper, a pen, and you need to know the applications format. Just kiding :p you must know some programming language for that. Start with c, then progress to c++ -> Java -> c#

> Herbert Schidlt is my personal favourite for C++ and Java for begineers.

> Congratulations, now you can edit text files in a WHOLE NEW app!!! :clap:


BTW why do you want to go into programming?
reddick
reddick #277
Mar 17, 2013 at 6:01 PM
Actually I or we all use computer techniques or related stuff in our daily life like - internet, android, e-mail, etc. So I just want to know the basic structure of this world and Secondly this field would develop more and more in coming yrs. So I think I have to learn the broad and only important areas just to increase my general knowledge :idea:
reddick
reddick #278
Mar 19, 2013 at 9:28 PM
Anybody please help by replying my querry . . .
nightcrawler
Apr 4, 2013 at 2:55 PM
I suggest you grab a good C/C++ book out there. Get a free C/C++ compiler and start coding on your own. That is how I learnt it. Although I am an Engineer, the Engineering syllabus or the teaching here in India is very poor. Most of the engineers out there (I am talking about Computer & IT) do not know how to write simple programs and get their way through by way of mugging. So if you want to learn you don't need to be an engineer :)

Take it from there and see how things go. Slowly start solving various programming puzzles that you might find across various sites. Just google it, you will find tonnes of them. Get your programming basic fundamentals to the T though. It will help you a lot as you move across various other languages.

Also it is more of developing a programming approach, language does not matter much. Yes you will be able to do certain things more easily in one language over the other, but then each language was designed for a specific purpose and will suite better for that purpose obviously. Although once your fundamentals are in place, all that you need to learn is syntax and rules of the new language that you will be using to code.

Hope this helps
saswat23
saswat23 #280
Apr 7, 2013 at 10:06 AM
Explain me the output of this:

Code:
void main()
{
float a=1.22; 
if (a==1.22) 
printf("C");
else 
printf("cD");
getch();
}
harshilsharma63
Apr 7, 2013 at 10:53 AM
Explain me the output of this:

Code:
void main()
{
float a=1.22; 
if (a==1.22) 
printf("C");
else 
printf("cD");
getch();
}

Thats a classic! It's just one of many codes to represent the complex world of floating point numbers. So, this is what happens:

> 1.22 base 10 is (0.0011100001010001111010111000010100011110101110000101...) base 2.

> The bold part is the binary pattern that repeats till infinity.

> As we do not have infinite memory, so to store it in a memory, it is truncated and rounded off to (1.22000003) base 10.

> Since 1.22000003 is NOT equal to 1.22 (which is stored as 1.22000000 in a float variable), so the program executes the false parte instead of the true part of if-else code (debug the program to see the actual values).

> Have a look at this page: 2.5 — Floating point numbers « Learn C++

> Float numbers are beyond any webpage's scope!
velociraptor
Apr 13, 2013 at 2:06 PM
hey i wrote a prog in c++ using notepad and i cant get how to compile and execute it please tell in detail .i m using windows 8 and i have got the MinGW compiler installed
nightcrawler
Apr 13, 2013 at 2:38 PM
Check out the MinGW wiki for First Time Users and the HOWTO guide on their site. It should solve all your problems and queries easily. Unless you are having problems in compiling itself.
Vyom
Vyom #284
Apr 13, 2013 at 2:43 PM
hey i wrote a prog in c++ using notepad and i cant get how to compile and execute it please tell in detail .i m using windows 8 and i have got the MinGW compiler installed

You can either install Code::blocks, which after integration with MinGW, will give you a full fledge IDE. Or compile and run program from command line.

  1. Press Windows + R.
  2. Open Command Prompt.
  3. With CD command navigate to the "bin" folder where MinGW is installed.
  4. Compile the program:
    g++ cppfile.cpp -o output.exe
  5. And then run the output file by just entering the name of output file and pressing enter.
    output.exe


You could have also used c++ command as an alternative to g++.

PS: Of course you have to keep program in bin folder, or give full path of the cpp filename.
gameranand
gameranand #285
Apr 13, 2013 at 6:31 PM
hey i wrote a prog in c++ using notepad and i cant get how to compile and execute it please tell in detail .i m using windows 8 and i have got the MinGW compiler installed

If you don't want any trouble and don't want to go the conventional way then you can use Code::Blocks. :)
somebodysme
Apr 13, 2013 at 6:59 PM
For improving problem solving
*projecteuler.net
*www.codechef.com

Register and get started
TheSloth
TheSloth #287
Apr 13, 2013 at 10:35 PM
In projecteuler.net, do they give solutions too?
nightcrawler
Apr 14, 2013 at 12:02 AM
In projecteuler.net, do they give solutions too?
No not directly. They give you a problem and ask you for the output. If it is correct you have solved the puzzle. I believe once that is done you could access the forum to get the answer or something. Although not sure. Not been on projecteuler for last 2 years or so.
harshilsharma63
Apr 14, 2013 at 10:33 AM
In projecteuler.net, do they give solutions too?
They have a forum for the purpose. However, I recommend to build the code yourself, get the correct answer, the optimize the code to the lowest complexity possible and then compare it with a code in the forum or elseware :)
velociraptor
Apr 15, 2013 at 5:30 PM
thanxx everyone thanx a lot
kunalht
kunalht #291
May 13, 2013 at 11:35 PM
Hii
I have just completed 12th sci.
Now I have vacation.
I want to learn programming in this vacation.
Which shold I learn HTML or C or C++ or JAVA ????
I want to learn this at home(without any classes)
can i learn it without classes??
& also plz suggest me some website or books or ebooks for learning that....
Nerevarine
Nerevarine #292
May 13, 2013 at 11:42 PM
python, learn it as a hobby..
Im learning it myself..
although.. u need basic OOP concepts to do any good
rohitshubham
Jun 25, 2013 at 3:46 PM
Help Me with this code
Code:
[COLOR=#339933]#include<stdio.h>[/COLOR]
 [COLOR=#993333]void[/COLOR] main[COLOR=#009900]([/COLOR][COLOR=#993333]void[/COLOR][COLOR=#009900])[/COLOR][COLOR=#009900]{[/COLOR]   
 [COLOR=#993333]long[/COLOR] x[COLOR=#339933],[/COLOR]y [COLOR=#339933];
[/COLOR] [URL="*www.opengroup.org/onlinepubs/009695399/functions/scanf.html"][COLOR=#000066]scanf[/COLOR][/URL][COLOR=#009900]([/COLOR][COLOR=#FF0000]"%l %l"[/COLOR][COLOR=#339933],[/COLOR] [COLOR=#339933]&[/COLOR]x[COLOR=#339933],[/COLOR] [COLOR=#339933]&[/COLOR]y[COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]   [COLOR=#B1B100]if[/COLOR][COLOR=#009900]([/COLOR]x[COLOR=#339933]>[/COLOR]y[COLOR=#009900])
[/COLOR]    [COLOR=#009900]{[/COLOR]    [URL="*www.opengroup.org/onlinepubs/009695399/functions/printf.html"][COLOR=#000066]printf[/COLOR][/URL][COLOR=#009900]([/COLOR][COLOR=#FF0000]"%l"[/COLOR][COLOR=#339933],[/COLOR]y[COLOR=#009900])[/COLOR][COLOR=#339933];[/COLOR]     [COLOR=#009900]}[/COLOR]  
  [COLOR=#B1B100]else[/COLOR]     [COLOR=#009900]{[/COLOR]     
[COLOR=#B1B100]       if[/COLOR][COLOR=#009900]([/COLOR]x [COLOR=#339933]%[/COLOR] [COLOR=#0000DD]5[/COLOR] [COLOR=#339933]==[/COLOR][COLOR=#0000DD]0[/COLOR][COLOR=#009900])[/COLOR]  
      [COLOR=#009900]{[/COLOR]         y[COLOR=#339933]=[/COLOR] y[COLOR=#339933]-[/COLOR]x [COLOR=#339933];[/COLOR]    
               y[COLOR=#339933]=[/COLOR]y[COLOR=#339933]-[/COLOR][COLOR=#800080]0.5[/COLOR][COLOR=#339933];
[/COLOR]               [URL="*www.opengroup.org/onlinepubs/009695399/functions/printf.html"][COLOR=#000066]printf[/COLOR][/URL][COLOR=#009900]([/COLOR][COLOR=#FF0000]"%l"[/COLOR][COLOR=#339933],[/COLOR] y[COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]     [COLOR=#009900]}[/COLOR]     
      [COLOR=#B1B100]else[/COLOR] 
       [COLOR=#009900]{[/COLOR]            [URL="*www.opengroup.org/onlinepubs/009695399/functions/printf.html"][COLOR=#000066]printf[/COLOR][/URL][COLOR=#009900]([/COLOR][COLOR=#FF0000]"%l"[/COLOR][COLOR=#339933],[/COLOR] y[COLOR=#009900])[/COLOR][COLOR=#339933];[/COLOR]                [COLOR=#009900]}[/COLOR]     
[COLOR=#009900]}
[/COLOR]     [COLOR=#009900]}[/COLOR]
It's Giving me runtime error

Help Me with this code
Code:
[COLOR=#339933]#include<stdio.h>[/COLOR]
 [COLOR=#993333]void[/COLOR] main[COLOR=#009900]([/COLOR][COLOR=#993333]void[/COLOR][COLOR=#009900])[/COLOR][COLOR=#009900]{[/COLOR]   
 [COLOR=#993333]long[/COLOR] x[COLOR=#339933],[/COLOR]y [COLOR=#339933];
[/COLOR] [URL="*www.opengroup.org/onlinepubs/009695399/functions/scanf.html"][COLOR=#000066]scanf[/COLOR][/URL][COLOR=#009900]([/COLOR][COLOR=#FF0000]"%l %l"[/COLOR][COLOR=#339933],[/COLOR] [COLOR=#339933]&[/COLOR]x[COLOR=#339933],[/COLOR] [COLOR=#339933]&[/COLOR]y[COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]   [COLOR=#B1B100]if[/COLOR][COLOR=#009900]([/COLOR]x[COLOR=#339933]>[/COLOR]y[COLOR=#009900])
[/COLOR]    [COLOR=#009900]{[/COLOR]    [URL="*www.opengroup.org/onlinepubs/009695399/functions/printf.html"][COLOR=#000066]printf[/COLOR][/URL][COLOR=#009900]([/COLOR][COLOR=#FF0000]"%l"[/COLOR][COLOR=#339933],[/COLOR]y[COLOR=#009900])[/COLOR][COLOR=#339933];[/COLOR]     [COLOR=#009900]}[/COLOR]  
  [COLOR=#B1B100]else[/COLOR]     [COLOR=#009900]{[/COLOR]     
[COLOR=#B1B100]       if[/COLOR][COLOR=#009900]([/COLOR]x [COLOR=#339933]%[/COLOR] [COLOR=#0000DD]5[/COLOR] [COLOR=#339933]==[/COLOR][COLOR=#0000DD]0[/COLOR][COLOR=#009900])[/COLOR]  
      [COLOR=#009900]{[/COLOR]         y[COLOR=#339933]=[/COLOR] y[COLOR=#339933]-[/COLOR]x [COLOR=#339933];[/COLOR]    
               y[COLOR=#339933]=[/COLOR]y[COLOR=#339933]-[/COLOR][COLOR=#800080]0.5[/COLOR][COLOR=#339933];
[/COLOR]               [URL="*www.opengroup.org/onlinepubs/009695399/functions/printf.html"][COLOR=#000066]printf[/COLOR][/URL][COLOR=#009900]([/COLOR][COLOR=#FF0000]"%l"[/COLOR][COLOR=#339933],[/COLOR] y[COLOR=#009900])[/COLOR][COLOR=#339933];
[/COLOR]     [COLOR=#009900]}[/COLOR]     
      [COLOR=#B1B100]else[/COLOR] 
       [COLOR=#009900]{[/COLOR]            [URL="*www.opengroup.org/onlinepubs/009695399/functions/printf.html"][COLOR=#000066]printf[/COLOR][/URL][COLOR=#009900]([/COLOR][COLOR=#FF0000]"%l"[/COLOR][COLOR=#339933],[/COLOR] y[COLOR=#009900])[/COLOR][COLOR=#339933];[/COLOR]                [COLOR=#009900]}[/COLOR]     
[COLOR=#009900]}
[/COLOR]     [COLOR=#009900]}[/COLOR]
It's Giving me runtime error
harshilsharma63
Jun 25, 2013 at 4:33 PM
^ At least mention the error and the input for which you are getting this error.

oops, krishnandu.sarkar's post cane beteen.
rohitshubham
Jun 25, 2013 at 11:30 PM
^ At least mention the error and the input for which you are getting this error.

oops, krishnandu.sarkar's post cane beteen.
i m running it on ideone and the input are 30 and 120 while the output is 89 which should be 89.5
krishnandu.sarkar
Jun 26, 2013 at 7:33 AM
You said it's giving you runtime error. Anyway, in that case check your logic.
rijinpk1
rijinpk1 #298
Jun 26, 2013 at 10:46 AM
Use float instead of long.

Use float instead of long.
vickybat
vickybat #301
Jun 28, 2013 at 12:01 AM
codechef gives this as a runtime error too :(

Just use float instead of long mate.

The value is getting rounded as long datatype doesn't support decimal values, just like int.
T
Jul 7, 2013 at 5:47 PM
int main() {
ifstream f("Words.cpp");
int nwords = 0;
string word;

while (f >> word)
++nwords;

cout << "Number of words = " << nwords << endl;
}
what does the thing in bold mean?
harshilsharma63
Jul 7, 2013 at 5:56 PM
what does the thing in bold mean?

Yes you can do it using string.

Code:
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
fstream file;
string line;

file.open("E:\\abc.txt", ios::in);

while(getline(file, line))
cout << line << endl;

return 0;
}
T
Jul 7, 2013 at 6:09 PM
Yes you can do it using string.

PHP:
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
fstream file;
string line;

file.open("E:\\abc.txt", [B]ios::in[/B]);

while(getline(file, line))
cout << line << endl;

return 0;
}

why php? what is ios::in??
harshilsharma63
Jul 7, 2013 at 7:00 PM
why php? what is ios::in??

Its C++ code enclosed in
PHP:
 tag. Edited it :wink:

ios::in is the file opening mode. When you open a file, you have to specify the opening mode. It can be read only, white only, append with in, out, app being their specifiers. These file openning specifiers reside in ios class (not sure if its a class), hence, the use of ios::in. If the file were to be apened for writing only, then it would be ios::out.
Chaitanya
Chaitanya #306
Jul 13, 2013 at 9:25 PM
How to use Open MP ??
kunalht
kunalht #307
Jul 28, 2013 at 3:20 PM
please suggest a C/C++ software for ubuntu (linux).
I am new to ubuntu.
So please suggest a good software with compiler with download links.
also tell me some good softwares for linux.
Chaitanya
Chaitanya #308
Jul 28, 2013 at 6:25 PM
please suggest a C/C++ software for ubuntu (linux).
I am new to ubuntu.
So please suggest a good software with compiler with download links.
also tell me some good softwares for linux.

I have no programming experience on linux tho heard it has inbuilt libs for C compilers.
You may try GCC(GNU Compiler Collection)GCC, the GNU Compiler Collection - GNU Project - Free Software Foundation (FSF)

You may try notepad++ for editing & creating codes..
nims11
nims11 #309
Jul 28, 2013 at 6:32 PM
please suggest a C/C++ software for ubuntu (linux).
I am new to ubuntu.
So please suggest a good software with compiler with download links.
also tell me some good softwares for linux.

gcc, g++, Codeblocks.
skeletor
skeletor #310
Aug 6, 2013 at 2:54 AM
Clang is the compiler of my choice these days. Error reporting is much better.
aaruni
aaruni #311
Aug 10, 2013 at 5:53 PM
Can anyone tell me why this program only prints "<year> is not a leap year." ?

Code:
/*
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;
}
Chaitanya
Chaitanya #312
Aug 21, 2013 at 11:14 PM
Can anyone tell me why this program only prints "<year> is not a leap year." ?

Code:
	cin>>year;
	limb1=year%4;
	if (limb1 == 0)
	{
		[B]limb10 = year%100;
		limb40 = year%400;[/B]
		if (limb40 == 0)

Lost there...
Why that segment??
aaruni
aaruni #313
Aug 21, 2013 at 11:38 PM
It was a logical error on my part. Corrected here : C/C++ Thread
Chaitanya
Chaitanya #314
Aug 21, 2013 at 11:49 PM
It was a logical error on my part. Corrected here : C/C++ Thread

Well you could have written program a lot smaller..
Couldn't get why you required 3 conditions while it is solved by one.

Well problem is solved & only that matters. ;-)
aaruni
aaruni #315
Aug 21, 2013 at 11:51 PM
how is it solved by a single statement ?
aaruni
aaruni #317
Aug 22, 2013 at 12:01 AM
condition of a leap year are specified in the program comments.

conditions of leap year : divisible by 4 !by 100 but by 400
Chaitanya
Chaitanya #318
Aug 22, 2013 at 12:12 AM
condition of a leap year are specified in the program comments.

conditions of leap year : divisible by 4 !by 100 but by 400

Hmm.. I see, I totally overlooked the Centurial years condition.... LOL on myself.. :-D
rohitshubham
Aug 27, 2013 at 8:19 PM
so, i was doing a code and submitting it online i encountered a problem i.e. when i submit code #1 it accepts the solution but when i try code #2 it gives wrong answer , but as far as i know, the logic is same. plz help.
code no 1:
Code:
int main(){
  int T;
  long int R;
  long int x1,y1;
  long int x2,y2;
  long int x3,y3;
  long int d1,d2,d3;
 
  scanf("%d",&T);
  while(T > 0) {
    scanf("%d",&R);
    scanf("%d %d",&x1,&y1);
    scanf("%d %d",&x2,&y2);
    scanf("%d %d",&x3,&y3);
    R = pow(R,2);
    d1 = pow((x1-x2),2) + pow((y1-y2),2);
    d2 = pow((x1-x3),2) + pow((y1-y3),2);
    d3 = pow((x2-x3),2) + pow((y2-y3),2);
    if((d1 <= R && d2 <= R) || (d2 <= R && d3 <= R) || (d1 <= R && d3 <= R)) {
      printf("yes\n");
    } else {
      printf("no\n");
    }
 
    T--;
  }  /* while */
  return 0;
}
code no 2:
Code:
int main(){   int test;
    float x1,x2,x3,y1,y2,y3,r;
    float dis1,dis2,dis3;
    cout<<"enter test cases";
    cin>>test;
    while(test--)
    {
        cin>>r>>x1>>y1>>x2>>y2>>x3>>y3;
        dis1= pow((x1-x2),2) + pow((y1-y2),2);
        dis2=pow((x2-x3),2)+ pow((y2-y3),2);
        dis3=pow((x1-x3),2)+pow((y1-y3),2);
        r=pow(r,2);
        if((dis1<=r && dis2<=r)||(dis1<=r && dis3<=r)||(dis3<=r && dis2<=r))
            cout<<"yes";
        else
            cout<<"no";


    }
    return 0;
}
Chaitanya
Chaitanya #320
Aug 27, 2013 at 10:52 PM
^^
1. in code #1 variables are long type & in #2 they are float type
2. #1 is in C & #2 is in cpp
rohitshubham
Aug 28, 2013 at 8:50 PM
^^
1. in code #1 variables are long type & in #2 they are float type
2. #1 is in C & #2 is in cpp
1. and that wont affect the output in any case... except for maybe very long integers and i have tried long datatype too :(
2. so???
Chaitanya
Chaitanya #322
Aug 29, 2013 at 9:57 PM
2. may be the place where you tried soln doesn't accept C++ code. ;-)
rohitshubham
Aug 29, 2013 at 10:57 PM
^^^nope that's not the case... it's on codechef and i have submitted quite a few programs on it
nims11
nims11 #324
Aug 30, 2013 at 1:46 PM
1. and that wont affect the output in any case... except for maybe very long integers and i have tried long datatype too :(
2. so???

When you use floats instead of long, you are compromising on precision. It is common to to have little precision error leading to wrong answer when using floats in codechef like environment...

Btw the problem in your code is something else. (Check newlines).
rohitshubham
Aug 30, 2013 at 3:48 PM
When you use floats instead of long, you are compromising on precision. It is common to to have little precision error leading to wrong answer when using floats in codechef like environment...

Btw the problem in your code is something else. (Check newlines).
ermmm....newlines???
rohitshubham
Aug 30, 2013 at 8:37 PM
^^nope still nothing...
sksksksk
sksksksk #328
Sep 11, 2013 at 3:05 PM
Code:
int main(){   int test;
    float x1,x2,x3,y1,y2,y3,r;
    float dis1,dis2,dis3;
    cout<<"enter test cases";
    cin>>test;
    [COLOR="#FF0000"][SIZE=2]while(test--)[/SIZE][/COLOR]
    {
        cin>>r>>x1>>y1>>x2>>y2>>x3>>y3;
        dis1= pow((x1-x2),2) + pow((y1-y2),2);
        dis2=pow((x2-x3),2)+ pow((y2-y3),2);
        dis3=pow((x1-x3),2)+pow((y1-y3),2);
        r=pow(r,2);
        if((dis1<=r && dis2<=r)||(dis1<=r && dis3<=r)||(dis3<=r && dis2<=r))
            cout<<"yes";
        else
            cout<<"no";
    }
    return 0;

iThis is an invalid condition. The loop won't stop, as your condition is not well defined. I dont have any idea about what your program is but you can modify the condition, according to your need! :)
harshilsharma63
Sep 11, 2013 at 3:13 PM
Code:
int main(){   int test;
    float x1,x2,x3,y1,y2,y3,r;
    float dis1,dis2,dis3;
    cout<<"enter test cases";
    cin>>test;
    [COLOR=#FF0000][SIZE=2]while(test--)[/SIZE][/COLOR]
    {
        cin>>r>>x1>>y1>>x2>>y2>>x3>>y3;
        dis1= pow((x1-x2),2) + pow((y1-y2),2);
        dis2=pow((x2-x3),2)+ pow((y2-y3),2);
        dis3=pow((x1-x3),2)+pow((y1-y3),2);
        r=pow(r,2);
        if((dis1<=r && dis2<=r)||(dis1<=r && dis3<=r)||(dis3<=r && dis2<=r))
            cout<<"yes";
        else
            cout<<"no";
    }
    return 0;

iThis is an invalid condition. The loop won't stop, as your condition is not well defined. I dont have any idea about what your program is but you can modify the condition, according to your need! :)

That is a perfectly valid condition. For non zero values, it will be evaluated as true and for zero and false.
kunalht
kunalht #330
Sep 14, 2013 at 1:55 AM
Hii
I am in 1st year in computer scinece.
But in 1st sem. there is no subject of computer in college.
C programming subject will start from 2nd sem.
I want to learn something at home now.
I am thinking to learn C language.
Should I start learning C or should i learn any other language or HtML??
I have learned C language in 12th but it was very basic & i have also watched thenewboston's C progtamming videos.
now should i learn C first or directly C++?
& also suggest me a good book for that?
How is Ansi C 6th edition by balagurusamy?
should i buy that book?
Also tell me what to learn for android & windows phone development?
vickybat
vickybat #331
Sep 14, 2013 at 2:27 AM
^^ For android development, you need to learn Java, which will show up later in your curriculum.
XML is required too and you need not worry about that now.

Now, i recommend you to buy this asap and start learning C.
It will not only help you immensely in the upcoming semester, but also make you comfortable with programming.

NewBoston videos are very good and you can watch those videos too along with reading.

P.S - Don't even think of buying that balagurysamy book.
rohitshubham
Sep 14, 2013 at 1:21 PM
^^ For android development, you need to learn Java, which will show up later in your curriculum.
XML is required too and you need not worry about that now.

Now, i recommend you to buy this asap and start learning C.
It will not only help you immensely in the upcoming semester, but also make you comfortable with programming.

NewBoston videos are very good and you can watch those videos too along with reading.

P.S - Don't even think of buying that balagurysamy book.
Why?? i find balagurusamy's book quite easily written for beginner.
vickybat
vickybat #333
Sep 14, 2013 at 1:28 PM
Why?? i find balagurusamy's book quite easily written for beginner.

It does not encourage to code imo. Same with all indian authored books including "Let Us C".
I strongly advice beginners to stay away from these as there are better materials and books out there.

"Head First C" is the best example.
N
Nue #334
Sep 14, 2013 at 3:20 PM
It does not encourage to code imo. Same with all indian authored books including "Let Us C".
I strongly advice beginners to stay away from these as there are better materials and books out there.

"Head First C" is the best example.

I agree with you. I always advise people to stay away from Balagarusamy and other Indian authors. They teach obsolete practices (like void main in C/C++ and iostream.h etc) and don't really help one in developing a programming mindset. I personally learned C from K.N King's book and I still think it's the best book on C out there. Head first series never really clicked with me but I'm always in the minority. It's a good recommendation as they don't seem to have any programming experience.
flyingcow
flyingcow #335
Sep 14, 2013 at 4:19 PM
I want to learn C, but im currently learning Visual Basic from the tutorials provided in this months digit CD (Taken from here-*www.learnvisualstudio.net/) I have already done the first 6-7 tuts. explaining the IDE and the fundamentals.
Does learning C make VB easier?? or there is no relation? I have previously learnt JAVA...please give your suggestions should I continue with VB or learn C first?
kunalht
kunalht #336
Sep 14, 2013 at 4:29 PM
IN our collage the reference book for C is ansi C by balaguruswami.
So if i buy head first C, Does it cover all the topics of balaguruswami's book?
& also tell me is head first C is good for beginners like me??
harshilsharma63
Sep 14, 2013 at 4:46 PM
IN our collage the reference book for C is ansi C by balaguruswami.
So if i buy head first C, Does it cover all the topics of balaguruswami's book?
& also tell me is head first C is good for beginners like me??

> head first will cover your entire syllabus and more.

> head first IS for beginners.
vickybat
vickybat #338
Sep 14, 2013 at 5:02 PM
IN our collage the reference book for C is ansi C by balaguruswami.
So if i buy head first C, Does it cover all the topics of balaguruswami's book?
& also tell me is head first C is good for beginners like me??

Not only your college but it was the reference book in our college too, when i was a student.
Its the default choice in all engg.colleges in India. Now we can't change that as we don't have the authority to do so.
What we can do is find better alternatives to gain effective knowledge.

Head First C covers everything and is highly recommended. You won't miss out on anything, not opting for the balagurusamy book.
You will be able to write all the programs in a snap, your teacher advises. Just trust us on this mate and get that book eyes closed.
Read and practice the problems sincerely though. :)
N
Nue #339
Sep 14, 2013 at 5:20 PM
I want to learn C, but im currently learning Visual Basic from the tutorials provided in this months digit CD (Taken from here-*www.learnvisualstudio.net/) I have already done the first 6-7 tuts. explaining the IDE and the fundamentals.
Does learning C make VB easier?? or there is no relation? I have previously learnt JAVA...please give your suggestions should I continue with VB or learn C first?

That depends on which area of programming industry you wish to enter and for what purpose you're currently learning vB. If you want to learn C simply out of intellectual curiosity or to become a better programmer then you can do it at any time...even alongside vB but I wouldn't recommend that :p Learning C won't make vB any easier. In fact, you mayfind it a bit hard to get used to the vB syntax after programming in C (note that the programming concepts and the logic remains the same regardless of the language). So I guess it really depends.
N
Nue #340
Sep 14, 2013 at 5:23 PM
IN our collage the reference book for C is ansi C by balaguruswami.
So if i buy head first C, Does it cover all the topics of balaguruswami's book?
& also tell me is head first C is good for beginners like me??
We had that book in our college too. Pretty much the same case for every Indian college. Ignore it.
Yes and probably a lot more than that.
Head first series is beginner friendly afaik.
kunalht
kunalht #341
Sep 14, 2013 at 5:57 PM
ok thank you.
Going to buy that book from flipkart.
& after completing that book, will i be able to make small games & Unreal devlopment (UDK) games??
Nerevarine
Nerevarine #342
Sep 14, 2013 at 6:12 PM
uhh.. you will find, game designing is a LARGE LARGE part of programming.. learning C is just scratching the surface..
You also might want to start with unity, if you plan on game development.. its a lot more noob friendly than UDK
kunalht
kunalht #343
Sep 14, 2013 at 10:05 PM
ok...
thanks for help.
ordered head first C from flipkart...
rohitshubham
Sep 14, 2013 at 11:27 PM
It does not encourage to code imo. Same with all indian authored books including "Let Us C".
I strongly advice beginners to stay away from these as there are better materials and books out there.

"Head First C" is the best example.
yup, you are correct, they do not encourage to code...and their motive is mainly to teach students how to use syntax of the language...
however i feel that indian authors are more relevant for most of the students.. you see the level of english they use for explaining is kinda tough for most of the indian students while the indian authors write in plain english only few students can understand foreign authors easily or else they are very elaborate and most of the students don't have time for that much research ...this is the case for many books like physics/chem/electronics etc.
BTW have you read "C++ object oriented programming by debasis jana"... i am currently reading it along with "thinking in C++"... its a good read although a bit technical approach has been followed in former one...
vickybat
vickybat #345
Sep 15, 2013 at 12:10 AM
yup, you are correct, they do not encourage to code...and their motive is mainly to teach students how to use syntax of the language...
however i feel that indian authors are more relevant for most of the students.. you see the level of english they use for explaining is kinda tough for most of the indian students while the indian authors write in plain english only few students can understand foreign authors easily or else they are very elaborate and most of the students don't have time for that much research ...this is the case for many books like physics/chem/electronics etc.
BTW have you read "C++ object oriented programming by debasis jana"... i am currently reading it along with "thinking in C++"... its a good read although a bit technical approach has been followed in former one...

Well rohit that is a plain misconception. There is nothing like plain and advanced english. It depends on the author how lucrative and simple he can be while presenting the stuff along with some solid and real life examples. This is where Indian authors mostly fail and always rely on same old "toy programs". At least i feel that way. Well about other subjects, its a different story as the curriculum are mostly different. For computer science subjects, its best to avoid Indian authors, unless a real gem is discovered. Till now, it hasn't been, atleast i haven't seen one.

I'm not a C++ programmer but Java and have followed head first java, Core Java (Cay Horstmann) , Data Structures in Java (Robert Lafore) and also planning to read Effective Java (Joshua Bloch).
I couldn't find a single Indian authored Java book that can hold a candle to the ones mentioned above.

About C++, "thinking in c++" by Bruce Eckel is one of the best books out there afaik. He has also authored thinking in java, but i never followed it.
Can't comment on the c++ book you mentioned cause of the reasons mentioned above (me not being a c++ programmer).

For a C++ absolute beginner planning to get hold of the syntax and trying to delve into the world of oop for the first time, the following is a great choice imo.
Its very very simple and is perfect for engg. students to pass semester exams with good marks and grades. It has lots and lots of examples with line by line explanation. Very effective for students who don't have time to spend more towards coding due to pressure from other subjects in a semester.

*pearson.vrvbookshop.com/book/learning-c-programming-concepts-sham-tickoo/9788131716533

ok...
thanks for help.
ordered head first C from flipkart...

Congrats mate :). Getting hold of the syntax alone is not enough to be an effective programmer but rigorous practice.
That is the only way to be a good programmer and there are no shortcuts here.

Happy coding and keep practicing.
kunalht
kunalht #346
Sep 15, 2013 at 7:09 PM
yes!! :razz:

& which IDE should I use?
dev c++ or code blocks or any other?
In our college, they still use TC but it's not supported in my windows 8 and also it is very old.
which should i use?
& if i use notepad++, then how to compile & run c program?
vickybat
vickybat #347
Sep 15, 2013 at 11:01 PM
yes!! :razz:

& which IDE should I use?
dev c++ or code blocks or any other?
In our college, they still use TC but it's not supported in my windows 8 and also it is very old.
which should i use?
& if i use notepad++, then how to compile & run c program?

Use code blocks eyes closed and avoid TC at all costs.

Notepad++ is a text editor and not a compiler. You can use it to highlight the code to understand it better before moving to the IDE.
You can directly code in code blocks editor too.
Mr.Kickass
Mr.Kickass #348
Sep 15, 2013 at 11:03 PM
TC is crap. Get codeblocks
Nerevarine
Nerevarine #349
Sep 15, 2013 at 11:05 PM
another +1 from my side towards codeblocks.. Your school may force you to use TC but stay adamant and use codeblocks, atleast in your own pc
kunalht
kunalht #350
Sep 15, 2013 at 11:23 PM
yes...
& thanks for help...

{
printf("thank you!");
}
rohitshubham
Sep 15, 2013 at 11:51 PM
yes!! :razz:

& which IDE should I use?
dev c++ or code blocks or any other?
In our college, they still use TC but it's not supported in my windows 8 and also it is very old.
which should i use?
& if i use notepad++, then how to compile & run c program?
TC is vintage.....code::blocks is the best one out there and i use it myself... In fact my college now recommend code::blocks due to excessive lobbying by me ... actually they used devC++ and i literally forced them to move out of that though devc++ is fine enough for semester exams.
Mr.Kickass
Mr.Kickass #352
Sep 16, 2013 at 12:18 AM
Python coders should try to Learn C The Hard Way
rohitshubham
Sep 16, 2013 at 5:17 PM
can someone please explain me operator overloading with a simple program...i mean explain the program too as how it is working...
ashs1
ashs1 #354
Sep 24, 2013 at 9:00 PM
hi Guys.. I have just started learning the C program recently. Teachers have advised me to go for books from balaguruswamy & "c in depth" by shrivastva. Judging from some of the previous posts, it looks like most of you guys prefer to stay away from it. Can you guys suggest a good book for beginners ? This is the first time i am learning a programming language. :)
Thanks.
harshilsharma63
Sep 24, 2013 at 10:10 PM
"head first c". End of story.
dashing.sujay
Sep 24, 2013 at 10:27 PM
No, better start with head first programming. Head first C misses too much on basics.
gameranand
gameranand #357
Sep 29, 2013 at 11:18 AM
Object Oriented Programming in C++ from Robert Lafore is also good book.
harshilsharma63
Sep 29, 2013 at 11:41 AM
can someone please explain me operator overloading with a simple program...i mean explain the program too as how it is working...

Do you understand the concept of function overloading? Operator overloading is similar to that, but with a few constraints:

> You cannot define new operators.
> You cannot change the precedence and priority of operators.
> You cannot change the arity of operators.


Just like a function call, a reference to the object which invokes the operator is implicitelly passed to the operator bosy. This reference is called the 'this' operator and it can be used to access the object which invoked the operator.



this will return an error because no definitation of the plus operator is defined for class a and class b;

Code:
#include <iostream>
class a
{...};   //skipping the class definition

class b
{...};   //skipping the class definition

int main()
{
a obj1;
b obj2;
cout << obj1 + obj2;

return 0;
}


Code with overloaded operator
Code:
#include <iostream>
class a
{public:
int num;

friend int operator +(b obj2);
};

class b
{public:
int num;
};

int operator +(b obj2
{
    return (this.num + obj.num);
}

int main()
{
a obj1;
b obj2;
cout << obj1 + obj2;

return 0;
}

Here, 'a' is invoking the 'operator +'. However, the if I wrode b+a instead of a+b, it would still crash as it would be 'b''s responsibility to invoke the + operator, but no definition of + exists for class b.
rohitshubham
Sep 29, 2013 at 1:20 PM
Do you understand the concept of function overloading? Operator overloading is similar to that, but with a few constraints:

> You cannot define new operators.
> You cannot change the precedence and priority of operators.
> You cannot change the arity of operators.


Just like a function call, a reference to the object which invokes the operator is implicitelly passed to the operator bosy. This reference is called the 'this' operator and it can be used to access the object which invoked the operator.



this will return an error because no definitation of the plus operator is defined for class a and class b;

Code:
#include <iostream>
class a
{...};   //skipping the class definition

class b
{...};   //skipping the class definition

int main()
{
a obj1;
b obj2;
cout << obj1 + obj2;

return 0;
}


Code with overloaded operator
Code:
#include <iostream>
class a
{public:
int num;

friend int operator +(b obj2);
};

class b
{public:
int num;
};

int operator +(b obj2
{
    return (this.num + obj.num);
}

int main()
{
a obj1;
b obj2;
cout << obj1 + obj2;

return 0;
}

Here, 'a' is invoking the 'operator +'. However, the if I wrode b+a instead of a+b, it would still crash as it would be 'b''s responsibility to invoke the + operator, but no definition of + exists for class b.
thanx. :)
Nerevarine
Nerevarine #360
Nov 20, 2013 at 11:24 PM
Code:
#include <stdio.h>
int main()
{   
    char C [3][3];
    int C1[3][3];
    
    int i, j; int m[8];int n=0; int k=0;
    int trigger=0;
    void check()
    {
        for(i=0;i<9;i++)
        {
            m[i]=0;
        }
        for(i=0;i<3;i++)//ACROSS ADD
            {
                for(j=0;j<3;j++)
                    {
                        m[i]=m[i]+C1[i][j];
                    }
            }
        for(i=0;i<3;i++)//DOWN ADD
            {
                for(j=0;j<3;j++)
                    {
                        m[i+3]=m[i+3]+C1[j][i];
                    }
            }
        //DIAGONALS ADD
        m[6]=C1[0][0]+C1[1][1]+C1[2][2];
        m[7]=C1[0][2]+C1[1][1]+C1[2][0];
        
        for(i=0;i<8;i++)
            {
                if(m[i]==3)
                    {trigger=1;
                    }
                if(m[i]==6)
                    {trigger=2;
                    }
            }
        
    }
    void display()
    {
        printf("\nState of Game:\n");
        for(i=0;i<3;i++)
         {
             for(j=0;j<3;j++)
                {
                    printf("%c  ",C[i][j]);
                }
            printf("\n");
         }
    }
    printf("Welcome to my Tic Tac Toe game\n");
    while(k<9)
    {   if(n%2==0)
        {
        printf("\nPlayer 1 Input : X at desired index location");
        printf("\ni:");
        scanf("%d",&i);
        printf("\nj:");
        scanf("%d",&j);
        C[i][j]='X';
        C1[i][j]=1;
        //CHECK
        display();
        check();
        n++;
        if(trigger==1)
          {
              printf("Player 1 wins");
              break;
          }
        }
        if(n%2==1)
        {
        printf("\nPlayer 2 Input : X at desired index location");
        printf("\ni:");
        scanf("%d",&i);
        printf("\nj:");
        scanf("%d",&j);
        C[i][j]='O';
        C1[i][j]=2;

        //CHECK
        display();
        check();
        n++;
        if(trigger==2)
          {   printf("Player 2 wins"); 
              break;
          }
        }
        k++;
    }
    return(0);
}
pls check for run time error..
its a basic 2 player tic tac toe program
rohitshubham
Nov 21, 2013 at 1:02 AM
^^what compiler are you using coz it's showing error on my GCC compiler as i am pretty sure it's due to the fact that function definitions are not allowed inside the main() function.
krishnandu.sarkar
Nov 21, 2013 at 6:55 AM
Code:
#include <stdio.h>
int main()
{   
    char C [3][3];
    int C1[3][3];
    
    int i, j; int m[8];int n=0; int k=0;
    int trigger=0;
    void check()
    {
        for(i=0;i<9;i++)
        {
            m[i]=0;
        }
        for(i=0;i<3;i++)//ACROSS ADD
            {
                for(j=0;j<3;j++)
                    {
                        m[i]=m[i]+C1[i][j];
                    }
            }
        for(i=0;i<3;i++)//DOWN ADD
            {
                for(j=0;j<3;j++)
                    {
                        m[i+3]=m[i+3]+C1[j][i];
                    }
            }
        //DIAGONALS ADD
        m[6]=C1[0][0]+C1[1][1]+C1[2][2];
        m[7]=C1[0][2]+C1[1][1]+C1[2][0];
        
        for(i=0;i<8;i++)
            {
                if(m[i]==3)
                    {trigger=1;
                    }
                if(m[i]==6)
                    {trigger=2;
                    }
            }
        
    }
    void display()
    {
        printf("\nState of Game:\n");
        for(i=0;i<3;i++)
         {
             for(j=0;j<3;j++)
                {
                    printf("%c  ",C[i][j]);
                }
            printf("\n");
         }
    }
    printf("Welcome to my Tic Tac Toe game\n");
    while(k<9)
    {   if(n%2==0)
        {
        printf("\nPlayer 1 Input : X at desired index location");
        printf("\ni:");
        scanf("%d",&i);
        printf("\nj:");
        scanf("%d",&j);
        C[i][j]='X';
        C1[i][j]=1;
        //CHECK
        display();
        check();
        n++;
        if(trigger==1)
          {
              printf("Player 1 wins");
              break;
          }
        }
        if(n%2==1)
        {
        printf("\nPlayer 2 Input : X at desired index location");
        printf("\ni:");
        scanf("%d",&i);
        printf("\nj:");
        scanf("%d",&j);
        C[i][j]='O';
        C1[i][j]=2;

        //CHECK
        display();
        check();
        n++;
        if(trigger==2)
          {   printf("Player 2 wins"); 
              break;
          }
        }
        k++;
    }
    return(0);
}
pls check for run time error..
its a basic 2 player tic tac toe program

#1 Function should be declared above
#2 Function definition should be outside main()
#3 Call the function inside main()
icebags
icebags #363
Nov 30, 2013 at 4:01 PM
I have not been in touch woth c / c++ for a long time, but need a solution for this. Googling kinda confusing me....
Need to add a few stings/ character variables into a new string variable. How can this be done?
rijinpk1
rijinpk1 #364
Nov 30, 2013 at 5:13 PM
I have not been in touch woth c / c++ for a long time, but need a solution for this. Googling kinda confusing me....
Need to add a few stings/ character variables into a new string variable. How can this be done?

can you elaborate a little more. i think what you want is to concatenate two strings by using strcat function.
harshilsharma63
Nov 30, 2013 at 5:20 PM
I have not been in touch woth c / c++ for a long time, but need a solution for this. Googling kinda confusing me....
Need to add a few stings/ character variables into a new string variable. How can this be done?

with arrays:

Code:
    char str1[] = "Hello ";
    char str2[] = "World!";
    char str3[30];
    strcat (str, str1);
    strcat (str, str2);

    cout << str;

with pointers:

Code:
    char *str1 = "hello ";
    char *str2 = "world!";
    char *str3;

    str3 = (char*)malloc( strlen(str1) + strlen(str2) + 1 );
    
    strcpy(str3, str1);
    strcat(str3, str2);

    cout << str3;

with 'string':

Code:
    string str1 = "hello ";
    string str2 = "world!";
    string str3;

    str3 = str1 + str2;
    cout << str3;

You can also implement a concat function manually or overload the '+' operator manually;
icebags
icebags #366
Nov 30, 2013 at 7:29 PM
thanks for the quick reply, i just forgot to mention that i have to concat a number (int/float) with it as well, it would be better if the number can be formatted in something like 00.00, i.e. if its 5.6 then it should show like 05.60 .

thanks again, please pardon my mistake. :D

can you elaborate a little more. i think what you want is to concatenate two strings by using strcat function.

well i was trying to concat with +, but i think it didn't work, i m gonna try with harsil said methods one by one.

i am trying to program in arduino environment, where there could be some restrictions and everything may not work like a standard c/c++ program. i need to see.
harshilsharma63
Dec 1, 2013 at 1:48 PM
thanks for the quick reply, i just forgot to mention that i have to concat a number (int/float) with it as well, it would be better if the number can be formatted in something like 00.00, i.e. if its 5.6 then it should show like 05.60 .

thanks again, please pardon my mistake. :D



well i was trying to concat with +, but i think it didn't work, i m gonna try with harsil said methods one by one.

i am trying to program in arduino environment, where there could be some restrictions and everything may not work like a standard c/c++ program. i need to see.

If you are working with C++, you can overload the plus operator to concatenate strings.
icebags
icebags #368
Dec 2, 2013 at 4:18 AM
arduino accepting arrays and pointers methods, but it doesn't recognize string as datatype.

any suggestion on concatenating numbers and numeric variables with strings ?
rijinpk1
rijinpk1 #369
Dec 2, 2013 at 10:29 AM
arduino accepting arrays and pointers methods, but it doesn't recognize string as datatype.

any suggestion on concatenating numbers and numeric variables with strings ?

arduino program is simply java, right? you can use any java ide ,i guess. else you may have to declare an integer array and convert characters to corresponding ASCII values and store it on the integer array and display it using a single quote which should print characters.
harshilsharma63
Dec 2, 2013 at 10:40 AM
arduino accepting arrays and pointers methods, but it doesn't recognize string as datatype.

any suggestion on concatenating numbers and numeric variables with strings ?

Which language are you using, C or C++?
icebags
icebags #371
Dec 2, 2013 at 9:22 PM
arduino program is simply java, right? you can use any java ide ,i guess. else you may have to declare an integer array and convert characters to corresponding ASCII values and store it on the integer array and display it using a single quote which should print characters.

the ide is build with java alright. i am gonna try what u said, but is this the normal way? i think there was something like typecasting ? *l.yimg.com/us.yimg.com/i/mesg/emoticons7/39.gif

Which language are you using, C or C++?

u can take it i am basically using C. but the ide supports some C++ stuff as it says here :
Frequently Asked Questions

if u want to try u can get it here.
ashs1
ashs1 #372
Dec 3, 2013 at 9:04 PM
hi guys..need a small help..
we have C language in our college course
Unfortunately, i was absent when they taught us pointers, structure, union,..
Though i got through the exam somehow, now we have practicals this week( viva too) & we also have c++ in next sem.
Can you guys suggest any sites which can help me easily understand pointers, structure, union ??
I am just a beginner on C, so if possible, please suggest those sites which can help me understand these concepts easily ( i am fairly thorough in looping now. :) )

Thanks. :)
quagmire
quagmire #373
Dec 4, 2013 at 5:48 PM
^
D
db22 #374
Jan 2, 2014 at 12:48 PM
guys i need c and c++ compilers.. my email id is dpnkrborah@gmail.com...it would of great help if u send me the files or provide me with links to download the compilers from
flyingcow
flyingcow #375
Jan 9, 2014 at 10:36 PM
I am building a calculator in c++ i am not building it via using functions
i want to display "invalid selection" if the user types in anything other than 1,2,3,4 as his selection
i tried
if(selection==1)
{xyz}
else
cout<<"Invalid chooice";
if (selection== 2)
{xyzz}
else
cout<<"invalid seklection";
but it isnt working... i also tried
if()
{xyz}
if()
{xyz}
then putting in cout
and also tried
if{
if()
{}
if()
{}
}
else
cout
help..
#include <iostream>
using namespace std;
//my first program(C++) CALCULATOR v1.0.0
int main()
{
float x, y, z, sum, prod, div, sub;
cout<<"Prototype Calculator v 1.0.0\n\n";
cout<<"Select the type of calculation you want to perform:\n";
cout<<"1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n";
int selection;
cin>>selection;

if (selection==1){
cout<<"Enter the first number\n";
cin>>x;
cout<<"Enter the second number\n";
cin>>y;
sum=x+y;
cout<<"Sum= "<<sum;
}

if(selection==4){
cout<<"Enter the first number\n";
cin>>x;
cout<<"Enter the second number\n";
cin>>y;
div=x/y;
cout<<"Division= "<<div;
}

if(selection==3){
cout<<"Enter the first number\n";
cin>>x;
cout<<"Enter the second number\n";
cin>>y;
prod=x*y;
cout<<"Product= "<<prod;}

if(selection==2){
cout<<"Enter the first number\n";
cin>>x;
cout<<"Enter the second number\n";
cin>>y;
sub=x-y;
cout<<"Subtraction= "<<sub;}


}
Vyom
Vyom #376
Jan 9, 2014 at 11:49 PM
^^ You haven't written the code for the selection *not* being equal to 1,2,3 or 4.
You can use any method to make a condition that if selection is not from 1 to 4 then display "Invalid selection".

guys i need c and c++ compilers.. my email id is dpnkrborah@gmail.com...it would of great help if u send me the files or provide me with links to download the compilers from

*www.codeblocks.org/downloads
flyingcow
flyingcow #377
Jan 10, 2014 at 12:05 AM
^^ You haven't written the code for the selection *not* being equal to 1,2,3 or 4.
You can use any method to make a condition that if selection is not from 1 to 4 then display "Invalid selection".
so i have to write
if(selection !==1&& !==2 && !==3 && !==4)
{
cout<<"Invalid selection";
}
??

EDIT: Thanks vyom, i got it working
also i have another question, i am making a rock paper scissors game and the code currently is
#include <iostream>

using namespace std;

int main()

{
int choice;
cout << "*-Welcome to the unfair Rock-Paper-Scissors game-*\nYou will always lose!!\n" << endl;
cout<<"Select your move:\n\n1.Rock 2.Paper 3.Scissor\n";
cin>>choice;
if (choice==1)
{cout<<"The computer has selected PAPER\n YOU LOSE";}
if (choice==2)
{cout<<"The computer has selected SCISSORS\n YOU LOSE";}
if (choice==3)
{cout<<"The computer has selected ROCK\n YOU LOSE";}
if (choice!=1 && choice!=2 && choice!=3)
cout<<"Invalid Choice";
return 0;
}

i want to make it so that the computer plays random moves, i.e it selects at random, how can i do thqat>?? i just want a code to generate random code, then i will use array to put "a[random digit]" as the computer chice
rohitshubham
Jan 11, 2014 at 4:15 PM
so i have to write
if(selection !==1&& !==2 && !==3 && !==4)
{
cout<<"Invalid selection";
}
??

EDIT: Thanks vyom, i got it working
also i have another question, i am making a rock paper scissors game and the code currently is
#include <iostream>

using namespace std;

int main()

{
int choice;
cout << "*-Welcome to the unfair Rock-Paper-Scissors game-*\nYou will always lose!!\n" << endl;
cout<<"Select your move:\n\n1.Rock 2.Paper 3.Scissor\n";
cin>>choice;
if (choice==1)
{cout<<"The computer has selected PAPER\n YOU LOSE";}
if (choice==2)
{cout<<"The computer has selected SCISSORS\n YOU LOSE";}
if (choice==3)
{cout<<"The computer has selected ROCK\n YOU LOSE";}
if (choice!=1 && choice!=2 && choice!=3)
cout<<"Invalid Choice";
return 0;
}

i want to make it so that the computer plays random moves, i.e it selects at random, how can i do thqat>?? i just want a code to generate random code, then i will use array to put "a[random digit]" as the computer chice
use the rand() function present in <cstdlib>
int m = rand() % 3; will produce random value between 0 and 2
imt m = rand() % 3+1; will produce random values between 1 and 3
flyingcow
flyingcow #379
Jan 11, 2014 at 4:55 PM
use the rand() function present in <cstdlib>
int m = rand() % 3; will produce random value between 0 and 2
imt m = rand() % 3+1; will produce random values between 1 and 3

thanks,i searched and found a rand() function but it gave a large value so i did %4 and it always gave me 3...
i will try doing the 3+1 thing, thank you :)
harshilsharma63
Jan 12, 2014 at 2:09 PM
thanks,i searched and found a rand() function but it gave a large value so i did %4 and it always gave me 3...
i will try doing the 3+1 thing, thank you :)

There are two methods for getting pseudo random numbers withing a range not starting from 1:

method 1:

MIN + (rand() % (MAX - MIN + 1 ))

method 2:

Code:
#include <iostream>
#include <random>
int main()
{
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 eng(rd()); // seed the generator
    std::uniform_int_distribution<> distr(25, 63); // define the range

    for(int n=0; n<40; ++n)
        std::cout << distr(eng) << ' '; // generate numbers
}

method 2 is the modern, preferred approach.

Source: Random number c++ in some range - Stack Overflow
flyingcow
flyingcow #381
Jan 14, 2014 at 6:49 PM
^thanks :)
can anyone suggest a goo begginners c++ book? our colege book sucks...
harshilsharma63
Jan 15, 2014 at 4:32 PM
You can try 'head first' series if you are aware of basic programing concepts.
flyingcow
flyingcow #383
Jan 15, 2014 at 4:53 PM
You can try 'head first' series if you are aware of basic programing concepts.
id like to read a book explaining basics too, i saw let us c++ but the reviews stated that it was sh!t and gave wrong info
skeletor
skeletor #384
Jan 15, 2014 at 8:16 PM
Buy this - C++ Primer book : Josee Lajoie, 8131775275, 9788131775271 - BookAdda.com India

Out of stock on Flipkart.
flyingcow
flyingcow #385
Jan 15, 2014 at 8:31 PM
Buy this - C++ Primer book : Josee Lajoie, 8131775275, 9788131775271 - BookAdda.com India

Out of stock on Flipkart.
thanks, is the book good for beginners? and what about the site? ill ask in some local shops...
skeletor
skeletor #386
Jan 15, 2014 at 8:38 PM
thanks, is the book good for beginners? and what about the site? ill ask in some local shops...
yup, the best book for beginners infact. It's a no nonsense book. Not a fancy one like Head First.
flyingcow
flyingcow #387
Jan 15, 2014 at 9:31 PM
yup, the best book for beginners infact. It's a no nonsense book. Not a fancy one like Head First.
ok thanks seems like the site has cod, ty again
M
Feb 3, 2014 at 12:14 PM
I think above is a thread that actually suits the content of the same. Programming is nothing but a set of commands created by a developer which is then coded into the machine so that the machine performs a set of tasks depending on user inputs or independently. such a fine post it is.
nims11
nims11 #389
Feb 3, 2014 at 5:01 PM
I think above is a thread that actually suits the content of the same. Programming is nothing but a set of commands created by a developer which is then coded into the machine so that the machine performs a set of tasks depending on user inputs or independently. such a fine post it is.

This statement is as abstract as "Mathematics is all about addition and subtraction"
vickybat
vickybat #390
Feb 3, 2014 at 8:24 PM
thanks, is the book good for beginners? and what about the site? ill ask in some local shops...

Get this:

OBJECT ORIENTED PROGRAMMING IN C++ 4ED 4 Edition - Buy OBJECT ORIENTED PROGRAMMING IN C++ 4ED 4 Edition by Robert Lafore Online at Best Prices in India - Flipkart.com
A
a.ravi #391
Feb 27, 2014 at 8:17 PM
Can any one tell me, how i can perform file operations copy, move in C??
May i know the compiler ua using?if ua using linux interface u can have the copy of the program by following steps:
1.from the editor press escape
2.then press shift+:(colon)
3.type wq then leave a space and give the new name to which u want to copy.
4.Press enter
now u can open the new file which has been copied.
ex: wq newname.cpp
A
a.ravi #392
Mar 1, 2014 at 9:41 AM
Go for C++ complete reference by Herbert schildt
V
Vignesh B #393
Mar 3, 2014 at 8:08 PM
What's the maximum number of if-else statements allowed in C++?
aaruni
aaruni #394
Mar 3, 2014 at 8:20 PM
What's the maximum number of if-else statements allowed in C++?

if-else ladder you mean? the deepest level in an if-else ladder?

because, I think there may be a limit in the if-else ladder, but otherwise, there may be infinite number of uses of if-else...
V
Vignesh B #395
Mar 3, 2014 at 11:32 PM
if-else ladder you mean? the deepest level in an if-else ladder?

because, I think there may be a limit in the if-else ladder, but otherwise, there may be infinite number of uses of if-else...
I didn't mean the if-else ladder. I just asked about the maximum number of uses of if-else in a program. I remember reading somewhere about the limit.
Since you pointed it out am also curious to know the deepest level in an if-else ladder.
nims11
nims11 #396
Mar 4, 2014 at 10:09 PM
there is no such limit on number of if-else or depth of if-else imposed by the C language specification.
G
gigyaster #397
Apr 16, 2014 at 11:45 PM
okay, a new question in here.

I want to convert a decimal number to binary and store it in a string so that I can use that binary output for later computation. Here is what I did

Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
    int num; char i=0,j; char a[11]={0,0,0,0,0,0,0,0,0,0,'\0'};
    char string[11];
    printf("\nEnter the decimal number\n"); scanf("%d",&num);
    while(num>0)
    {
        a[i]=num%2;
        i++;
        num=num/2;
    }
    printf("\nThe Binary equivalent is\n");
    for(j=9;j>=0;j--)
    {
        printf("%d",a[j]);
    }
    


}

Now as you can see that all the binary output is in a[] but how do I get it into a string so that I can use printf("%s",string) and get the binary output ?
Neuron
Neuron #398
Apr 17, 2014 at 7:11 AM
okay, a new question in here.

I want to convert a decimal number to binary and store it in a string so that I can use that binary output for later computation. Here is what I did

Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
    int num; char i=0,j; char a[11]={0,0,0,0,0,0,0,0,0,0,'\0'};
    char string[11];
    printf("\nEnter the decimal number\n"); scanf("%d",&num);
    while(num>0)
    {
        a[i]=num%2;
        i++;
        num=num/2;
    }
    printf("\nThe Binary equivalent is\n");
    for(j=9;j>=0;j--)
    {
        printf("%d",a[j]);
    }
    


}

Now as you can see that all the binary output is in a[] but how do I get it into a string so that I can use printf("%s",string) and get the binary output ?

The quickest way to do this is to add 48 to the contents of the int array to get the ascii equivalent char value of that digit. For example, '1' 's ascii value is 49. Add 48 to 1 and store it in the char array. Or you can use switch-case statements to individually put the ascii value of digits into arrays.
RBX
RBX #399
Apr 18, 2014 at 1:32 PM
[C++]

In a method, I have a pointer to a node, how do I set node to NULL using that pointer?
Also, can only use delete(), and not free().

Edit: Precisely, I need to delete root of tree, but when it's the last element, it doesn't work because tree's class always has a pointer to it.

Edit: In this root is accessible directly since it's in a friend class and I'm using iterative approach, so I just checked if it was root and a leaf and then set it to NULL.
rohitshubham
Apr 19, 2014 at 12:52 AM
[C++]

In a method, I have a pointer to a node, how do I set node to NULL using that pointer?
Also, can only use delete(), and not free().

Edit: Precisely, I need to delete root of tree, but when it's the last element, it doesn't work because tree's class always has a pointer to it.

Edit: In this root is accessible directly since it's in a friend class and I'm using iterative approach, so I just checked if it was root and a leaf and then set it to NULL.
i am sorry , i am not getting your question..are you making threaded tree? coz you're saying you root node always has a pointer to it;
BTW if you want to set the value NULL if method has been called by pointer to pointer(void abc(node **,int))then you could set the value of node such as tree_1 as NULL by using (*tree_1)->left=NULL ; which i guess is not the question you are asking.
RBX
RBX #401
Apr 19, 2014 at 2:27 PM
i am sorry , i am not getting your question..are you making threaded tree? coz you're saying you root node always has a pointer to it;
BTW if you want to set the value NULL if method has been called by pointer to pointer(void abc(node **,int))then you could set the value of node such as tree_1 as NULL by using (*tree_1)->left=NULL ; which i guess is not the question you are asking.

This was the code to be prefixed, I had to design methods around it. Although recursive methods could be designed, I decided to make iterative ones.
Code:
#include <iostream>

using namespace std;

class binarySearchTree;
class treeNode{
    /*
    *with the following friend declaration
    *binarySearchTree class can also access private members of treeNode
    */
    friend class binarySearchTree;
    private:
        int data;
        treeNode * left;
        treeNode * right;
    
    public:
        treeNode(){
            left=right=NULL;
            //parent = NULL;
        }
        treeNode(int key){
            data=key;
            left=right=NULL    ;
            //parent=NULL;
        }
        int getData(){ return data;}
        void setData(int key){data=key;}
};

class binarySearchTree{
    private:
        treeNode * root;
    public:
        binarySearchTree(){root=NULL;}

/*THE ABOVE CODE WILL BE ADDED AS PREFIX TO YOUR CODE**/
/*Finish The Implementation of the binarySearchTree Class*/

This is how I implemented delete (seems to be quite a bad implementation, I'll try to improve it).

Code:
void binarySearchTree::remove(int val) {
    treeNode* temp = root;
    treeNode* tempParent = NULL;    //needs to be tracked so that parent doesn't point to a deleted node

    

    //find the node to be deleted
    if (temp != NULL) {
        while (temp->data != val) {
            if (val < temp->data) {
                tempParent = temp;    //new changes for parent
                temp = temp->left;
            } else if (val > temp->data) {
                tempParent = temp;    //new changes for parent
                temp = temp->right;
            }
        }
    }

    //if leaf node
    if (temp->left == NULL && temp->right == NULL) {
        if (tempParent != NULL) {
            if (temp->data < tempParent->data) tempParent->left = NULL;
            else if (temp->data > tempParent->data) tempParent->right = NULL;
        }
        
       [B] if (temp == root) root = NULL;
        delete(temp);
        temp = NULL;[/B]
        return;
    }

    //if not a leaf node
    //find the replacement node
    treeNode* replace = temp;
    treeNode* replaceParent = NULL;    //needs to be tracked so that childen of replacement can be attached to it
    if (temp->left != NULL) {    //find largest element in left subtree
        replaceParent = replace;
        replace = replace->left;
        while (replace->right != NULL) {
            replaceParent = replace;
            replace = replace->right;
        }

        temp->data = replace->data;    //make replacement
        
        //test
        if (replaceParent != temp) {
            if (replace->left != NULL)    //if replacement is not a leaf node
                replaceParent->right = replace->left;    //attach left-children of replacement to its parent
            else
                replaceParent->right = NULL;    //now parent won't point to the deleted child(replace)
        }

        ////if replacement is a leaf node, replace->left is NULL, so this *should* work in both cases(leaf/non-leaf)
        //replaceParent->right = replace->left;
        if (replaceParent->left == replace) replaceParent->left = replace->left;

        delete(replace);
        replace = NULL;

    } else if (temp->right != NULL) {    //find smallest element in right subtree
        replaceParent = replace;
        replace = replace->right;
        while (replace->left != NULL) {
            replaceParent = replace;
            replace = replace->left;
        }

        temp->data = replace->data;

        if (replaceParent != temp) {
            if (replace->right != NULL)    //if replacement is not a leaf node
                replaceParent->left = replace->right;    //attach right-children of replacement to its parent
            else
                replaceParent->left = NULL;    //now parent won't point to the deleted child(replace)
        }

        ////if replacement is a leaf node, replace->right is NULL, so this *should* work in both cases(leaf/non-leaf)
        //replaceParent->right = replace->left;
        if (replaceParent->right == replace) replaceParent->right = replace->right;




        //replaceParent->left = replace->right;
        delete(replace);
        replace = NULL;
    }

    /**abandoned**/
    /*
    //replace
    if (replace == temp) {    //No replacement found    //leaf node
        free(temp);
        free(replace);
    } else {
        if (replace->data > temp->data) {    //largest in left subtree
            temp->data = replace->data;
            if (replace->left != NULL) {    //if the replacement had left children

            }
        }
    }
    */
}

As can be seen root is a member of BST class, so delete(temp) would just set root to some garbage value, and then if I do temp = NULL, it would just make temp point to NULL, not set root to NULL, so I have to set root to NULL in this dirty way.
rohitshubham
Apr 19, 2014 at 11:23 PM
This was the code to be prefixed, I had to design methods around it. Although recursive methods could be designed, I decided to make iterative ones.
Code:
#include <iostream>

using namespace std;

class binarySearchTree;
class treeNode{
    /*
    *with the following friend declaration
    *binarySearchTree class can also access private members of treeNode
    */
    friend class binarySearchTree;
    private:
        int data;
        treeNode * left;
        treeNode * right;
    
    public:
        treeNode(){
            left=right=NULL;
            //parent = NULL;
        }
        treeNode(int key){
            data=key;
            left=right=NULL    ;
            //parent=NULL;
        }
        int getData(){ return data;}
        void setData(int key){data=key;}
};

class binarySearchTree{
    private:
        treeNode * root;
    public:
        binarySearchTree(){root=NULL;}

/*THE ABOVE CODE WILL BE ADDED AS PREFIX TO YOUR CODE**/
/*Finish The Implementation of the binarySearchTree Class*/

This is how I implemented delete (seems to be quite a bad implementation, I'll try to improve it).

Code:
void binarySearchTree::remove(int val) {
    treeNode* temp = root;
    treeNode* tempParent = NULL;    //needs to be tracked so that parent doesn't point to a deleted node

    

    //find the node to be deleted
    if (temp != NULL) {
        while (temp->data != val) {
            if (val < temp->data) {
                tempParent = temp;    //new changes for parent
                temp = temp->left;
            } else if (val > temp->data) {
                tempParent = temp;    //new changes for parent
                temp = temp->right;
            }
        }
    }

    //if leaf node
    if (temp->left == NULL && temp->right == NULL) {
        if (tempParent != NULL) {
            if (temp->data < tempParent->data) tempParent->left = NULL;
            else if (temp->data > tempParent->data) tempParent->right = NULL;
        }
        
       [B] if (temp == root) root = NULL;
        delete(temp);
        temp = NULL;[/B]
        return;
    }

    //if not a leaf node
    //find the replacement node
    treeNode* replace = temp;
    treeNode* replaceParent = NULL;    //needs to be tracked so that childen of replacement can be attached to it
    if (temp->left != NULL) {    //find largest element in left subtree
        replaceParent = replace;
        replace = replace->left;
        while (replace->right != NULL) {
            replaceParent = replace;
            replace = replace->right;
        }

        temp->data = replace->data;    //make replacement
        
        //test
        if (replaceParent != temp) {
            if (replace->left != NULL)    //if replacement is not a leaf node
                replaceParent->right = replace->left;    //attach left-children of replacement to its parent
            else
                replaceParent->right = NULL;    //now parent won't point to the deleted child(replace)
        }

        ////if replacement is a leaf node, replace->left is NULL, so this *should* work in both cases(leaf/non-leaf)
        //replaceParent->right = replace->left;
        if (replaceParent->left == replace) replaceParent->left = replace->left;

        delete(replace);
        replace = NULL;

    } else if (temp->right != NULL) {    //find smallest element in right subtree
        replaceParent = replace;
        replace = replace->right;
        while (replace->left != NULL) {
            replaceParent = replace;
            replace = replace->left;
        }

        temp->data = replace->data;

        if (replaceParent != temp) {
            if (replace->right != NULL)    //if replacement is not a leaf node
                replaceParent->left = replace->right;    //attach right-children of replacement to its parent
            else
                replaceParent->left = NULL;    //now parent won't point to the deleted child(replace)
        }

        ////if replacement is a leaf node, replace->right is NULL, so this *should* work in both cases(leaf/non-leaf)
        //replaceParent->right = replace->left;
        if (replaceParent->right == replace) replaceParent->right = replace->right;




        //replaceParent->left = replace->right;
        delete(replace);
        replace = NULL;
    }

    /**abandoned**/
    /*
    //replace
    if (replace == temp) {    //No replacement found    //leaf node
        free(temp);
        free(replace);
    } else {
        if (replace->data > temp->data) {    //largest in left subtree
            temp->data = replace->data;
            if (replace->left != NULL) {    //if the replacement had left children

            }
        }
    }
    */
}

As can be seen root is a member of BST class, so delete(temp) would just set root to some garbage value, and then if I do temp = NULL, it would just make temp point to NULL, not set root to NULL, so I have to set root to NULL in this dirty way.
IF root is to be deleted; use the same method, find it's in-order successor and replace it with that data then, continue with process until you reach a node which has single/no child. as technically there can't be a BST without a root. so by this method you could delete the root node by freeing the last node.
RBX
RBX #403
Apr 20, 2014 at 9:58 AM
IF root is to be deleted; use the same method, find it's in-order successor and replace it with that data then, continue with process until you reach a node which has single/no child. as technically there can't be a BST without a root. so by this method you could delete the root node by freeing the last node.

I have problem only in the case when root itself is a leaf node i.e., it's the last node remaining in tree.
tanmaymohan
Apr 21, 2014 at 10:54 PM
n00b question
I recently took PCM with CS and we have C++ in our syllabus. Our school uses only Turbo C++ which used to run in a dos screen. But it is no longer supported in x64 versions of windows and the latest 8.1 .Is there any another GUI or dos based c++ compiler which I can use?

Sometimes we use VM 's with XP to run c++
kunalht
kunalht #405
Apr 21, 2014 at 11:35 PM
Code Blocks & Dev C++ are great IDE's
I use Code:Blocks.
& if you want to use Turbo C search on google " Turbo C for 64-bit "
rohitshubham
Apr 21, 2014 at 11:46 PM
code::blocks is the best one out there... it's a fully functional developing environment... and i personally like the interface of code:blocks :p
Neuron
Neuron #407
Apr 22, 2014 at 8:20 AM
n00b question
I recently took PCM with CS and we have C++ in our syllabus. Our school uses only Turbo C++ which used to run in a dos screen. But it is no longer supported in x64 versions of windows and the latest 8.1 .Is there any another GUI or dos based c++ compiler which I can use?

Sometimes we use VM 's with XP to run c++

Use code:blocks or visual c++ express edition and stay away from tc++.
tech0freak0
May 28, 2014 at 7:05 PM
I learned basic of C like array , string, structures..
And I also hv some knowledge of c++.
Basically I want to make android apps.
Should I move on to java or to go deep in c programming?
ankush28
ankush28 #409
May 28, 2014 at 7:13 PM
I learned basic of C like array , string, structures..
And I also hv some knowledge of c++.
Basically I want to make android apps.
Should I move on to java or to go deep in c programming?

Lol you went wrong way!
Android app programming needs knowledge of Java. You can program with C/C++ but its not recommended. In that too you HAVE to learn java. Checkout Android NDK page for more info.

--update--
Plus complication while using other APIs. Better code full using Java.
tech0freak0
May 28, 2014 at 7:36 PM
Lol you went wrong way!
Android app programming needs knowledge of Java. You can program with C/C++ but its not recommended. In that too you HAVE to learn java. Checkout Android NDK page for more info.

--update--
Plus complication while using other APIs. Better code full using Java.

yeah....i know android programming needs knowledge of Java.
My point is I have heard that if you have strong grasp on c and c++ ....then u can easily get into java.

I should move on or learn deep into c programming i.e data structures and mangement??
harshilsharma63
May 29, 2014 at 5:30 PM
Data structure has nothing to with c, c++ or Java. They are just concepts that can be implemented in any language. The reason we are first taught C is that we have to do everything manually, like no provision for accessing length of array other than manually stirring it. So learn a lot data structures and algorithms. If you are good at abstract maths, get "Introduction to Algorithms" by Cormen.

First implement these DS and algorithms in C/C++ then more ahead to Java. The transition will be like from walking on broken glass to gliding on silk.
tech0freak0
Jun 4, 2014 at 8:38 PM
I moving from c to c++.
I don't get the concept and usage of namespace std
Why we using this in cpp??

And What really meanings of gnu99 and anscii??
And What is Object Oriented Language??
harshilsharma63
Jun 4, 2014 at 9:11 PM
I moving from c to c++.
I don't get the concept and usage of namespace std
Why we using this in cpp??

And What really meanings of gnu99 and anscii??
And What is Object Oriented Language??

Suppose we both were working on a single project. I created an object named 'foo'. Apparently you also created an object with the same name. Now, when we merged what you and I developed, somehow a conflict occured between the two 'foo's. But neither of us wants to change the object's name in out code. So what do we do? You create your own namespace and I create mine. You place all your code in your namepscae (eg- 'You') and I do the same with my code (eg- 'Me'). Now when we merge the code, all we have to specify is which namepsace the foo being referred to belongs to. We can write You.foo or Me.foo depending on situation. So what happens is the code got divided into two logical independent units. This way and object in your namepsace cannot cause any conflick with any object in my namespace with the same name.
krishnandu.sarkar
Jun 4, 2014 at 9:13 PM
I moving from c to c++.
I don't get the concept and usage of namespace std
Why we using this in cpp??

In general, a namespace is a container for a set of identifiers (also known as symbols, names).[1][2] Namespaces provide a level of indirection to specific identifiers, thus making it possible to distinguish between identifiers with the same exact name. For example, a surname could be thought of as a namespace that makes it possible to distinguish people who have the same first name. In computer programming, namespaces are typically employed for the purpose of grouping symbols and identifiers around a particular functionality.

-Taken from Wikipedia.

endl, cout these belongs to std namespace. So in programs they use using namespace std.

Let me explain in a bit detail. Let's take this program.

#include <iostream>
using namespace std;
void main()
{
cout << "Hello World!" << endl; cout << "Welcome to C++ Programming" << endl;
}

If you don't use using namespace std then compiler won't be able to find cout, endl as they belongs from that namespace. You can also re-write it as

#include <iostream>
void main()
{
std::cout << "Hello World!" << std::endl; std::cout << "Welcome to C++ Programming" << std::endl;
}

:: is a scope resolution operator. Let me explain.

Under iostream header file, there's a namespace named std which means standard. Under this std namespace cout and endl is defined.

As you are coming from C, you know about scope. In c printf is defined in stdio header file and it have no concept of namespace. So writing #include<stdio.h> was enough to bring printf in scope so that compiler can understand what we are referring to.

So it's just a wrapper introduced for many reasons, which you'll learn accordingly while learning C++. So under iostream header file, there's a namespace std, under which cout and endl is defined.

So only referring iostream header file is not enough. You also need to explicitly mention under which namespace those are there.

So if you don't want to use that using namespace std then you have to use it with scope resolution operator like I did in 2nd example, std::cout. So wherever you use any materials defined in std you have to write it like this.

So it's best to use using namespace <namespace_name> above to avoid clutter and the extra typing.

And What really meanings of gnu99 and anscii??

Let someone more experienced explain this. I'm not that good in C++ :p

And What is Object Oriented Language??

If you can make out couple of hours do read this => Introduction to Object Oriented Programming Concepts (OOP) and More - CodeProject
tech0freak0
Jun 5, 2014 at 9:19 AM
Thanks for explaining namespace std.
New compiler still needs namespace apart from turbo c++ ??
krishnandu.sarkar
Jun 5, 2014 at 8:13 PM
Thanks for explaining namespace std.
New compiler still needs namespace apart from turbo c++ ??

Don't use TurboC++. The program examples I provided above uses void main() which is wrong actually and that works only in TC++. You should use int main() instead.
TheSloth
TheSloth #419
Jun 5, 2014 at 8:49 PM
i have never used namespace std in my c++ programs. i use cout to print statements. though i used iostream.h.
A
Jun 7, 2014 at 10:36 AM
Hi all!


[C++]
I wanted to create something like Menu in the output window /Run in Code::Blocks .Like when I run the code,it should first ask me to input 2 numbers ,then it should ask to do sum,difference,product or division in this format--

Press 1 for Addition
Press 2 for Subtraction
Press 3 for Multiplication
Press 4 for Division

or something like that .Please help

P.S-I'm a beginner actually and I've made programs to calculate multiplication tables,all maths operations and area/perimeter of triangle and square ,so please not-so-advanced code :p :p

Thank you
aaruni
aaruni #422
Jun 7, 2014 at 11:12 AM
you could do simple things like enter 1 for addition, 2 for subtraction, etc (notice I use the word enter, not press, so you can use cin, instead of getchar).

then, you can use simple if-else to direct the control to relevant code.
V
Vignesh B #423
Jun 7, 2014 at 11:56 AM
You may use the else-if ladder as already posted above, or you may also use the switch statement to use the relevant code.
kunalht
kunalht #424
Jun 7, 2014 at 12:35 PM
or you can also use switch statement for that.
harshilsharma63
Jun 7, 2014 at 6:30 PM
Switch will look more elegant than an if-else-if ladder.
A
Jun 7, 2014 at 8:50 PM
Thank you all ! It would be great if someone would give a code related to it so as to help me understand :D
kunalht
kunalht #428
Jun 7, 2014 at 11:25 PM
Thank you all ! It would be great if someone would give a code related to it so as to help me understand :D


Try yourself first! and then ...... hit spoiler :p

Code:
#include <iostream>

using namespace std;

int main()
{
    int a , b, c,x ;
    cout <<" Enter value of a and b"<< endl;
    cin >> a ;
    cin >> b ;
    cout << "Enter 1 for addition , 2 for suntraction 3 for multiplication & 4 for division!" << endl;
    cin >> x ;
    switch (x)
        {

    case 1:
        c = a + b ;
        cout << c ;
        break;
    case 2:
            c = a - b;
            cout << c ;
            break;
    case 3:
            c = a * b;
            cout << c ;
            break;
    case 4:
            c = a / b;
            cout << c ;
            break;
    default:
            cout  << "Wrong input" << endl;
        }

    return 0;
}
harshilsharma63
Jun 8, 2014 at 8:04 AM
^ I request not to spoon feed anyone here.
tech0freak0
Jun 16, 2014 at 8:04 PM
Eclipse is giving me hard time.....

I can't compile program, i have downloaded Cywin; But it not helping

And gcc is not downloading from equation.com as it giving ftp error.
krishnandu.sarkar
Jun 17, 2014 at 8:48 AM
Eclipse is giving me hard time.....

I can't compile program, i have downloaded Cywin; But it not helping

And gcc is not downloading from equation.com as it giving ftp error.

Why don't you simply use Code::Blocks? Or you can even use Visual Studio.
srkmish
srkmish #432
Jul 28, 2014 at 11:36 PM
Hi friends,

Im learning unix at office. Im enjoying it. I use putty for it. I have downloaded putty in my home computer but am puzzled as to how to use it cuz there is no remote server to login to from my home pc. Is there a workaround for this?
Vyom
Vyom #433
Jul 29, 2014 at 12:00 AM
Im learning unix at office. Im enjoying it. I use putty for it. I have downloaded putty in my home computer but am puzzled as to how to use it cuz there is no remote server to login to from my home pc. Is there a workaround for this?

You use Putty to connect to actual remote machines.
If you want to practice Unix commands/shell programming you have following choices:
1. Use linux distros like Ubuntu
2. Use Live Disk of any distro like Ubuntu
3. Use a program like UWIN which provides a tool on windows to practice Unix commands. A Link. But its trialware so only works for 30 days. First two methods are preferred.
Desmond
Desmond #434
Jul 29, 2014 at 12:21 AM
Best option to learn Unix is Cygwin in windows. Also, you can use MinGW
layzee
layzee #435
Jul 30, 2014 at 11:29 AM
Hi friends,

Im learning unix at office. Im enjoying it. I use putty for it. I have downloaded putty in my home computer but am puzzled as to how to use it cuz there is no remote server to login to from my home pc. Is there a workaround for this?

Install VirtualBox and then create a new virtual machine with a new virtual hard disk. Boot into it using a live ISO of any popular GNU/Linux distro like Ubuntu or Fedora, install it to the virtual hard drive and you're done.
srkmish
srkmish #436
Jul 30, 2014 at 9:33 PM
Thanks to all. I have installed cygwin and its working fine.
kunalht
kunalht #437
Aug 21, 2014 at 10:54 PM
Suggest some good books for Data structure in c programming.
tech0freak0
Sep 20, 2014 at 1:13 PM
In C language malloc() is a function, right?
I want to see contents of the malloc function i.e behind scene, So i can have a better understanding.
aaruni
aaruni #439
Sep 20, 2014 at 8:23 PM
In C language malloc() is a function, right?
I want to see contents of the malloc function i.e behind scene, So i can have a better understanding.

if its a function in one of the header files, simply open that header file in a text editor and read away!
TechnoBOY
TechnoBOY #440
Oct 30, 2014 at 7:08 PM
I installed turbo ide with DOSBOX but i cant get into the userscreen
Chaitanya
Chaitanya #441
Oct 30, 2014 at 7:09 PM
Can't help there but you may try code blocks
aaruni
aaruni #442
Oct 30, 2014 at 7:18 PM
I installed turbo ide with DOSBOX but i cant get into the userscreen

what do you mean? can you be more clear about what you have tried?
TechnoBOY
TechnoBOY #443
Oct 30, 2014 at 7:28 PM
Can't help there but you may try code blocks
Ohh le me try it
I am getting that DOSBOX menu when choosing userscreen

- - - Updated - - -

what do you mean? can you be more clear about what you have tried?
I need Turbo IDE on my PC with 64bit ,Turbo IDE cannot run on mine so installed DOSBOX DOSBox, an x86 emulator with DOSThen i intalled IDE in it every thing works fine but cant view the output
aaruni
aaruni #444
Oct 30, 2014 at 8:07 PM
[MENTION=285910]TechnoBOY[/MENTION] : here is a short guide I just wrote up. Tell me if you need anything more : TC++ Under DOSBox | Aaruni's Blog
Desmond
Desmond #445
Oct 30, 2014 at 8:10 PM
Why do people still use Turbo C++?
TechnoBOY
TechnoBOY #446
Oct 30, 2014 at 8:13 PM
[MENTION=285910]TechnoBOY[/MENTION] : here is a short guide I just wrote up. Tell me if you need anything more : TC++ Under DOSBox | Aaruni's Blog
My prob is cant get to output
aaruni
aaruni #451
Oct 30, 2014 at 8:23 PM
My prob is cant get to output

are you writing the clrscr() and getch() functions in your code? Because just executing the following code gives me output :

*edufor.fosspowered.com/blog/wp-content/uploads/2014/10/Screenshot-from-2014-10-30-200539.png
TechnoBOY
TechnoBOY #452
Oct 30, 2014 at 8:44 PM
[MENTION=134449]aaruni[/MENTION]
choosing output gives me this window
imgur: the simple image sharer
aaruni
aaruni #453
Oct 30, 2014 at 9:17 PM
[MENTION=134449]aaruni[/MENTION]
choosing output gives me this window
imgur: the simple image sharer

you're definitely not using clrscr() function at the beginning of you're program. try adding clrscr() and getch() at the beggining and the end of the program, respectively, then execute.
TechnoBOY
TechnoBOY #454
Oct 30, 2014 at 9:44 PM
you're definitely not using clrscr() function at the beginning of you're program. try adding clrscr() and getch() at the beggining and the end of the program, respectively, then execute.
ya did try it whn u posted that pic then its fine
but ehy without using them
aaruni
aaruni #455
Oct 30, 2014 at 9:48 PM
clrscr() clears the output screen.

getch() waits for you to press any key before going further.

If you don't write getch(), it shows the output, and then comes back to the IDE screen, but it does it so fast, that you think the output screen was never displayed.
Desmond
Desmond #456
Oct 30, 2014 at 11:07 PM
I don't remember but Alt+F2 or some key shows the output if you don't use getch().

- - - Updated - - -

Pro tip: If you are using Dosbox, don't use Ctrl + F9 to run. That same key also quits Dosbox.
aaruni
aaruni #457
Oct 30, 2014 at 11:12 PM
Desmond, he did get to the output screen. But because he didn't use clrscr(), there was still DOSBox stuff on it. (read a few posts earlier, imgur link).

I approve of your pro-tip :p
TechnoBOY
TechnoBOY #458
Oct 31, 2014 at 4:40 PM
I don't remember but Alt+F2 or some key shows the output if you don't use getch().

- - - Updated - - -

Pro tip: If you are using Dosbox, don't use Ctrl + F9 to run. That same key also quits Dosbox.
no prob i change cntl + F9 in keymapper
harshilsharma63
Oct 31, 2014 at 4:43 PM
are you writing the clrscr() and getch() functions in your code? Because just executing the following code gives me output :

*edufor.fosspowered.com/blog/wp-content/uploads/2014/10/Screenshot-from-2014-10-30-200539.png


Why are you using TurboC/C++? Do you not take your life seriously? Are you a sheep in a heard?
aaruni
aaruni #460
Nov 3, 2014 at 9:00 PM
Why are you using TurboC/C++? Do you not take your life seriously? Are you a sheep in a heard?

Wow. I think I forgot to be vocal about my hate for TC++ in this thread. Those who know me, and those who are regulars on the IRC channel know how much I hate it. I wrote a TC++ specific guide, because TechnoBOY asked a TC++ question, and if he's a newbie, then he's probably being taught TC++, because our syllabus is so awesome.

Personally, I used GCC C++ compiler on Linux Ubuntu.

So, I do take my life seriously. And I am not sheep in a herd.

I do appreciate your concern though. If more people were like you, the era of TC++ would've been over long ago.
harshilsharma63
Nov 4, 2014 at 1:40 AM
Wow. I think I forgot to be vocal about my hate for TC++ in this thread. Those who know me, and those who are regulars on the IRC channel know how much I hate it. I wrote a TC++ specific guide, because TechnoBOY asked a TC++ question, and if he's a newbie, then he's probably being taught TC++, because our syllabus is so awesome.

Personally, I used GCC C++ compiler on Linux Ubuntu.

So, I do take my life seriously. And I am not sheep in a herd.

I do appreciate your concern though. If more people were like you, the era of TC++ would've been over long ago.

Sorry mate, didn't knew about that. GCC FTW! Era of TC++ is long gone. We just have to delete it form or college systems one by one. Now that I know college's admin password, I prepared a shell script that deletes the TC++ directory on startup and installed it on each PC in our lab. Evil + technology = rule the world!
V
Nov 19, 2014 at 8:36 PM
I find 2 versions of head first c on flipkart both published in 2012 but with different isbn :

9781449399917 - book 1

9789350236925 - book 2

1st one is selling on the publisher's site: Head First C*-*O'Reilly Media

which one to use?
ankush28
ankush28 #463
Nov 23, 2014 at 7:13 PM
Sorry mate, didn't knew about that. GCC FTW! Era of TC++ is long gone. We just have to delete it form or college systems one by one. Now that I know college's admin password, I prepared a shell script that deletes the TC++ directory on startup and installed it on each PC in our lab. Evil + technology = rule the world!
Nice man! :mrgreen: Will do something similar for AutoCAD 2004 and TC++ in my college :D
harshilsharma63
Nov 25, 2014 at 5:04 AM
Our school PCs are being upgraded with Windows 8.1, and we will run TC++ on DOSBox. -_-

Wrong thread. Should go in the "dumbest thing I've ever heard about technology" thread :lol: :p
Vyom
Vyom #467
Nov 25, 2014 at 7:51 AM
Our school PCs are being upgraded with Windows 8.1, and we will run TC++ on DOSBox. -_-

Who the hell told then about DOSBox. Nobody but you I hunch. This was the perfect opportunity to get out of TC++. "Madam Windows 8.1 pe MinGW hi chalta hai."
aaruni
aaruni #468
Nov 27, 2014 at 5:07 PM
Who the hell told then about DOSBox. Nobody but you I hunch. This was the perfect opportunity to get out of TC++. "Madam Windows 8.1 pe MinGW hi chalta hai."

Our computer textbook tells us to run TC++ inside DOSBox in appendix section.
thetechfreak
Nov 28, 2014 at 12:16 AM
Vyom said:
"Madam Windows 8.1 pe MinGW hi chalta hai."
Teaching code that would work in MingGW is another thing. Besides the syllabus is based on the TC++ system.
aaruni
aaruni #470
Nov 28, 2014 at 12:18 AM
Teaching code that would work in MingGW is another thing. Besides the syllabus is based on the TC++ system.

egg-****ing-zactly:banghead::banghead:

- - - Updated - - -

hey, who put the censor system in place?
harshilsharma63
Nov 28, 2014 at 8:21 AM
At least CBSE is doing something about this. They replaced VB with Java 2009 and then brought Python.
aaruni
aaruni #473
Nov 28, 2014 at 9:06 AM
At least CBSE is doing something about this. They replaced VB with Java 2009 and then brought Python.

GHANTA! Python is here only for namesake. All the schools still teach TC++.
RBX
RBX #474
Nov 28, 2014 at 9:16 AM
Our computer textbook tells us to run TC++ inside DOSBox in appendix section.
Which textbook is that?

GHANTA! Python is here only for namesake. All the schools still teach TC++.
I don't think that is true. I learned VB6 in school, and my sister learned Java (Swing apps).
harshilsharma63
Nov 28, 2014 at 9:25 AM
GHANTA! Python is here only for namesake. All the schools still teach TC++.

You have two optional subjects -Computer Science and Information Practices. Computer Sciences includes C++ and MySQL whereas Information Practices includes Python (earlier Java and even earlier VB) and MySQL. It's up to the school which elective subjects they offer to student. I myself had Information Practices and learned Java.
thetechfreak
Nov 28, 2014 at 10:31 AM
[MENTION=46039]RBX[/MENTION] The C++ books used in +2 level is the one written by Sumita Arora. It's more or less the de-facto book throughout the country.
RBX
RBX #477
Nov 28, 2014 at 11:02 AM
[MENTION=57860]thetechfreak[/MENTION] Yes, I remember now. That was the one I read for VB6/Oracle.
JojoTheDragon
Apr 1, 2015 at 10:11 PM
Can you please reupload the images for mac users? Thanks :)
TechnoBOY
TechnoBOY #479
May 18, 2015 at 8:04 PM
which language will be used wildly after 4-5 years ?
P
potatoboy #481
Aug 7, 2015 at 10:16 PM
Greetings, coders!

I'm pursuing my Bachelor of Computer Applications degree(BCA) in Bangalore, and boy was I shocked when I read the first few posts on this thread. I knew the Turbo C compiler was old, but WOW.Why do colleges and universities still insist on teaching on such an outdated platform?
On a side note, I want to stray away from Turbo CPP after becoming enlightened. I've learnt the nuances of C++ and have some moderate knowledge of C, but I NEED to become better. Maybe even start learning Python. Any help would be greatly appreciated! TIA!

On another side note, my teacher even told us at one point that TC was old as hell, but he taught us with it merely because it was in the syllabus. *facepalm* Shows that most teachers merely want to teach students for the sake of marks.

EDIT : now I'm really starting to feel like sheep in a herd. I was led all these days to thinking that integers have 2 bytes of memory where it is 4, and we used conio.h ALL these days in the lab(guess which compiler!) I really want to start over again from scratch :(
Nerevarine
Nerevarine #482
Aug 8, 2015 at 12:30 AM
use the inbuilt gcc in ubuntu, getting used to it will help you a lot A LOT!
Desmond
Desmond #483
Aug 8, 2015 at 2:22 AM
Greetings, coders!

I'm pursuing my Bachelor of Computer Applications degree(BCA) in Bangalore, and boy was I shocked when I read the first few posts on this thread. I knew the Turbo C compiler was old, but WOW.Why do colleges and universities still insist on teaching on such an outdated platform?
On a side note, I want to stray away from Turbo CPP after becoming enlightened. I've learnt the nuances of C++ and have some moderate knowledge of C, but I NEED to become better. Maybe even start learning Python. Any help would be greatly appreciated! TIA!

On another side note, my teacher even told us at one point that TC was old as hell, but he taught us with it merely because it was in the syllabus. *facepalm* Shows that most teachers merely want to teach students for the sake of marks.

EDIT : now I'm really starting to feel like sheep in a herd. I was led all these days to thinking that integers have 2 bytes of memory where it is 4, and we used conio.h ALL these days in the lab(guess which compiler!) I really want to start over again from scratch :(

There is nothing wrong with learning on Turbo C++ as long as you are able to distinguish between it and modern C++ variants.

It also helps if you code on gcc as well.
v.Na5h
v.Na5h #484
Aug 24, 2015 at 10:18 AM
What ide do you guys use..

I used to use code blocks.. But found out that netbeans 8.0.2 is way better
P
priyar #485
Jan 9, 2016 at 3:22 PM
I have learnt C,C++ can i create any software with this technology and learning Cloud Computing is also very useful.
TheSloth
TheSloth #486
Mar 14, 2016 at 3:02 PM
in windows you cannot create a file/folder with a same name as a existed file/folder. You must give a different name. like there is one folder called MyPics. In that folder there is a file named pic1.jpg. Now if you try to rename another file as pic1.jpg, windows will not allow. But you can have a file named pic1.jpg in some other folder.

Similarly, when you have two or more functions of same name then the compiler will face ambiguity problem, i.e. which one to call. Suppose if you create a function called getsize() then you cannot have another function as getsize(). Compiler will say "getsize() is already defined" .
So you create two namespaces, viz. namespace one and namespace two. and define getsize() function in each as per your requirement.
to use that particluar function you type as one::getsize();
OR
you just declare the namespace you are goin to use before writing the code
using namespace one;
int main()
{
getsize();
return 0;
}

the statement you have given is :
using namespace std; // here std is the name of the directory you are goin to use

PS:Wait for others to comment, I am not 100% sure as I studied C++ 3 yrs back
aaruni
aaruni #487
Mar 14, 2016 at 10:08 PM
in windows you cannot create a file/folder with a same name as a existed file/folder. You must give a different name. like there is one folder called MyPics. In that folder there is a file named pic1.jpg.
Now if you try to rename another file as pic1.jpg, windows will not allow. But you can have a file named pic1.jpg in some other folder.

Similarly, when you have two or more functions of same name then the compiler will face ambiguity problem, i.e. which one to call. Suppose if you create a function called getsize() then you cannot have another function as getsize(). Compiler will say "getsize() is already defined" .
So you create two namespaces, viz. namespace one and namespace two. and define getsize() function in each as per your requirement.
to use that particluar function you type as one::getsize();
OR
you just declare the namespace you are goin to use before writing the code
using namespace one;
int main()
{
getsize();
return 0;
}

the statement you have given is :
using namespace std; // here std is the name of the directory you are goin to use

PS:Wait for others to comment, I am not 100% sure as I studied C++ 3 yrs back

I'm not sure that this is the reason, but it works this way. You can either use

Code:
using namespace std;

at the beginning of the program, or you can type

Code:
std::cin
std::cout
....

throughout your program.

When asked to comment in my C++ project, why I had to write
Code:
using namespace std;
, I commented the following

Code:
using namespace std;	//to avoid std::cin, std::cout, std::fstream, etc.
TheSloth
TheSloth #488
Mar 14, 2016 at 11:28 PM
[MENTION=134449]aaruni[/MENTION] That actually make more sense and really summed up my post. std is a library, and cin, cout and fstream are declared inside std. Thanks man. I hope OP will understand better now.
Desmond
Desmond #489
Apr 20, 2016 at 4:59 PM
i have just started my academic career in programming, and my teacher choose c++ as essential language for us, they are using dev c to write and compile program, would that be alright ?

I don't see why not.
S
sampada #490
Oct 7, 2016 at 1:27 PM
Moving and permissions. If you move a file from one location to another, the file generally retains its permissions settings. Thus, if you move an application from the Applications folder to your Home directory, it will retain system and admin as its owner and group.

Conversely, if you move a file from your Home directory to the Applications folder, it will retain the permissions settings it had in your Home directory. Depending on what those settings were, nonadministrative users may not be able to launch the file due to insufficient access. In such a case, the solution is to modify the file so that it acquires the system and admin attributes of most other files in the Applications folder.

Copying and permissions. If you copy a file from one location to another, the copy generally acquires the attributes of its enclosing folder. Thus, if you copy a file from Applications to your Home directory, it will acquire your user name as the owner and staff as the group.

Conversely, if you copy a file from your home directory to the Applications folder, its permissions change to that of system and admin. Thus, you are no longer the owner of the file you just copied. In this slightly odd situation, you may be able to modify the privileges settings (via Mac OS X's Show Info window) of the original file but not those of the copy.
aaruni
aaruni #491
Oct 7, 2016 at 1:31 PM
^ Although true, I don't see how that fits in here.
S
Nov 16, 2016 at 11:05 AM
May I know How to install Turbo c software in Ubuntu operating System ? If you have any ideas please revert.
TheSloth
TheSloth #493
Nov 16, 2016 at 11:19 AM
@shanmorkel1685 buddy use some other IDE like Eclipse or Codeblocks instead of ancient Turbo C/C++. You won't find it much difficult to use.
aaruni
aaruni #494
Nov 16, 2016 at 5:59 PM
+1 . Use something other than TC++ .

But, if for whatever reason, you absolutely need to run TC++, install it in DosBox.

TC++ Under DOSBox – Aaruni's Blo (note that the guide points to Dosbox website for dosbox install. in ubuntu, just install dosbox via apt)
J
Johnny1 #495
Nov 18, 2016 at 11:23 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:
*img4.imageshack.us/img4/8531/path3.png
*img12.imageshack.us/img12/1399/path4.png
*img11.imageshack.us/img11/6822/path5.png
*img18.imageshack.us/img18/1511/path6.png

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:
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:
su

Then pass the comand.(exact as in the quotes):

Code:
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.

PHP:
#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.
PHP:
#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:
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:
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:
*img89.imageshack.us/img89/8343/program.png
*img26.imageshack.us/img26/893/savertz.png
*img530.imageshack.us/img530/4053/compile.png

Steps for Mac OS X users:
*img836.imageshack.us/img836/3885/sc1z.jpg
*img259.imageshack.us/img259/2444/sc2n.jpg

Steps for Linux users:
*img152.imageshack.us/img152/9222/screenshot2btw.png
*img2.imageshack.us/img2/3937/screenshot4ymv.png

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.

Its Great And very Informative Post..I have been looking for a long time.Its awesome. Really Appreciate it. Thanks For Sharing with us.
SaiyanGoku
SaiyanGoku #496
May 19, 2017 at 11:05 AM
Hello,
I have completed my engineering from Computer science branch.
Now I am preparing for <Link Removed>
My engineering concepts are not so clear I mean my programming is not so good.
Suggest me the books I prefer and how can I improve my programming?

You want to study programming for IBPS?
Anyway, just go to tutorials point website.
W
Jun 16, 2017 at 6:04 PM
@SaiyanGoku SO is specialist officer,different from PO & it also includes IT officer for which an IT specific exam is there(though I think it focuses more on networking & theoretical concepts & not so much on coding/application part).
Desmond
Desmond #498
Dec 8, 2017 at 11:13 PM
Thanks for giving such an info
OMG...is this all you have to say? Your first post and all you have to say is Thanks for this info? Does this look like Facebook or Twitter to you?
pkkumarcool
Dec 11, 2017 at 5:50 PM
I want to study c# swift any good website for that


Sent from my iPhone using Tapatalk
quicky008
quicky008 #500
Apr 8, 2018 at 3:09 PM
can anyone provide me with a relatively simple program that can be used to represent an array of integers as a binary tree?
Nerevarine
Nerevarine #501
Apr 8, 2018 at 3:16 PM
Index n = root
Index 2n+1 = left child
Index 2n+2 = right child
If im not mistaken.
quicky008
quicky008 #502
Apr 8, 2018 at 3:34 PM
i remember reading somewhere that in an array representation of a tree,

if node: i

Child: 2*i, 2*i+1

Parent: i/2

Is this a correct way to represent the array elements as nodes of a binary tree?
pkkumarcool
May 16, 2018 at 12:47 PM
i remember reading somewhere that in an array representation of a tree,

if node: i

Child: 2*i, 2*i+1

Parent: i/2

Is this a correct way to represent the array elements as nodes of a binary tree?
so both child will be greater than parent? as far as i reme,
i remember reading somewhere that in an array representation of a tree,

if node: i

Child: 2*i, 2*i+1

Parent: i/2

Is this a correct way to represent the array elements as nodes of a binary tree?
any explanation why i dont get why child is 2*i
Nerevarine
Nerevarine #504
May 16, 2018 at 1:10 PM
Simple reason is that we should have a formula for properly mapping out a root node to 2 different unique child nodes which can be easily tracked and there is no collision.
To be absolutely fair, you can make a binary tree with ANY formula, it is not a given that it should be 2*i, as long as there is a one to one mapping between root -> left child and root -> right child.
What I mean is, there should not be a situation where
root1 index -> leftchild1 index
root1 index -> rightchild1 index

root2 index -> leftchild1 index
root2 index -> rightchild2 index


As you can see from the above example root1 and root2 are both mapped to leftchild1 index, which causes a collision.
To sum up, a binary tree is just a mapping of root to 2 unique and retrievable child nodes without any collision.

We use the 2*i format because it is very simple, and wastes very little space. You could literally use ANY hash function to make a custom tree of your own, as long as there is no collision.


This is wiki's defination
Arrays[edit]
Binary trees can also be stored in breadth-first order as an implicit data structure in arrays, and if the tree is a complete binary tree, this method wastes no space. In this compact arrangement, if a node has an index i, its children are found at indices {\displaystyle 2i+1}*wikimedia.org/api/rest_v1/media/math/render/svg/f077f73c2ecdf3c6e29a120f948a7255c0a65da1 (for the left child) and {\displaystyle 2i+2}*wikimedia.org/api/rest_v1/media/math/render/svg/a756deaef520ee23fe2b1232c90957f55ec9d92b (for the right), while its parent (if any) is found at index {\displaystyle \left\lfloor {\frac {i-1}{2}}\right\rfloor }*wikimedia.org/api/rest_v1/media/math/render/svg/35dc2d601bbd9aff8f1ed1c4b2323122f2403317 (assuming the root has index zero). This method benefits from more compact storage and better locality of reference, particularly during a preorder traversal. However, it is expensive to grow and wastes space proportional to 2h - n for a tree of depth h with n nodes.

This method of storage is often used for binary heaps. No space is wasted because nodes are added in breadth-first order.

Correct me If I'm wrong.
quicky008
quicky008 #505
Feb 27, 2020 at 10:37 AM
How can i create an array of strings in c++?

Whenever i create a string array using "string ar[5]" and then attempt to enter values in it via a for loop,i can only enter 4 values ie one less than the arrays capacity.


Can anyone suggest why this happens?
Nerevarine
Nerevarine #506
Feb 27, 2020 at 10:40 AM
When you create ar[5], here the 5 refers to size of array.
But programming index starts from 0, not one.
So ar[0], 1,2,3,4 are your entries
pkkumarcool
Feb 27, 2020 at 3:20 PM
When you create ar[5], here the 5 refers to size of array.
But programming index starts from 0, not one.
So ar[0], 1,2,3,4 are your entries

But he should still get 5 entries right 0,1,2,3,4


Sent from my iPhone using Tapatalk
W
Feb 27, 2020 at 4:27 PM
But he should still get 5 entries right 0,1,2,3,4


Sent from my iPhone using Tapatalk
My C++ knowledge is quite dusty but from whatever I remember if you assign an array value to wrong index it won't enter & here a 'for' loop is used which I presume starts from i=1 with +1 increment till i=5 which will result in only 4 entries as array[5] entry will be ignored.
pkkumarcool
Feb 27, 2020 at 5:06 PM
My C++ knowledge is quite dusty but from whatever I remember if you assign an array value to wrong index it won't enter & here a 'for' loop is used which I presume starts from i=1 with +1 increment till i=5 which will result in only 4 entries as array[5] entry will be ignored.

Yeah if you start for loop with i=1 till i<5 then you will get 4 values only.


Sent from my iPhone using Tapatalk
Nerevarine
Nerevarine #512
Feb 27, 2020 at 6:43 PM
Guys if you are on windows, Visual Studio is definitely the go to choice for C/CPP development. MacOS the obvious best choice is XCode.
Linux its either you use gcc or a proper IDE. I know I suggested to learn and use gcc in the past, but managing a large project completely via gcc and make is a monumental task. So my IDE of choice for Linux is definitely Clion (Its paid unfortunately)
Eclipse CDT is too slow, QT creator is also good (free) choice.
W
Feb 27, 2020 at 7:32 PM
But i=1 to i<=5 will give 5 inputs wont it?


Sent from my iPhone using Tapatalk
For i=5 the loop will try to assign array[5] which will fail as valid values to assign are array[0,1,2,3,4]. The correct loop should be i=0;i<5;i++
quicky008
quicky008 #515
Feb 27, 2020 at 11:18 PM
thanks for all of your valued inputs.

I am aware that in case of arrays and strings,the index starts from 0 and i had coded the for loop correctly keeping that in mind.

The coding was ok,it seems the error was being caused by some bug in Dev-Cpp as when i executed the same program on another machine (having a different version of Dev-CPP installed) it worked just fine and accepted 5 values as input like its supposed to.

Dev-cpp is known to be a somewhat buggy IDE-i think i will switch to code blocks from now on.BTW can regular C/C++ programs be executed in VStudio? Are any free versions of Vstudio available which aren't too resource or memory intensive?
Nerevarine
Nerevarine #516
Feb 28, 2020 at 3:59 PM
That took an interesting turn o_O
Nerevarine
Nerevarine #517
Feb 28, 2020 at 4:01 PM
An advice for any new c/cpp developers.
Learn new cpp syntax, especially cpp+14/17. Smart pointers , etc. You don't need to worry about memory allocation and shit.
Learn concept of RAII
Use better ide from the get-go (visual studio)
Learn to use breakpoints instead of print statements (millions of them)
Use scm(git)
W
Feb 28, 2020 at 4:30 PM
So anyone still uses the good old blue coloured turbo c++ :grin:
Nerevarine
Nerevarine #520
Feb 28, 2020 at 10:00 PM
I only briefly used Visual Studio and its the dark theme definitely.
Mostly use Xcode and now moving to Clion
quicky008
quicky008 #521
Feb 28, 2020 at 11:59 PM
How about those who use linux on a daily basis?I dont suppose they can utilize VS to code their C/C++ programs now,can they?
Nerevarine
Nerevarine #522
Feb 29, 2020 at 12:29 PM
Surprisingly they can.
1) you can use VS Code (which is a glorified text editor) with a few debugger plugins to code . This is a hobby IDE at best.
2) Use regular VS Community/Pro/Enterprise on a windows machine and attach debugger to a VM or another machine on network running linux. VS has full linux library compatibility, sadly the application itself is not on Linux
quicky008
quicky008 #523
Apr 21, 2020 at 7:46 PM
Can someone please explain to me how this program works:

C++:
#include<iostream>

using namespace std;

class Vector
{
  public:
    int x;
    int y;
    Vector(int x, int y) : x(x), y(y) {}
    Vector operator+(const Vector &right)
    {
        Vector result(x + right.x, y + right.y);
        return result;
    }
};

std:: ostream &operator<<(std:: ostream &Str, Vector const &v)
{
    Str << "[" << v.x << "," << v.y << "]";
    return Str;
}

int main()
{
    Vector x(2, 3);
    Vector y(4, 5);
    cout << "Sum of vectors " << x << " and " << y << " is " << x + y << endl;
    return 0;
}

Its based on operator overloading-but my knowledge of C++ is a bit rusty as i haven't been using it for a long time.So any explanation would have been really helpful

Mod edit: Fixed code formatting using code blocks.
Desmond
Desmond #524
Apr 21, 2020 at 11:21 PM
Can someone please explain to me how this program works:

#include<iostream>

using namespace std;

class Vector
{
public:
int x;
int y;
Vector(int x, int y) : x(x), y(y) {}
Vector operator+(const Vector &right)
{
Vector result(x + right.x, y + right.y);
return result;
}
};

std:: ostream &operator<<(std:: ostream &Str, Vector const &v)
{
Str << "[" << v.x << "," << v.y << "]";
return Str;
}

int main()
{
Vector x(2, 3);
Vector y(4, 5);
cout << "Sum of vectors " << x << " and " << y << " is " << x + y << endl;
return 0;
}

Its based on operator overloading-but my knowledge of C++ is a bit rusty as i haven't been using it for a long time.So any explanation would have been really helpful

I haven't coded in C++ in a long time, but from what I remember, here you are overloading the + operator and giving it the functionality to add two vectors. Note that the + operator historically is defined to add two numbers, floats or doubles, etc. it is not defined for custom types such as Vector here. Therefore, you have to define the functionality of + for user defined types in this case and that is what is going on.

Here, the operator + has been defined to add the x of the first operand vector to the x of the second operand vector and the y of the first operand vector to the y of the second operand vector. The result is a new vector object having the resultant values of x and y.
Nerevarine
Nerevarine #525
Apr 22, 2020 at 7:07 AM
Same thing happens with << operator. It is used here to pass a vector object to a stream, by converting that vector object into a string format.
quicky008
quicky008 #526
Apr 22, 2020 at 2:42 PM
^thank you both for the inputs,but i can't understand what's going on in this part

C++:
Vector operator+(const Vector &right)
{
    Vector result(x + right.x, y + right.y);
    return result;
}

Whats the purpose of using the const Vector &right as the parameter? Is &right a pointer variable of type Vector?If so,why are they using a pointer variable and why is it being declared as a constant?

Are the variables x and y being initialized with 2 and 3 respectively,and then 4 and 5 are added to them later via (x + right.x, y + right.y)?

Also i am having a hard time understanding the significance of this :

C++:
std:: ostream &operator<<(std:: ostream &Str, Vector const &v)
{
    Str << "[" << v.x << "," << v.y << "]";
    return Str;
}
Desmond
Desmond #527
Apr 22, 2020 at 11:47 PM
Whats the purpose of using the const Vector &right as the parameter?
It represents the RHS operand of that operator. There is no LHS because the current class is considered the LHS operand.
Are the variables x and y being initialized with 2 and 3 respectively,and then 4 and 5 are added to them later via (x + right.x, y + right.y)?
It's a bit confusing since you have named your vectors x and y. Suppose if you named them v1 and v2, then v1 + v2 will be equals to [(v1.x + v2.x),(v1.y + v2.y)]. Therefore, in this case, suppose if v3 = v1 + v2, then v3 will be (2+4, 3+5) = (6, 8)
Also i am having a hard time understanding the significance of this :
Here you are overloading the insertion operator. Here the operands are an output character stream and a Vector user defined type. Basically, this operator will format your Vector (right operand) in this format: [x,y] and insert it into the character stream variable in the left operand.
skeletor
skeletor #528
May 1, 2020 at 10:23 AM
Can someone please explain to me how this program works:

~ coded snipped out ~

Its based on operator overloading-but my knowledge of C++ is a bit rusty as i haven't been using it for a long time.So any explanation would have been really helpful

Mod edit: Fixed code formatting using code blocks.

Purpose of std:: ostream &operator<<(std:: ostream &Str, Vector const &v):

What this does is, it modifies the behaviour of << operator in std:: ostream. So when you use std::cout << and you have an object of class Vector, it will use this new definition of the operator <<.

Why? To add support in std::cout so that it print the object of class Vector in the desired format. The desired format being what you see in the definition. Remove this definition and your code will fail to compile and report that there is "no match for operator<< in std:: ostream when Vector is an operand".

Purpose of Vector operator+(const Vector &right):

To add binary operator +. The way this works is when you do a + b where both a and b are objects of class Vector, a is considered the caller object. b is considered a parameter to the operator's definition, i.e. "right" in the code. Then what the operator is supposed to do is. Create and return a new Vector object that adds x and y members of the caller (i.e. a) and the operand (i.e. b).

For simplicity, I suggest that in the main function you replace x with a and y with b (or v1 and v2 like Desmond suggested).
quicky008
quicky008 #529
Mar 20, 2021 at 8:28 PM
i was trying to write an int value to a file using the fputc command in the following way:

fputc(count,p) where count is the integer variable and p is the file pointer.

the program is supposed to write 5(the value of count),but after running the program,all i can find in the file is a garbage/unrecognizable value.

however if i attempt to write a char value to a file instead of an int value(eg '5'),its written correctly and the value appears in the file after running the program.

Can anyone explain why this happens?

also i am bit confused about the syntax of fputc-acc. to some sources it should be int fputc(int char, FILE *pointer) (Where char is the character value being written). If i am trying to write a char value,why not use char datatype directly,rather than an int value?Whats the reasoning/logic behind this?
aaruni
aaruni #530
Mar 20, 2021 at 8:36 PM
Characters are just variants of integers, encoded in ASCII.
Code:
char '5'
is the same value as
Code:
int 53
. The number 5 refers to the character ENQ ( Enquiry character - Wikipedia ).

In C++, you can write to files in text mode, or binary mode. When writing in text mode, all writing is done in characters.

Important thing to remember is that every character is actually a number behind the scenes.
Nerevarine
Nerevarine #531
Mar 20, 2021 at 8:38 PM
It could be writing the ascii value of 5 onto the file, which is

505005^EEnquiry (ENQ)


Can you try 65 and see if A (in caps) is being written ?

Edit : anyway aaruni beat me to it, i think thats whats happening
quicky008
quicky008 #532
Mar 20, 2021 at 9:31 PM
^indeed,when i entered 65,it did write A to the file.

Why then is it writing some sort of unrecognizable character if i try to write an int variable containing the value 5?Is it writing the ASCII character that corresponds to the value of 5?

so what should one do if he wishes to write some numeric value to a file?Does one need to derive its ASCII value then write it to the file-wont that become quite cumbersome?
quicky008
quicky008 #533
Mar 20, 2021 at 9:43 PM
Characters are just variants of integers, encoded in ASCII.
Code:
char '5'
is the same value as
Code:
int 53
. The number 5 refers to the character ENQ ( Enquiry character - Wikipedia ).

In C++, you can write to files in text mode, or binary mode. When writing in text mode, all writing is done in characters.

That was my understanding too,but why then is the first argument to fputc function an integer as opposed to a character value(as i have pointed out in my earlier post)?
Nerevarine
Nerevarine #534
Mar 20, 2021 at 9:56 PM
^indeed,when i entered 65,it did write A to the file.

Why then is it writing some sort of unrecognizable character if i try to write an int variable containing the value 5?Is it writing the ASCII character that corresponds to the value of 5?

That is exactly what it is doing, the ascii equivalent of 5 is ENQ which doesnt have a corresponding human readable letter.

so what should one do if he wishes to write some numeric value to a file?Does one need to derive its ASCII value then write it to the file-wont that become quite cumbersome?

Yes it is cumbersome but this particular function is meant to be a lower level function me thinks, this particular function writes character by character, sort of like a telegraph machine. find a slightly better inbuilt function to handle writing to file.
I am out of touch with cpp but check, you will find better funcs.
quicky008
quicky008 #535
Mar 20, 2021 at 11:39 PM
there are other functions like fprintf() which can accomplish this more elegantly,but i am stuck with a project where the requirement is i must write an int value to a file using fputc () only-therein lies the problem.
Nerevarine
Nerevarine #536
Mar 21, 2021 at 1:28 AM
there are other functions like fprintf() which can accomplish this more elegantly,but i am stuck with a project where the requirement is i must write an int value to a file using fputc () only-therein lies the problem.
Then write a wrapper that efficiently handles the problem.

I.e. do all your integer or character logic outside and feed fputc all the final characters, character by character. If you need to feed in integer which is multi digit, then remember to convert to string or char array and feed it one by one.
aaruni
aaruni #537
Mar 24, 2021 at 5:39 AM
i must write an int value to a file using fputc

Nerevarine is right. You will have to convert your number into a character array, and then call fputc() character by character.

A hint here is, that the character value of a digit is just '0'+i (notice the single quotes around 0). 0 is 47 in ASCII, 1 is 48, etc. So, when you type something like
Code:
int a = '0'+1;
, the compiler will change it to 48+1 = 49 = '1'. Similar for all other digits.
quicky008
quicky008 #538
Apr 6, 2021 at 8:19 PM
^thanks,your suggestion did work out for me and i was able to complete the assignment by following this method.


Does anyone know anything about the Curses library in C? What is it exactly and in which scenarios is it used?

It seems this library is included by default with C compilers in linux but is not present in popular C/C++ ides like DEV C for windows etc.

Is it used to work with graphics?

Are there any tutorials available for it that are friendly for beginners?
Nerevarine
Nerevarine #539
Apr 6, 2021 at 8:38 PM
curses and ncurses..
Yes, its used for rich terminal based GUIs. If you ever opened htop in linux, you would get an idea. Literally every OS in the world starting from lowly puppy linux, solaris to macos support ncurses or curses in their terminal. That gives them an edge over windows when it comes to designing terminal based apps. The command line apps on windows are bastardized versions.
Example :
Glances on Linux,mac runs beautifully because of ncurses support.. Run it in windows and it runs only in server mode.

I think I went on a tangential rant here.. but microsoft has included WSL and by extension curses should be supported although via an emulation layer. Microsoft should just get with the times and just add it natively.

Here's glances on Linux :p
*raw.githubusercontent.com/nicolargo/glances/develop/docs/_static/glances-summary.png

*github.com/nicolargo/glances
quicky008
quicky008 #540
Apr 6, 2021 at 9:15 PM
what's the difference between curses and ncurses?Are they both similar to each other (as far as syntax and other parameters are concerned)?

Also can you post the link to a tutorial or guide on implementing curses in C ?
Nerevarine
Nerevarine #541
Apr 6, 2021 at 9:17 PM
ncurses is the modern implementation of curses, sorry I am out of touch. I myself have never implemented ncurses :(, you should google for better answers (or wait for people here).
quicky008
quicky008 #542
Apr 28, 2021 at 8:13 PM
#include<stdio.h>

struct abc{

int a[5];
float b;

};



int main()
{

struct abc obj={

.a={
{0,1,2,3,4}

},

.b=2.5


};


printf("%d",obj.b);


}

Is this code correct?When i am trying to print the value of obj.b,its outputting 0.Shouldn't it display 2.5 (as the variable was initialized to 2.5 earlier)?
TheSloth
TheSloth #543
Apr 29, 2021 at 8:08 PM
Hi @quicky008, after googling I found out you should %f formatting in printf for float/double values
try this : printf("%d",obj.b);
quicky008
quicky008 #544
May 5, 2021 at 10:30 PM
if there is a string say char s[]="ABCD" and a pointer called char *ptr,how can i obtain the reverse of this string s and store it in ptr?
Nerevarine
Nerevarine #545
May 6, 2021 at 12:07 AM
just reverse the string by your favourite algo and store the entire string in the ptr

char *ptr is a different notation for char[]. Both are interchangeable.

Also, this is how you access indexes incase of char
Both LHS and RHS mean same thing
char *ptr + sizeof(char)*i = str squarebracket i squarebracket
quicky008
quicky008 #546
May 6, 2021 at 12:14 AM
No i was wondering how i could reverse the string using a pointer only,not by any other means.Should have specified it clearly earlier.
Nerevarine
Nerevarine #547
May 6, 2021 at 2:25 AM
Are you given the size of the char * or do you have to calculate that using strlen ?
quicky008
quicky008 #548
May 6, 2021 at 9:57 PM
i can calculate that using strlen and assign it to a dynamically allocated memory for storing character type data(that was created using malloc).Then my plan is to reverse the string and store it in this newly allocated memory space,the size of which is same as that of the original string

today someone gave me this makefile for a particular project:

CFLAGS = gcc -std=c11 -Werror -Wall -Wconversion
LDLIBS = -lcurses -lm
OUTPUT = game
all: $(OUTPUT)

$(OUTPUT): main.o hof.o k.o ui.o
gcc $(CFLAGS) main.o hof.o k.o ui.o $(LDLIBS) -o $(OUTPUT)

main.o: main.c
gcc $(CFLAGS) -c main.c -o main.o

hof.o: hof.c hof.h
gcc $(CFLAGS) -c hof.c -o hof.o

k.o: k.c k.h
gcc $(CFLAGS) -c k.c -o k.o

ui.o: ui.c ui.h
gcc $(CFLAGS) -c ui.c -o ui.o
clean:
rm -r *.o

Can anybody explain whats going on here?I primarily do all my c programming under windows and thus i dont have much knowledge of makefiles.