[GUIDE]**Beginners guide to programming-C,C++,Bash,Python,java**[GUIDE]

Search This thread

Dark Wraith

Senior Member
Feb 18, 2013
250
1,022
Bangalore
"if .. else" conditions is usually taught with "switch" conditions.

switch conditions are better then nested "if..else" and "else.. if" conditions as it doesn't needs to perform all the conditions check like if..else . :)
u should consider including "switch" in tutorial if u can :)

ummm....sure...will add switch statement as well......:good:
 

N00B_IN_N33D

Senior Member
May 27, 2011
1,014
998
Pompano Beach
Yes..you are correct..If....else is a conditional statement...and a conditional statement can be used as a loop...

Code:
int i=0;

if( i <= 50)
{

printf("Hello");

i++;

}

would print hello 50 times....

I'm not too sure about that.. I've never messed with C before, however, I can't imagine the logic being different than Java or C++. Assuming it is similar, your above would only execute the printf statement once.

To be exact, the integer i would be set to 0, then the condition would be checked (0 <= 50 equates to true), the printf statement would be executed and i would be incremented by 1. After that, the program would end/exit the if statement and terminate. However, had the "if" been replaced with a "while" the code would execute as desired..

Could be wrong though.

Sent from my Nexus 4 using Tapatalk
 

Dark Wraith

Senior Member
Feb 18, 2013
250
1,022
Bangalore
I'm not too sure about that.. I've never messed with C before, however, I can't imagine the logic being different than Java or C++. Assuming it is similar, your above would only execute the printf statement once.

To be exact, the integer i would be set to 0, then the condition would be checked (0 <= 50 equates to true), the printf statement would be executed and i would be incremented by 1. After that, the program would end/exit the if statement and terminate. However, had the "if" been replaced with a "while" the code would execute as desired..

Could be wrong though.

Sent from my Nexus 4 using Tapatalk

yes....you are totally right..it will print it just once....no idea what i was thinking

(thats why i should never post after just waking up from sleep)

thanks for the post buddy...I will update the op....:)
 
  • Like
Reactions: N00B_IN_N33D

abcdjdj

Senior Member
May 28, 2012
1,732
3,228
Thane
Nice work bro:)
Btw don't you think that it would be better to use // for comments in all the C snippets rather than # as it will confuse beginners between comments and the preprocessor (#). Also, assigning ints to chars is allowed (at least in Java you can directly assign any value between 0-65535). In C it seems that you can assign upto 255 without type casting. Also, the keyword is class and not Class and the s in string is in upper case.

Please don't get offended or anything, I have no intention of pointing out mistakes. It's just that new comers and beginners should not familiarize themselves with misconceptions. Excellent initiative bro. Keep it up:D:good:
 

Dark Wraith

Senior Member
Feb 18, 2013
250
1,022
Bangalore
Nice work bro:)
Btw don't you think that it would be better to use // for comments in all the C snippets rather than # as it will confuse beginners between comments and the preprocessor (#). Also, assigning ints to chars is allowed (at least in Java you can directly assign any value between 0-65535). In C it seems that you can assign upto 255 without type casting. Also, the keyword is class and not Class and the s in string is in upper case.

Please don't get offended or anything, I have no intention of pointing out mistakes. It's just that new comers and beginners should not familiarize themselves with misconceptions. Excellent initiative bro. Keep it up:D:good:

Yes you are correct.. Just that I had forgotten the // for commenting in C..been working on my tool which is in bash and got the bad habit of commenting everything with #..as for the assigning from char to into...I chose a bad example..I have to include a topic on type casting... and yes I am making a list of changes that needs to be made to the op... Will do so in a few hours... And of course m not offended..its a good thing you are pointing out mistakes.. Feedbacks help streamline the guide until it is 100% correct

Sent from my LegoIce_Fusion™ using xda app-developers app
 

abcdjdj

Senior Member
May 28, 2012
1,732
3,228
Thane
Yes you are correct.. Just that I had forgotten the // for commenting in C..been working on my tool which is in bash and got the bad habit of commenting everything with #..as for the assigning from char to into...I chose a bad example..I have to include a topic on type casting... and yes I am making a list of changes that needs to be made to the op... Will do so in a few hours... And of course m not offended..its a good thing you are pointing out mistakes.. Feedbacks help streamline the guide until it is 100% correct

Sent from my LegoIce_Fusion™ using xda app-developers app

Afaik, declaring an array without giving the size results in a syntax error. In Java as well as C..
 

klincharov

Senior Member
Nov 29, 2013
281
22
34
Wien/Sofia
Can we get some noob explanation on what exactly is a device tree ?

Otherwise awesome post(s), although it makes me sad - I understand the concepts of programming, but don't seem to be suitable to be a programmer ! :)
 

dr.wtf

Senior Member
Dec 25, 2011
1,001
211
if...else just isn't a loop. and it can't be used as a loop. theres no iteration in an if...else statement. you can perform it within a loop but then an if...else statement is still not a loop but the loop in which the statement is is the loop.
 

J-Hope

Member
Feb 21, 2012
43
11
I'm not too sure about that.. I've never messed with C before, however, I can't imagine the logic being different than Java or C++. Assuming it is similar, your above would only execute the printf statement once.

To be exact, the integer i would be set to 0, then the condition would be checked (0 <= 50 equates to true), the printf statement would be executed and i would be incremented by 1. After that, the program would end/exit the if statement and terminate. However, had the "if" been replaced with a "while" the code would execute as desired..

