UPDATED:

How To Make A Simple Calculator By C Happy Coding.......... Happy Coding.......... Happy Coding.......... Happy Coding.......... Happy Coding.......... Happy Coding.......... Happy Coding.......... Happy Coding.......... Happy Coding.......... Happy Coding.......... Happy Coding.......... Happy Coding.......... This blog is under construction!!!!
Namecheap.com

Tuesday, December 27, 2016

Scope of validity


In C, you can declare local and global variables. There are therefore two different areas of validity. The scope of validity specifies where a variable exists and is "visible".

A local variable (or constant) is declared within an instruction block, such as a function. So far we have declared only local variables in the main () function. These are only valid in this function. That is, another function (if you had one) can not access these variables. The same applies to constants. For a different function, these variables and constants are non-existent.

It is important that you initialize local variables before using them! The value that local variables have is not predictable! In other words, at the beginning, there is some value in a local variable. This can be 0, but also any other value. And that is rarely desired.

A local variable is only valid (available) when the function in which it was declared is called. If the function is terminated, the variable is no longer available. This is why it is advantageous for local variables if they immediately assign a value to their values ​​when they are declared so that no unpredictable results are obtained. The best way to initialize each variable is 0.

By default, 0 (zero) is used to initialize global variables. Global variables are valid throughout the program, therefore in all functions. Write the declaration as far as possible at the top of the source code to keep the overview.

#include <stdio.h>

Int global_variable; / * Is initialized with 0 and is valid throughout the program * /

Int main ()
{
  Int local_variable; / * Is initialized with an unpredictable value and is only valid in main () * /

  Printf ("local:% d \ n", local_variable); / * Output the value of the local variable * /
  Printf ("Global:% d \ n", global_variable); / * Output the value of the global variable * /

  Return 0;
}

For a detailed explanation of printf (), keep your eyes on our next post. Here, only the following is anticipated: The% d ensures that an integer is output. In this case, the first parameter specified after the text (string). A newline is generated with \ n.

You can declare local variables that have the same name as declared global variables. In this case, you always "see" the local variable, as the following example shows:

#include <stdio.h>

Int i = 10; / * Global variable i with the value 10 * /

Int main ()
{
   Int i = 50; / * Local variable which is also called i /
                 / * I is initialized to 50 * /

   Printf ("value of i:% d \ n", i); / * I output * /

   Return 0;
}


Local Variable

The variables declared inside the function are automatic or local variables.
The local variables exist only inside the function in which it is declared. When the function exits, the local variables are destroyed.
int main() {
    int n; // n is a local varible to main() function
    ... .. ...
}
void func() {
   int n1; // n1 is local to func() fucntion
}

Global Variable

Variables that are declared outside of all functions are known as external variables. External or global variables are accessible to any function.

#include <stdio.h>
void display();

int n = 5;  // global variable

int main()
{
    ++n;     // variable n is not declared in the main() function
    display();
    return 0;
}

void display()
{
    ++n;     // variable n is not declared in the display() function
    printf("n = %d", n);
}

Output
n = 7
Suppose, a global variable is declared in file1. If you try to use that variable in a different file file2, the compiler will complain. To solve this problem, keyword extern is used in file2 to indicate that the external variable is declared in another file.
Test it yourself!

Monday, December 26, 2016

Data types and allocation In C


Let's look at the individual data types. In C, a distinction is made between integer and floating-point types. The integer types include char, short int, int, and long int. The floating-point types include float, double, and long double. For each of the 4 integer types, a signed and unsigned variable or constant can be declared. By default, all integer types are signed (signed). This means that you can store both negative and positive numbers. With the keyword signed in front of the type, you can still mark that extra. Whether you are Int i; or Signed int i; Is indifferent. If you only want to store positive integers, you can declare a unsigned type with unsigned: Unsigned int i; The advantage is that unsigned types can represent larger numbers. The reason for this is that for signed types the most significant bit is used as a sign bit. With unsigned, however, it can be used to display the number. By the way, it does not matter if you write long int or long. Likewise, only short can be used instead of short int. The following table lists all data types that you can specify as a type when declaring a variable or constant. The range specifies the smallest and largest possible number that can be stored. The size is the memory space consumption in the working memory.

Integer types:

Char Type:



The long data type often has 8 bytes (64 bits) on 64-bit systems. The size of the integer types is not defined in ANSI-C. But the order is as follows: Char <= short <= int <= long The type short must be at least 2 bytes long and at least 4 bytes large. If you are interested in the exact size on your system, you can look at the limits file header file. It is easier, however, as mentioned, with the sizeof operator.

Floating point types:


Allocation

After a variable has been declared, you can specify the value to store. This process, in which one tells the variable what value to store, is called an assignment.
Example: I = 10; Assume that the variable i is of type int, then the value is assigned to the value 10 (an integer). After this, variable i stores this value. In general it can be said: Variable = value; Instead of variable, you set the identifier of the variable to which you want to assign a value. The assignment operator follows the right of the identifier. The assignment operator ensures that data is "transported" to the variable and signals that it is an assignment. To the right of the assignment operator is the value that the variable should store. This can also be a different variable, then the value of the right variable is assigned to the left variable, ie copied to the left variable. It is always transferred from right to left. IMPORTANT: The assignment operator = is NOT a comparison for equality! The variable, which is on the left, has the right value, but the equality operator (==), which you will get to know later on, must be strictly distinguished from this! The meaning of the = in C is thus different from what you probably know from mathematics. You already know the initialization of variables during their declaration. Here again for the repetition: Type Identifier = value; For example: Int i = 0; If several variables of the same type are agreed, it is also possible to initialize only some of them. An example: Int i, j = 20, k = 100, l; Here, we declare the variables i, j, k, and l. We immediately assign values ​​to the variables j and k, while the others do not. The assignment of constants is very important. Without assignment, constants would be useless. Const int repetitions = 10, mode = 1; Then the constant repeats with the fixed value 10 and the constant mode with the value 1.

Thank you for being with coder mania BD.

Friday, December 23, 2016

Variables and Constants

Data must be stored continuously during the program sequence or data must be read in. When the user makes an input, this input must be stored somewhere in order to be able to evaluate it later. To store data, there are basically two possibilities: storage in memory or in a file. A database is ultimately only one file.

The main memory has two main problems: it is volatile, so the data is lost at the latest when you turn off the PC. And its capacity is usually too limited to accommodate larger amounts of data. The latter is increasingly relativized by falling prices for memory modules, but compared to hard disk sizes it is still "small". In addition, the requirements are always increasing with the calculation work. 

But the memory has an advantage: It is fast! Much faster than any hard drive. How fast depends on the type of memory and its construction. In principle, the closer to the processor, the faster the memory module should be. So L1 cache before L2 cache before RAM modules. This topic is not intended to deal with this issue.

To process data, you will always load it into the working memory. At least part of it, depending on the size of the data and the available memory. If data are also available after the end of the program, they are stored in a file or transferred to a database management system. I will treat the file access in a later post.

Now to the actual topic:  To store data in the working memory, one needs in the programming variables. 
Variables are certainly known to you from mathematics. Here they stand for placeholders. This is similar in programming. A variable reserves a certain amount of memory in memory. Thus, a variable can reserve about two bytes, in which data can then be stored.

Variables can be of different types (data types). Depending on the type, the reserved memory space is of a different size and different data can be stored. For example, variables of type int have a size of 2 or 4 bytes. How much accurately depends on the word length of the processor register and the compiler used. A register is an internal memory space of a processor. This is the fastest available memory for the CPU. For this purpose, the number of registers and thus the memory size is strongly limited. Say: There are only a few.

You can determine how much memory a variable actually needs on your system using the size of operator (more on this later). Depending on the type, however, not only a differently large memory space is reserved, but different values can also be stored. For example, int can only store integers (about -10, 12, or 20007, and you will see that characters such as "a" can be stored as a number); floating-type variables record floating-point numbers (about 1.3, 40.345313) can.

Constants must be distinguished from variables. A constant corresponds to a variable, but with a fixed, non-variable value. This means that a constant must be initialized (defined) at its declaration. So if you want a constant, you must assign a value to it. And it keeps this as long as it exists (which does not necessarily have to be the end of the program).

C compilers do not complain about this (no error, no warning) if you do not perform the initialization, but you can not begin with the constant at a later time. For example, if you try to assign a value to the constant a, you get the error message from GCC: Error: assignment of the read-only variable »a«. You only have the "opportunity" at the declaration.

A declaration is the announcement to the compiler that something (here: the variable) exists. If a is declared as int, the compiler knows: The variable a exists and has the type int. If a variable is assigned a value before its use, especially at the declaration (ie an initial value), it is referred to as an initialization.

If a value is assigned, it is called a definition. Initialization is a special form of definition. As far as the linguistic subtleties that had to be mentioned. As shown in Fig.

Declaration
Notification, e.g. Tell the compiler that a variable exists, which identifier (name) it carries, and what type it is.
Definition
value assignment, e.g. A previously declared variable is now assigned a value.