Could be wrong though.

Sent from my Nexus 4 using Tapatalk

Not to be too precise or pedant, but I am pretty sure that since you inizialized i=0 the condition "i<=50" in the while would printf 51 values and not 50 (even if the last one would be 50).

ie: 0, 1, 2, 3, 4, 5....50.
 
Last edited:

chemicalrage

Senior Member
Oct 17, 2011
1,220
763
You forgot the modulo "%" math operator. Btw, lots of typo's. Many places instead of "if's" it is "i's".

Nevertheless, Good job!
 

Dark Wraith

Senior Member
Feb 18, 2013
250
1,022
Bangalore
You forgot the modulo "%" math operator. Btw, lots of typo's. Many places instead of "if's" it is "i's".

Nevertheless, Good job!

Thanks, the i's are not typos bro, read that portion again...by i's i mean the variable i's value...

and yeah i left out modulo operator, switch case and type casting deliberately...i was actually writing it at the moment.. Will add in some time..
 

chemicalrage

Senior Member
Oct 17, 2011
1,220
763
Thanks, the i's are not typos bro, read that portion again...by i's i mean the variable i's value...

and yeah i left out modulo operator, switch case and type casting deliberately...i was actually writing it at the moment.. Will add in some time..

Oh, my bad! Btw, are you a student or are you working somewhere?
 

Spec-Chum

Senior Member
Mar 7, 2013
280
89
No man.,,,working,..wish i was a student and i had an android phone..Would have had loads of time to spend on development

You and me both mate, I'd get loads more "important" stuff done if I didn't have to work instead :D

Nice thread BTW, I hope it really takes off and want to offer my assistance in any way I can. Just PM me if needed, but I'll check on here and try and help anyone, if that's OK?

PS
Code:
int a;
a = 'a';
is perfectly valid C/C++ and will assign the ASCII value of 'a' (97) to the integer a - it'll zero extend the 8 bit value to the 32 bit variable.
 

Dark Wraith

Senior Member
Feb 18, 2013
250
1,022
Bangalore
You and me both mate, I'd get loads more "important" stuff done if I didn't have to work instead :D

Nice thread BTW, I hope it really takes off and want to offer my assistance in any way I can. Just PM me if needed, but I'll check on here and try and help anyone, if that's OK?

PS
Code:
int a;
a = 'a';
is perfectly valid C/C++ and will assign the ASCII value of 'a' (97) to the integer a - it'll zero extend the 8 bit value to the 32 bit variable.

thanks....
yeah adding a guide in 2 mins for type casting..hang on..:)
 

Dark Wraith

Senior Member
Feb 18, 2013
250
1,022
Bangalore
You forgot the modulo "%" math operator. Btw, lots of typo's. Many places instead of "if's" it is "i's".

Nevertheless, Good job!

You and me both mate, I'd get loads more "important" stuff done if I didn't have to work instead :D

Nice thread BTW, I hope it really takes off and want to offer my assistance in any way I can. Just PM me if needed, but I'll check on here and try and help anyone, if that's OK?

PS
Code:
int a;
a = 'a';
is perfectly valid C/C++ and will assign the ASCII value of 'a' (97) to the integer a - it'll zero extend the 8 bit value to the 32 bit variable.

Nice work bro:)
Btw don't you think that it would be better to use // for comments in all the C snippets rather than # as it will confuse beginners between comments and the preprocessor (#). Also, assigning ints to chars is allowed (at least in Java you can directly assign any value between 0-65535). In C it seems that you can assign upto 255 without type casting. Also, the keyword is class and not Class and the s in string is in upper case.

Please don't get offended or anything, I have no intention of pointing out mistakes. It's just that new comers and beginners should not familiarize themselves with misconceptions. Excellent initiative bro. Keep it up:D:good:





"if .. else" conditions is usually taught with "switch" conditions.

switch conditions are better then nested "if..else" and "else.. if" conditions as it doesn't needs to perform all the conditions check like if..else . :)
u should consider including "switch" in tutorial if u can :)

Have updated the OP with the following

1st post

-Type Casting
-Modulus operator

2nd Post

-Changed if to conditional statement
-Added Switch Case statement
-Nesting

Lemme know if anything is wrong or needs to be added...:)
 