To declare a variable, you need to know two things:

How do I call my variable? Each variable requires a name (identifier), which can be used to address them. What is my variable to be? Depending on which values are to be stored, a different type must be selected. Sometimes it is also necessary to consider the storage space consumption. When you choose the name (identifier), you are bound by some rules. The name can only consist of alphanumeric characters (such as "a", "X" or "3", BUT NOT "§" or "$"), and the underscore "_". The name must start with a letter or the underline. There must therefore be no number at the beginning of the name.

By default, the identifier should not contain more than 32 characters. In addition, there are some other things to consider that make sense, but are not a duty. The identifier should be as meaningful as possible so that you can know later what the variable is good for. This is difficult for variables such as a, k1, j, and y3.

The identifier should therefore indicate the purpose of the variable. The purpose of the data storage is, of course, clear, but the question arises, which data should be stored and when and why the variable is used. However, try to keep the length of the identifier as short as possible. So as short as possible, as long as necessary.

So better count than This_is_my_newvariable as an identifier. Count variables are often also designated with the letters i, j, k, etc. Here, therefore, only i (like index) would be used.

Let's look at a variable declaration:

Int i;

You already know the integer type int. From this, the variable i exists after this line. The declaration is indicated by a semicolon; completed. In general it can be said:

Type identifier;

Several variables can be easily declared in one line. Example:

Int a, b, c;

As you can see, each identifier must be separated by commas. In the example above, the variables a, b, and c were declared int (each type int). If you also need one or more variables of a different type, this declaration must be placed in an extra line. Such as:

Int a, b, c;
Char z;

Here the variable z of type char was also declared. Because char is a type other than int, the declaration must be on its own line. In principle, you could also write the second declaration in the same line if it is after the semicolon. There is the semicolon.

IMPORTANT: In ANSI-C (C89 / C90), it is not allowed to simply place the variable declaration anywhere in the statement block. Declarations must ALWAYS be at the beginning of an instruction block. 
Example:

Int main ()
{
  Int a, b, c;
  Char z;

  / * Only now follow further instructions ... * /

  Return 0;
}


Attention: The next two programs contain an error!
These examples will not work with real (older) C compilers.

Example 1:

#include <stdio.h>

Int main ()
{
  / * ERROR: Program code BEFORE the variable declaration! * /
  Printf ("The program has started ...");

  Int a, b, c; / * The declaration is only made here ... /
  Char z;

  / * Only now follow further instructions ... * /

  Return 0;
}

Example 2:

Int main ()
{
  ; Int a, b, c; / * Pay attention to the semicolon at the beginning! * /
  Char z;

  / * Only now follow further instructions ... * /

  Return 0;
}

In Example 1, you will probably find the error easier than in Example 2. In the first example, there is an entire "meaningful" statement before the variable declaration. In the second example, the programmer is much more difficult. The only thing that is wrong here is a "lost" semicolon. It is before the variable declaration and is therefore considered by the compiler as an entire statement. Therefore, a mistake.

By the way: The line / * Only now follow further statements * / is marked with / * and * / as comment. Comments are ignored by the compiler. I'll go into later.

Now to practice: 

All upper "wrong" examples work with GCC - without error messages, without warnings. This is because GCC is also a C ++ compiler and also supports the newer C standards. As of C99, variable declarations are no longer required at the beginning of the statement block. In C ++ anyway not. Even with the command-line parameter -std = c89, the source code can be easily translated. GCC should still allow newer extensions as long as they do not conflict with the old C standard. The "error simulation" becomes perfect only if you also add the parameter -pedantic.

If you want to test an old, ancient C compiler, you can try Borland Turbo C. But please do not make any complaints to me, something should not work as desired (or Turbo C do not run). ;-) Turbo C comes in version 2 from the year 1989. Turbo C also knows no new standards guaranteed.

Although this is not the case, in this tutorial, variable declarations are always at the beginning of an instruction block. If you want to write pure C code, you should do that too.

A constant is declared by placing the const keyword before the type. Keywords are reserved identifiers. These are names that you can not use as identifiers. They may, for example, Do not declare a variable with the name "const". An example of a constant:

Const float PI = 3.14159;

Here the constant PI was declared and initialized (defined). Otherwise, the same applies to the declaration of variables.

Structure of a C program (updated)

After previous post The Basic structure of C....

Programming is done in the form of instructions that contain the individual programming lines. In the Hello World program, the text hello, world! On the screen. 
Basically, only a single programming line is provided:

Printf ("hello, world!");

But that would not be the case. Test it yourself: Just write this line and let the "program" compile and run. The compiler will then report an error. The compiler complains that it can not find a main () function.