Top Liked Posts

  • There are no posts matching your filters.
  • 439
    Hi guys!!!Someone posed a nice question on the forum a few days back asking me if there are any guides on programming(he meant C) in the forum and I actually wondered...There are no beginner's guides for programming as such..There are good extensive guides though and you have to ultimately go through those if you wanna dig in deeper..But i thought about creating a beginner's guide..One that teaches you the following thigs...

    - Basic introduction to a programming(Be it C/C++/Python/Java)

    - An overview over a wide range of topics that are used by every programming language

    - And how to relate it to Android and use it to modify kernels/Roms/apks etc

    So here it goes....

    Basic introduction to programming

    We have in our life always wondered, how come the gadgets we use, hardware we use function so well and how do they understand and perform such complicated tasks. The answer lies in one word "Programming"

    What is Programming and what are these Programming languages??

    -Programming is nothing but a set of commands created by a developer(human being or beings) which is then coded into the machine so that the machine{digital) performs a set of tasks depending on user inputs or independently. In simpler terms, Even a microwave or a washing machine have a set of codes programmed so that they work and do what they are intended to do

    -Programming languages are nothing but ways to communicate something to the machines to make them perform the tasks which you want.There are many languages out there..Famous among them being, C,C++,Java,Python and so many more....

    So why are these programming machines needed??

    -Simple....because the computer understands only one language..the daddy of all languages....Binary language ( 0 & 1)...
    Binary language would somewhat be like ( 0 1 01 0101 010101 0101010101....)...To us it would look crazy,To a computer or any digital device..0 means no electric pulse...1 means an electric pulse and hence everything is done in pulses...

    -So what are these languages(C and all): Proper term would be an interpreter not a language. All these languages do only one thing in different ways : convert whatever you say aka code into 0s and 1s and tell the computer,mobiles, any other device to do something via binary language(010101000101)

    -So why are they needed, well if you can code in 0s and 1s...umm, you'd be a champ..:)(Dont mean it sarcastically,you'd seriously be a champ)..But normally you need such languages to do the job.

    -Which language is the best??Well they all do the same jobs but they are divided into 3 categories
    >High level language
    >Medium level language
    >Low level language

    High level languages are nothing but what we are gonna go through in this thread. C,C++,Java,Python,Perl,bash etc are all examples of high level languages.Why are they named as such. Its because they are the closest to human readable language(taking English as the standard)

    Medium level language is nothing but an intermediate stage between high level language and low level or machine level language.Medium-level language is mainly an output of the programming source code written in a higher-level language.The GNU Compiler Collection (GCC)(Android tool chains you use to compile kernel) uses several intermediate languages internally to simplify portability and cross-compilation

    Low level language is the lowest level of programming. Generally this refers to either machine code or assembly language. As the name suggests it is not close to human readable language. Low-level languages can be converted to machine code without using a compiler or interpreter, and the resulting code runs directly on the processor.

    Example: A function in 32-bit x86 machine code to calculate the nth Fibonacci number:

    8B542408 83FA0077 06B80000 0000C383 #courtesy : Wikipedia
    FA027706 B8010000 00C353BB 01000000
    B9010000 008D0419 83FA0376 078BD98B
    C84AEBF1 5BC3
    (That looks seriously scary to me....:eek:)

    One advantage of this though is that it runs very fast and consumes less memory as an equivalent program in a high-level language will be more heavyweight
    Disadvantage:Low-level languages are considered difficult to use, due to the numerous technical details which must be remembered.

    -Why do you need to all this?? Well i for one think that in order to use a language to code something, you should know the flow of your code. how it goes, what it does and how the end result is processed

    So say you write a code to add two numbers you should know that

    1.You write the code(I'll tell you in later sections how)
    2.It goes to your processor which loads the program into your ram
    3. With the help of inbuilt functions the the intermediate code is generated
    4.The compiler then converts the intermediate code to the machine code
    5.The machine code is then executed

    -Which language is the best and which one do i need to learn?
    Every language has its pros and cons. Which on you learn is up to you and depends on what you want to do. Eg: If you are interested in kernel development, then you need knowledge in linux commands and C programming as the source of a kernel has modules built on C and linux commands are needed for compiling on linux. Similarly, Lets say you wanna create a tool, you can do so using bash(bash is a command line interpreter language: Will tell you in next paragraph),C,Java etc..

    BTW, BASH is a command line interpreter for linux, technically its a programming language but it is basically used in command line(eg: command prompt in windows, terminal in linux)...in lay man's term...a line in bash can be executed from the terminal...eg. cd foldername in linux will come under bash..a bash script is executed line by line on the terminal in linux

    So enough of basics,Lets head over to the next section(Check the Next post)..​
    158
    How to relate it to Android and use it to modify kernels/Roms/apks etc​

    Android is basically an operating system for phones based on a linux kernel and it is an open source operating system.

    >What does open source mean?

    -It means that the files that were required for building or compiling android are available for you to view and modify accordingly. So the main advantage is that you can build your own android OS and kernel from scratch,adding modifications that are sometimes not available in stock android OS.

    -Now I wont go through the tutorial to build kernel or Os from source(There are many tutorials here regarding that)

    -If you download the source code for your phone or pure Android code by google(also known as vanilla code), You will see that it is built on C language. You will see tons of C files and .H files(header files).

    What happens with those C files and why is source code so big?

    -Well at the beginning of the tutorial i had told you that compiling a program file gives you an output in computer language that is flashed on your device's ROM(read only memory).

    -So you must have heard during kernel compilation about compiling zImage.zImage is nothing but the output after compiling your kernel source code.zImage is then packed with ramdisk and you get your desired boot.img for flashing.

    >What is a cross compiler toolchain?

    -Toolchain is nothing but an application or a tool that is used to compile your source code. It is known as cross compiler because you are compiling a piece of code present on your computer not meant for your computer but some other device( Your mobile). Hence the term Cross compiler.

    Note: When you specify arch=arm while compiling using a toolchain, you specify that the output generated is for your arm device( Your mobile).

    >So now what can we do with the source files?

    I will take kernel compilation as an example..

    Overclocking:

    In your source files you will find a file named..acpuclock.c but it differs from mobile to mobile and depends on your mobile's chipset(It is mostly under arch/arm/mach-msm folder...Example for xperia s....(msm 8680 chipset) , it is kernel source/arch/arm/mach-msm/acpuclock-8x60.c

    Now you fill find a strucure in C in that file with the name;

    Source: Xda university adding features to your kernel

    Note: I take this example as it differs from device to device, so the best way would be to take xda's example, you can study other dev's github to learn more about your device

    Code:
    static struct pll pll2_tbl[] = {
     { 42, 0, 1, 0 }, /* 806 MHz */
     { 53, 1, 3, 0 }, /* 1024 MHz */
     { 125, 0, 1, 1 }, /* 1200 MHz */
     { 73, 0, 1, 0 }, /* 1401 MHz */
     };
    
    and 
    
    static struct clkctl_acpu_speed acpu_freq_tbl[] = {
        { 0, 24576,  LPXO, 0, 0,  30720000,  900, VDD_RAW(900) },
        { 0, 61440,  PLL_3,    5, 11, 61440000,  900, VDD_RAW(900) },
        { 1, 122880, PLL_3,    5, 5,  61440000,  900, VDD_RAW(900) },
        { 0, 184320, PLL_3,    5, 4,  61440000,  900, VDD_RAW(900) },
        { 0, MAX_AXI_KHZ, AXI, 1, 0, 61440000, 900, VDD_RAW(900) },
        { 1, 245760, PLL_3,    5, 2,  61440000,  900, VDD_RAW(900) },
        { 1, 368640, PLL_3,    5, 1,  122800000, 900, VDD_RAW(900) },
        /* AXI has MSMC1 implications. See above. */
        { 1, 768000, PLL_1,    2, 0,  153600000, 1050, VDD_RAW(1050) },
        /*
         * AXI has MSMC1 implications. See above.
         */
        { 1, 806400,  PLL_2, 3, 0, UINT_MAX, 1100, VDD_RAW(1100), &pll2_tbl[0]},
        { 1, 1024000, PLL_2, 3, 0, UINT_MAX, 1200, VDD_RAW(1200), &pll2_tbl[1]},
        { 1, 1200000, PLL_2, 3, 0, UINT_MAX, 1200, VDD_RAW(1200), &pll2_tbl[2]},
        { 1, 1401600, PLL_2, 3, 0, UINT_MAX, 1250, VDD_RAW(1250), &pll2_tbl[3]},
        { 0 }
    };

    Now what if you add the following lines to the first structure
    Code:
    {78, 1, 3, 0 },        /* 1516 MHz */
    {83, 1, 3, 0 },        /* 1612 MHz */
    {88, 1, 3, 0 },        /* 1708 MHz */
    
    and 
    
    { 1, 1516800, PLL_2, 3, 0, UINT_MAX, 1250, VDD_RAW(1250), &pll2_tbl[6]},
    { 1, 1612800, PLL_2, 3, 0, UINT_MAX, 1275, VDD_RAW(1275), &pll2_tbl[7]},
    { 1, 1708800, PLL_2, 3, 0, UINT_MAX, 1300, VDD_RAW(1300), &pll2_tbl[8]},
    { 1, 1804800, PLL_2, 3, 0, UINT_MAX, 1325, VDD_RAW(1325), &pll2_tbl[9]},
    { 0 }
    };

    So this would add few additional clock speeds to your device like 1516 Mhz,1612 Mhz, 1708 Mhz, 1804 Mhz

    But this really differs from device to device and you might wanna study the repository of some dev of your device to know the exact changes....

    Same goes for undervolting

    Adding Governors

    What is a governor: A governor is actually nothing more then a behavior profile for your CPU, the governor will tell the CPU exactly what to do in what situation. The term ‘governor’ has nothing to do with it’s function, imagine it was called CPU Presidents! sounds strange but it’s as normal as using the word Governor.(Source : XDA university) (Couldn't improve on this so posted it here)

    How to add a governor??

    Simple, get a hold of your governor file( another C file, by the name cpufreq_govname.c)

    Now for governors you need to edit your Kconfig file. What is Kconfig file. It is your configuration file that tells you compiler how to compile the source file...

    You have to add the lines
    Code:
    config CPU_FREQ_GOV_GOVNAMEHERE
    tristate "'gov_name_lowercase' cpufreq governor"
    depends on CPU_FREQ
    help
    governor' - a custom governor!

    you can head over to http://xda-university.com/as-a-developer/adding-features-to-your-kernel for further details, I will just tell you why you do it...

    After that you have to open makefile and add the line for your governor
    Code:
    obj-$(CONFIG_CPU_FREQ_GOV_Governorname)    += cpufreq_governorname.o
    
    #btw check out the fact that we are adding .o file not .c, I will explain this later
    Now head over to kernel_source/includes/linux and open cpufreq.h(The header file).. Now you have to add
    Code:
    #elif defined(CONFIG_CPU_FREQ_DEFAULT_GOV_Governorname)
     extern struct cpufreq_governor cpufreq_gov_Governorname;
     #define CPUFREQ_DEFAULT_GOVERNOR    (&cpufreq_gov_Governorname)

    # is a comment and compiler ignores those...main thing is extern struct line...It just defines the structure name for your governor...

    How to add these lines...Well you have to scroll through the file until you find similar lines and see the pattern...You have to add these lines according to the exact pattern or else this will throw and error while compiling

    Adding I/O schedulers....



    Just like governors, you have to find your I/O scheduler C file and add it to kernel source/block folder

    and similarly open Kconfig.iosched(not Kconfig)

    and add the lines

    Note: Taking SIO(Simple input output scheduler) as an example

    Code:
    config IOSCHED_SIO
     tristate "Simple I/O scheduler"
     default y
     ---help---
     The Simple I/O scheduler is an extremely simple scheduler,
     based on noop and deadline, that relies on deadlines to
     ensure fairness. The algorithm does not do any sorting but
     basic merging, trying to keep a minimum overhead. It is aimed
     mainly for aleatory access devices (eg: flash devices).

    Now open makefile and add

    Code:
    obj-$(CONFIG_IOSCHED_SIO)    += sio-iosched.o

    Have you guys wondered what is this o file instead of C file we are using..?????

    Well guys, Thats an object file..It is generated by your toolchain while compiling your C files. What the compiler does is that for each C file, it creates a corresponding object(.o file) and links them together at the end of compilation to make the final executable(In our case zImage)...

    so in makefile you dont give the kernel source file(.C), you give the corresponding object file(.O)

    >APKs

    for Apks you need the android SDK(Standard Development Kit) and some basic knowledge about Java and xml coding. I am not that familiar with developing apks so wont give you wrong info. Maybe someone can add in the thread later and i will add it in the post later....:)


    So that's it for now. I hope you find it useful. Please do give your feedbacks(good or bad) so that i can add to this in future

    Credits

    -XDA Ofcourse...
    -Xda university tutorial on Adding features to kernel.Link here
    -Thanks to @broodplank1337.. @abcdjdj. @N00B_IN_N33D and @karan5chaos for finding the errors and telling me about the changes that had to be made

    Cheers..................;)
    141
    - An overview over a wide range of topics that are used by every programming language

    So lets start ...A program be it in whichever language it always begins with one thing

    >Importing necessary libraries

    =What does it mean??

    Lets say you have to get a door fixed by the carpenter..The carpenter would always need one thing to fix your door i.e. his toolbox. Similarly a Program written in any language would need its toolbox aka libraries to perform whatever task you have for it. Some languages require you to add the libraries required at the beginning of the program while some like python or bash do not need it

    Note: In a bash script you need to add the lines #!/bin/bash to tell the interpreter that it is a bash script

    In C/C++ this is how you include a library file

    Note: A library file in C/C++ is actually called a header file and its extension is .h(You might have seen many .h files in any android source files(ROMs or Kernels)

    Code:
    For C :
    
    #include<stdio.h>
    
    For C++
    
    #include<iostream.h>

    Please note that this is a single example where stdio.h(Full form: Standard input/output) file contains utilities that is used to print something on your monitor or scan whatever you type in your keyboard etc..

    For java, you need to get the .jar files. However where do we have to put it is the tricky part. My suggestion as of now would be to use Eclipse and you will be able to see that when you create a java project, Eclipse directly creates the tree structure of your project with a tab called libraries. Just add the jar files there and you are good to go
    or
    trickier method is to create a lib folder or any folder in your project and add the jar files there and then you just have to set a path variable in your environment settings. Add a path of your jar files in your "PATH" variable(for windows)..in linux, just define and export the PATH in your bashrc file

    Note: You will come across import functionality in Java. Import functionality is different and has nothing to with importing libraries. I will explain this at the end of this post

    Ok,So lets assume your environment is set, your libraries have been defined...Now its time to start the actual coding

    >Initializing variables

    Prolly the most important step in this guide. What are variables??

    in simple lay man terms, is something that is used in programming to store a value. Now the value can be a lot of things, value can be a number(eg:. 2), value can be a letter of English alphabet(eg: b), It can be a line of letters(eg: Abc), can be anything....

    so basically a variable will be something like a=2;
    where a is the variable name and 2 is the value...
    similarly a = 'a' (where a would be the variable and the a in quotes would be the a character)

    But its not that simple, in C,C++ and Java you need to explicitly specify what type of variable it is( The compiler allocates memory according to what you specify)
    Note: Python and bash don't need such a declaration( a = 2 is good enough...:) )
    So i C/C++ and Java, variable declaration must be something like
    Code:
    int a;
    char b;
    float c;
    or 
    int a=2;
    char b = 's';
    float c= 2.00

    Where int is integer value,b is character,c is float

    Float is nothing but a decimal value is known as float.Please also note the semi colon(;) after every statement.semicolon in C,C++,java is used to terminate a statement(Except loop)

    =Why it needs to be defined in c/c++/java and not in python/pearl/bash??

    Every compiler is different. In C/C++/Java, when a variable is declared, memory is assigned to it. For eg. If you say int a then variable a is assigned 2 bytes, now you say char a, a is assigned 1 byte. In python/bash/pearl variable memory is dynamically allocated according to its value and therefore we do not need to specify its type.
    So what happens if you assign an char variable(say char a) an integer value
    eg:
    Code:
    int a;
    a= 'a';


    The next section will tell you what happens with the above code....

    Type casting (You can skip this section and come back later if you feel its confusing you)...

    What if you had to convert a float value to an int value or an int to float..or simple a char value to int(Will give its ASCII value which is your job to find out what that is) or as simple as taking input as char...like '0' and converting it to 0...

    That is where type casting comes into picture

    There are two types of type casting

    Implicit and Explicit

    Implicit type casting means that the type is changed automatically by the compiler itself. Explicit is just the opposite..Will show you all scenarios...

    Code:
    int a=2;
    int b=3;
    
    float c;
    
    float c= a+b;  // compiler automatically converts value of a and b to int and calculates(Implicit)
    
    ---------------------------
    
    float a = "10.00";   //float values
    float b = "20.50";
    int c;
    
    c=(int)a+(int)b;       //Explicit type casting
    
    printf("%d",c);
    
    --------------------------
    
    char a= 'a';
    
    int b = a;     //implicit
    
    or
    
    int b = (int)a;  //explicit
    
    Note: Where implicit is required you can use explicit type casting as well to be safe...
    
    -----------------------
    
    now char a = '2';
    
    int b= a - '0'  //used to take number as character input and assign it to integer variable
    
    Again you can write this as
    
    int b = a;
    
    or 
    
    int b = (int)a - '0'

    Now how to know which one require explicit or implicit type casting

    That is your job to find out....

    Hint:

    float to int causes truncation, i.e. removal of the fractional part;
    double to float causes rounding of digit;
    long int to int causes dropping of excess higher order bits

    >Printing and scanning

    Now for any program on this planet to work, you need one basic thing. The program should be able to display something on your monitor.
    Now combine that with taking inputs from the user. You will get an interactive program that takes inputs from a user and prints the result accordingly. the command to print differs from language to language
    Code:
    For C
    
    printf("Hello");
    
    For C++
    
    cout<< "Hello" ;
    
    For Java
    
    system.out.println("Hello");
    
    For Python
    
    print "Hello"
    
    For bash
    
    echo "Hello"

    All of these will give the same output on the screen:

    Hello

    Note: Please note that C/C++/Java requires brackets while python/bash don't.

    Note: Check out the semi-colons again. Python/pearl/Bash don't require a semi-colon to end a statement

    Now comes scanning part. Lets say you want to take two integer inputs from the user.Now we'll combine it with variable declaration and print statement so that u can understand better

    Note: From here on i will mainly show you examples in C or C++ because it would get too confusing for you to handle all the syntaxes together. Once your C knowledge increases, you can easily learn the syntaxes of other languages and try programming

    Code:
    C
    int a;
    int b;
    printf("Enter two numbers");
    scanf("%d %d",&a,&b)
    
    C++
    int a;
    int b;
    cout << "Enter two numbers";
    cin>>a;
    cin>>b;
    
    Java (A bit complex and thats why i wont include Java/python or even bash after this)
    int a;
    int b;
    Scanner s=new Scanner(system.in);
    System.out.println("Enter two numbers");
    a=s.next();
    b=s.next();

    Now in C you will notice two %d %d...%d tells the compiler that its an integer value..it is repeated two times because you take two input values.&a,&b will tell the compiler that store the first input in a and the second one in b. You could also have written it as

    scanf("%d",&a);
    scanf("%d",&b);

    for int its %d
    for char its %c
    for float its %f

    so in order to take character input the syntax will be

    scanf("%c",&a)

    >Now comes the operator part

    Lets go over some basic operations : there are 4 operators in maths or Programming

    sum,minus,division,multiplication

    in programming it would be +, -, /, *

    so a+b would give you the addition of integer values in a and b

    I will write a simple C program with comments after # sign now to take two numbers as input and add them,subtract them, divide them and multiply them

    Code:
    #include<stdio.h>   // initializes the library for standard input/output
    #include<conio.h>  // Another header file containing command to clear the screen
    
    void main()     // for now just learn this,this is how you write the body of a C program,anything that you code inside is executed(no semi-colon here)
    {                     // Curly brackets are used to denote the start of your program body
    
    int a;              // variable initializing
    int b;              // variable initializing
    
    clrscr();         // module to clear screen,not really required but i used it to show how conio.h is included to make this module work
    
    printf("enter two numbers");
    scanf("%d %d",&a,&b);
    
    #now we need to store the value of the result somewhere,so we define new variables
    
    int c,d,e,f;
    
    #to add
    
    c=a+b;
    
    #to subtract
    
    d=a-b;
    
    #to divide
    
    e=a/b;
    
    #to multiply
    
    f=a*b;
    
    #Now to print the result
    
    printf("the result is as follows %d,%d,%d,%d",c,d,e,f);
    
    }   # curly bracket to end the program

    Thats it...:)...now variable e can be taken in float..because if you take it as int. and say a is 3 and b is 2 then 3/2 would give you 1.50,a float value

    Modulus(%) operator

    Modulus operator is used to calculate the remainder of two numbers if divided....

    what are its uses?...Well one major use is you can find out if a number is odd or even

    Code:
    int a=20;
    int b=10;
    int c=a%b;
    printf("%d",c);  // would yield 0 as result
    
    so wen coupled with if
    
    if ( a%2 == 0 )    // Check next post to find out about if...:)
    
    would check if number is even
    
    if a is not even, then it would give a remainder wen divided by 2 and you can easily find out...

    There is one slight problem with it though....what if you have a negative number and divide it with a positive number(non divisible numbers)...Then the remainder comes in negative...

    say -7%3 should return remainder as 1

    but it returns -1..So you have to be careful...Best it to check if remainder is non zero...than exact remainder

    Continued in Post 3
    99
    Tutorial continued


    >Looping


    One of the most important concepts

    What if you had to display your name 50 times????

    Wont it be a bit tedious to write it 50 times using printf statement???

    That is where the concept of looping comes into picture. What is a loop??

    A loop is something that gets executed as many times you want depending on the condition

    There are 3 main types of loop methods(Mostly same in all languages, the syntax only differs)

    1.For loop

    2.While loop

    3.Do while loop

    For loop

    The most widely used probably

    Syntax of FOR loop in C is

    for(condition)
    {
    body of the loop
    }

    that is just the skeleton of the loop. Lets take the problem as our example(you need to print your name 50 times). I will write the program to demonstrate. I'll assume my name : dark wraith to print

    Code:
    #include<stdio.h>
    
    void main()
    {
    
    int i;
    
    for (i=1;i<=50;i++)    // see the contents of the loop in brackets ( i=0 >> stores the value 0 in i; i<=50 >> this is the actual condition,so as long as i's             
    {                                 value is less or equal to 50 the loop's body will run; i++ >> this increments the value by 1 every time the loop is executed
    printf("dark wraith");   // the body of the loop is executed as long as the condition is satisfied
    }                                 // The curly bracket denotes the end of the loop
    
    }

    Ok in the above example i++ is used to increment the value of i. so when the body is executed first time i's value is 1. then i+1 happens. So next time i's value becomes 2 and it goes on till i's value becomes 51. At that point the condition is not satisfied(i<=50) and the compiler exits the loop and the next line after the loop is executed.

    Note: You may also write: for(int i=1;i<=50;i+1) // we are initializing i in the loop itself instead of writing it outside


    Drawbacks and uses: For loop is generally used when you have to do something for many number of times. Drawback is that if you want to execute something only once if a condition is satisfied then you generally go for if..else loop


    While loop

    Its the same as for, which one you want to use is upto you( for is my favourite but that's just personal opinion)

    Code:
    int i=0;
    while(i<=50)
    {
    i++;
    printf("dark wraith");
    }

    Do ....while

    Same as while but with one difference..this you need to find out urself....;)

    Final Note: Looping is a huge concept and you will use it extensively..This is just a beginner's guide so make sure you study more on this

    >Conditional Statements

    What if you wanted to execute something only if a condition is satisfied..In such cases we use the following

    If...else

    As the name suggests if something happens execute this else execute something else....:)..Now what if you wanted to print your name only once if user if the user says y and print no name if user says n

    Code:
    #include<stdio.h>
    
    void main()
    {
    char a;
    printf("Do you want to print a name(y/n");
    
    scanf("%c",&a);                  // stores user input in char variable a
    
    if(a ="y" )                              // checks if whatever user entered is y
    {
    printf("dark wraith");
    else if (a = "n")                    // additional condition to check if user inputs n
    {
    printf("no name");                 // Note that the statement inside a loop body is terminated by semi-colon 
    }
    else                                   // if user enters anything apart from y/n then this is used
    {
    printf("enter a valid choice");
    }
    }
    }             // the three brackets here are one for the last else, one for the if and the last bracket is for closing void main

    Note: You need to be careful with the curly brackets, remember if you start a loop, you also need to close it(solves most of the errors most of the times)

    >Switch...Case statement and nested if...else conditional statements

    Switch...Case...This is a very handy tool in case of a you have multiple conditions and multiple declarations pertaining to those conditions..

    for eg: In case you have used dxdia's kitchen or any other tool of such sort, you will see a list of options with a corresponding number. Say if user presses one, then it shows some options, if he presses 2, then you go to some other options and so on and so forth.Switch and case statement allows you to do that with ease

    eg:

    Code:
    #include<stdio.h>
    #include<stdlib.h>  //header file for exit and break functions
    void main()
    {
    int i;
    printf("Press 1 to say Hi");
    printf("Press 2 to say Hello");
    printf("Press 3 to display XDA on screen");
    printf("Press 4 to exit");
    scanf("%d",&i)
    switch( i ) 
    {
        case 1:                           //Executed if input is 1
            printf("Hi");
            break;                       // Break statement is used to skip the block and go to the next line after                                         the entire switch case block.It is mandatory except the last default case                                        (Though its better to include in that as well) 
        
        case 2:
            printf("Hello");
            break;
        case 3 :
            printf("XDA");
            break;
        case 4 :
            exit(0); 
        default :
            printf("make up your mind and try again..:P");
    }
    
    }

    case statements in bash is my favourite though...Syntax is similar and much more friendlier and you dont need to define a default block or use break to end it....

    Code:
    #!/bin/bash
    
    echo "Press 1 to say Hi"
    echo "Press 2 to say Hello"
    echo "Press 3 to display XDA on screen"
    echo "Press 4 to exit"
    
    read input
    
    case $input in
    
    1)echo "Hi";;      # A case ends with ;; not break
    2)echo "Hello";;
    3)echo "XDA";;
    4)exit;;

    Nesting

    What do you mean by nesting? Nested loops mean a loop iside a loop..It can be nested for loop or while or anything...
    Nesting can be done for anything
    An if statement can be nested inside a for loop (There is an example in array portion for that)

    >Strings and Arrays

    Till now we have only taken one character as an input but what if you wanted to get yes as an input from the user??? then char would fail because it can contain only one character

    Solution: Array data type

    Strings : Arrays are something that can be used to store a string of characters(eg. dark would be a string made of characters d,a,r,k) or a string of numbers(1,2,3,4)
    An array is defined like this: char a[size];
    Where [] denotes that a is an array data type

    Now lets say you define the length: char a[20] : That means a is an array variable which can store upto 20 character data type values

    Similarly int a[20] can store 20 numbers

    But how do you store the value, you cannot just do scanf a[]. I will show you how...:)

    Note: Before i show you how, we need to learn how an array works. think of an array like a train. A train will have compartments. Say 20 bogies. Now you place exactly one passenger in each compartment. Now each compartments has a name. Similarly, say you wanna store a,b,c,d,e,f in an array named abc[7]

    abc[7]=a b c d e f \0
    Index= 0 1 2 3 4 5 6

    Note that the index of the first letter starts with 0 and the array is take note of the last character "\0". Every array in C/C++ is terminated by "\0"(This will be instrumental in whatever you do with arrays)

    Code:
    #include<stdio.h>
    
    void main()
    {
    char a[20];                // array definition
    
    printf("Please enter your name"); 
    
    scanf("%c",&a);    // array is stored normally just like char or int using scanf
    
    // Now to print the array
    
    for(int i = 0 ; a[i] != '\0' ; i++) 
    
    // i= 0 and != means not equal to so the loop will go on till \0 in array i e the last character is not       encountered
    
    {
    
    printf("%c",a[i]);         // Prints array a[0] then a[1] and so on till a[] reached \0
    
    }
    
    }

    There is a header file called string.h that can be used to calculate a string length, or join two string etc.(Thats your job to find out..:))

    Cannot dwelve deeper into arrays but half of your job is done if you understand arrays and loops

    Key points for arrays is : You can access individual elements of an array..like the second character in array
    looping and array so hand in hand, For loop is extensively used

    I will show you one more example.Say you have to find out if the 2nd letter of the array is 'a' (suppose i enter dark, then it should say yes else no)

    So lets start

    Code:
    #include<stdio.h>
    void main()
    {
    char name[20];
    printf("Enter a name");
    scanf("%c",&name);
    
    for( int i=0;a[i] !='\0' ; i++)
    {
    if(a[1] == 'a')       // will check if second character i.e. position 2 has character a
                              // This is an example of nested if statement in for loop
    { 
    printf("Yes");
    }
    else printf("no");
    }

    >Functions

    What if there is a process you are calling hundred times in a program. Say you wrote the logic to add two numbers. But you need to add two numbers 100 times in your program. Won't it be tedious to write the same lines of code so many times when you are doing the same thing again and again

    That is where functions come into picture..

    A function needs to be defined only once and can be called n number of times in your program. How do you define a function

    function name ( arguments,arguments....n) (looks scary) (Maybe an example would help)

    Say you need to define a function that adds two numbers...so....syntax would be

    int add(int a,int b)
    {
    int c=a+b;
    return c;
    }

    That's the function definition..return statement returns whatever the output of the function is...since it is an addition function it will return an integer value that's why we have defined it as int add....(int a,int b) are the arguments or the input required to make the function work.

    How do you call this function...there are many ways....

    int d=add(2,3) 1 way, will store whatever is returned by add(2,3) in variable d
    or
    int p=1;
    int q=2;

    int r=add(p,q) another way, will take value of p and q as input and store result in r

    Hang on!!...Did you guys wonder about the void main we have been using till now????

    Yes it is a function as well.....in fact it is the main function of our compiler...The compiler executes the main function first always...Thats why we write our actual program in void main()......

    Can it be int main() or char main()????

    Well, why not..but remember if you define your main like that then you have to return a value.......so if you write it as int main and dont want any value to return, then you have to add the line....return 0 at the end....or return NULL for char main at the end....Thats why we use void main...void means no return type required...:)


    where do you define functions?? At the beginning or end of your main, not inside the body..

    Warning: If you want to define the function after your main then a special thing needs to done for your program to work,Its up to you to find out)

    Example: Lets say you want to add 3 numbers and print the output

    Code:
    #include<stdio.h>
    void add(int a,int b,int c)               #We can use void here as we don't need return, we can just print the result from here
    {
    int c=a+b+c;
    printf("%d",c);
    }
    void main()
    {
    int a,b,c;
    a=2;
    b=3;
    c=4;
    add(a,b,c);
    
    // Now lets try one more thing
    
    a=4;
    b=5;             // You can change values(Hence the name variable)..:P
    c=7;
    add(a,b,c);
    }

    You can do a range of things with functions. They are just like buttons. When you call them, they start their work...

    >Last topic:Structures

    Pheww....One major problem of C is that it is not object oriented as java or C++ or python. What does object oriented programming mean. Well,
    What if you had a class of 50 students and you would like to store their roll numbers,names,DOBs etc....That would be like totally chaotic and the number of variables would be huge...

    But what if you just had 50 variables..a,b,c and so on....and just by accessing a you could access all the details of a particular student like name of the student,roll no.,DOB etc.....

    that is what object oriented programming is all about. those 50 variables wont be variables but will be known as objects and you would have something called class which will contain the variables name,roll no,DOB etc...

    In C, we dont have classes as such.....Thats why C doesnt really come under object oriented programming...a typical example of a class in java would be...

    Class Student
    {
    string name;
    int rollnumber;
    int DOB;
    }

    Now in java we can store value using objects

    student s= new student("somik",2,26091989);

    Now s would be the object..

    now say one more object is there

    student p=new student("dark",13,19091989);

    so now if you print s.name....you will get output as somik

    if you print p.name..you will get output as dark...

    C doesn't have classes but it has something same called structures..

    Code:
      typedef struct 
    {
              char name[64],
              char course[128],
              int age,
              int year,
    } 
    student;
    
    in main you can access it by
    
    student s;
    
    s.name;

    Next post will tell you how to relate all this to android
    13
    Thanks! Not really for Android (sorry!), but you seriously helped me a lot in getting the hang of C! (Bonus: it's a lot like JavaScript, which I'm already pretty good at!)

    Yeah....even though I feel that JavaScript has much more similarities with bash... there also variables are dynamically allocated like bash....var a=2



    Sent from my LegoIce_Fusion™ using xda app-developers app