A function includes one or more programming lines and is intended to serve a particular purpose. The purpose of our main () function in the Hello World program was to issue a text.

Each C program must have a main () function, but only one. If there are several main () functions, the compiler reports an error because the identifier (= name) main has been used more than once. The word main means in English as much as main, in C the main function is meant, since this is called first. The compiler always searches first for the main () function. The main () function represents the program entry point. After the program is started, the main () function is called first. How it then goes, stands in main (), or is your decision.

It is also common among C programmers when functions are used to write parentheses () behind function names. This notation again suggests that abc () is a function. Abc without brackets is something else (usually a variable, more on that later). If you can not imagine a lot of functions at the moment, this is not bad. At the present time, it is enough to know that a function is for a specifically delimited purpose (for example, outputting text, printf () is also one) and one or more programming lines.

Let's take a look at the main () function. The shortest form would be the following:

Int main ()
{

}

This is also the shortest program! But it does not matter. Type the following source code and test the program:

Int main ()
{

}

The program does not do anything, but the compiler does not report any errors - unless you have mistyped. This indicates that the program is operational. In C, it does not matter if you write something big or small! C is a case-sensitive language (nice-slipped), so it is case-sensitive. If you were to write something instead of main, this would cause the compiler to fail because it misses the main () function (lowercase). The Main () function could be any other function (although a different name would be used here, the more "talking" and better the function name describes the subtask of the function, the better).

Test the following program:

#include <stdio.h>
Int Main ()
{
  Printf ("This line will never be displayed!");
}
Int main ()
{
  Printf ("The main function has been executed!");
}


Look for the exact spelling! The two function names differ only by the first letter, and here only by the upper and lower case! The first function is called Main () and the second main (). After the start, main () is executed and the text The main function has been executed! On the screen. Because after the line with printf ("The main function was executed!"); Nothing will follow, the program will terminate.

Let us return to the simplest version, and let's look at the "components" more closely:

Int main ()
{

}


Main, as mentioned several times, is the function name. In this case, the word int. Int (short form for integer) is one of several possible return types. Functions may return values. Or. A function must return a value if so specified. That int stands before a function name means: This function must return a value of type int.

Let's take a step back. Consider the following scenario: You want to perform a mathematical calculation. For the sake of simplicity, this is supposed to be the square root of a number. The function you have written does this task. To do this, the function takes data (input, e.g., an input from the user), performs the calculation by (processing), and returns the result (output). This process is also known as the EVA principle (= input-processing output).

The data takes the function in the form of parameters. Here we would be again with the brackets (). What is between the parentheses is passed to the function. In line

Printf ("hello, world!");

The text (more precisely, a string, so-called string strings in C, more to be called later) hello, world! To the printf () function as a parameter. What is enclosed in quotation marks "..." belongs together and is passed as a string (string) to printf (). In theory, any number of parameters are possible, depending on how you have defined this as a programmer.

At this point again - forcing - something to anticipate: int is an integer type. Main () must return an integer (positive or negative integer, -10, 70, 0, 30000, whatever). In order to return the return value, which is quasi the result of the processing by the function, there is return. Return you already know:

Return 0;

Use return to specify the value that a function returns. Here the number 0. the return also ends the execution of the function. In main () returns the entire program. So if main () has the return type int and has to return an integer (int), why does the shortest possible program (see above) work anyway? Quite simply an exception, the C-standard also allows. But it is not nice. Therefore: Leave main () always return a value. 0 (zero) usually indicates that the program has been executed correctly.

As already mentioned, there are also functions without a return value. You may see the following variant of main ():

Void main ()
{

}


Void means "nothing", here: NO return value. Void, you can also write between the brackets to point out that no parameters are needed and are not allowed. (There is an exception: parameters can be passed from the command line to main (), but main () must look different, more in chapter 12.)

Void main (void)
{

}

Test it yourself. The program can be compiled without errors and is also running. However, GCC issues a warning: Warning: The return type of "main" is not "int". Main () must be of the int type according to the C standard. Void works (with a warning), but should not be used.

One is still missing: {} (curved brackets) enclose an instruction block. An instruction block includes several programming lines (or one).

In summary, one can for

Int main ()
{

}


So say:

  • Int = return value, here int for an integer
  • Main = identifier (name) of the function, main has a special position and stands for the main function
  • () = Parameters between the parentheses; This data is passed to the function
  • {= Opening curved bracket, beginning of the statement block, this bracket follow the instructions
  • } = Closing curved bracket, terminates the statement block, after the last statement

The following version of the example would also be valid:

Int
   Main
(
  ) 
{
}


This stylistically "impossible" variant can be compiled without errors and without warnings. This is because the compiler decomposes the source code into individual parts, blocks (so-called tokens), and evaluates them for themselves. Spaces, line breaks, tabs, etc. do not matter. How does the compiler know when a program line is off? The semicolon serves this purpose; At the end of a "normal" line like we had it after printf ():


Printf ("hello, world!");

In languages where semicolons (semicolons) are not mandatory at the end of the lines (eg BASIC, but also in JavaScript, it is not mandatory!), You can not distribute statements over several lines (because the compiler does not know where the line is over). What is important here is only: pay attention to the; At the end of the lines!

A word still to indentation: Although spaces do not matter to the compiler, I have inserted the lines within the statement block by 2 spaces in the Hello World example. This helps to preserve the overview when you have multiple nested statement blocks (you'll see later). The number of spaces you indent, or the number of tab positions, is left to you and is a question of the style or conventions you specify.

#include <stdio.h>
Int main ()
{
  Printf ("This line is 2 spaces from the left.");
  Return 0;
}


Include header files with #include


One thing is still missing to fully understand the Hello World program. There was the line:

#include <stdio.h>

The double cross # has a special meaning: it draws a statement to the preprocessor. The preprocessor is a part or its own program, which belongs to the compiler. The preprocessor processes the source code before the actual translation process. Here it does the following: It loads the stdio.h file and copies the entire text (source) from the specified file to the location where the #include statement is located.

Stdio.h is a so-called header file. A header file (also known as an include file) usually stores declarations. A declaration is a notification to the compiler. For example, you can use a declaration to tell the compiler what functions exist. What the function actually does is elsewhere (= definition).

The compiler then sees the statements from the header file as if you had written them directly to the source file. Typically, #include statements are at the beginning of a program. It would also have been possible to swap any source code into a file and then insert it by #include. But I can advise against this and is not the point.

Stdio.h contains declarations of the standard functions required for input and output. If you need printf (), you must include stdio.h. Stdio.h (std as standard) belongs to the C Standard Library (C standard library). That brings every C compiler with. If you want to know more: Standard C Library at Wikipedia.

Depending on where (!) Is the contained file, the filename must either be between brackets <> or quotation marks. This is very important and a frequent beginner error! If the file is located in the standard directory for contained files (each compiler offers the possibility to specify such a directory), use brackets <> (or for standard library files). If the file is in the current (!) Directory (that is, where the source file of the program is), you use quotation marks "". Compare:

#include <stdio.h>

#include "LocalHeaderdatei.h"

I would like to point out once again how important it is to try out what is read. Test every example and everything new! Write smaller programs for exercise, if possible. Programming is only learned through a lot of practice!

Differences between C and C ++

C ++ is a successor to C and was developed by Bjarne Stroustrup in AT & T-Labs. C ++ is down-compliant to C, which means that C programs can also be compiled with a C ++ compiler.

Theory and practice can be diverted here.
The programming language C has been standardized several times (see variants of the programming language C at Wikipedia), of which C ++ is based on the 1990 standard (C90, ISO / IEC 9899: 1990). C was expanded afterward. The following C standards (C95, C99) play a subordinate role in practice, but these extensions could not be considered in C ++.

On the other hand, extensions that brought C ++ (!) Found their way into C standards. Thus C ++ language elements were integrated into C.

In addition to the different standards, non-standard implementations of the C ++ compiler can also create problems.

However, what is complicated here is less dramatic in practice. I just want to point out that there is not always a 100% downward compatibility.

What to start with? C or C ++?


Basically: Both are possible. Beginning with C ++ is certainly more complex and time-consuming (time and patience problem) - because of the larger number of language elements.
We suggest you start with C

As mentioned above, C ++ is the "larger brother" of C, backward compatible with it (except for minor exceptions). All C language elements are also available under C ++. They are learning new things when switching to C ++, and C ++ offers better solutions (object-oriented programming). Conversely, if you first need to learn C ++, and then later you have to write a pure C program (which has to run on a "pure-breed" C compiler), you first have to learn what was not yet available in C.

If you primarily intend to program hardware or microcontrollers, also speaks more for pure C. C compilers, there are more platforms than C ++ compilers. For every exotic processor, there is usually a C compiler. And if not, then often remains more assembler.

If you are completely new to the programming (beginners), speak also a lot of a language with fewer language elements, in order to keep the learner motivated. Otherwise, the overview of the whole is often lost. Another point for C.
Namecheap.com

Popular Posts