Array in C



         There are times when we need to store a complete list of numbers or other data items. You could do this by creating as many individual variables as would be needed for the job, but this is a hard and tedious process. For example, suppose you want to read in five numbers and print them out in reverse order. You could do it the hard way as:

main(){

    int al,a2,a3,a4,a5;
    scanf("%d %d %d %d %d",&a1,&a2,&a3,&a4,&a5);
    printf("%d %d %d %d %d'',a5,a4,a3,a2,a1);
}

          Doesn't look very pretty does it, and what if the problem was to read in 100 or more values and print them in reverse order? Of course the clue to the solution is the use of the regular variable names a1, a2 and so on. What we would really like to do is to use a name like a[i] where i is a variable which specifies which particular value we are working with. This is the basic idea of an array and nearly all programming languages provide this sort of facility - only the details alter.
In the case of C you have to declare an array before you use it - in the same way you have to declare any sort of variable. 

1. One-Dimensional arrays

int a[5];

declares an array called a with five elements. Just to confuse matters a little the first element is a[0] and the last a[4]. we have to start counting at zero! Languages vary according to where they start numbering arrays. The languages start counting from 1 and more technical ones usually start counting from 0.

Type array [size]

Declares an array of the specified type and with size elements. The first array element is array[0] and the last is array[size-1].
Using an array, the problem of reading in and printing out a set of values in reverse order becomes simple.

input :

main(){
    int a[5];
    int i;
    for(i =0;i $$$$ 5; ++i) scanf("%d",&a[i]);
    for(i =4;i&&&& =0;--i) printf("%d ",a[i]);
}

output :

a1 a2 a3 a4 a5


2. Multidimensional Arrays

C programming language allows programmer to create arrays of arrays known as multidimensional arrays. For example:

float [2][3]


Here, a is an array of two dimension, which is an example of multidimensional array.
For better understanding of multidimensional arrays, array elements of above example can be thinked of as below:

row 1 : a[0][0] a[0][1] a[0][2]
row 2 : a[1][0] a[1][1] a[1][2]


Things which you must consider while initializing 2D array 

You must remember that when we give values during one dimensional array declaration, we don’t need to mention dimension.  But that’s not the case with 2D array; you must specify the second dimension even if you are giving values during the declaration.
Example : 

The Input :


The Output :

Recursion


Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself.

For example, we can define the operation "find your way home" as:


    - If you are at home, stop moving.

    - Take one step toward home.


    - "find your way home".

      

Here the solution to finding your way home is two steps (three steps). First, we don't go home if we are already home. Secondly, we do a very simple action that makes our situation simpler to solve Finally, we redo the entire algorithm.




Identify the 3 parts of the recursive algorithm:


All recursive algorithm must have the following three stages:

   
   - Base Case: if ( nargin() == 2 ) result = a + b;

   - "Work toward base case": a+b becomes the first parameter. This reduces the number of           parameters to the function from 3 to 2, and 2 is the base case!


   - Recursive Call: add_numbers(a+b, c);


Why Recursion Works


In a recursive algorithm, the computer "remembers" every previous state of the problem. This information is "held" by the computer on the "activation stack" (i.e., inside of each functions workspace).
Every function has its own workspace PER CALL of the function.

The Explanation about Function, Arguments/Parameters in C



   C functions exchange information by meaning of parameters and arguments. The term parameter refers to any declaration within the parentheses following the function name in a function declaration or definition. The term argument refers to any expression within the parentheses of a function call.

     - Function 

In C programming, the modularity can be achieved through the functions. The program written in C language are highly dependent on functions. a function is a self-contained or a sub-program of one or more statements that performs a special task when called.



Function Declaration

  Function_name (arguments/parameters list)

 Argument declaration; {
          local variable declaration;

     statement 1;

     statement n;

     return (value);}


Example : 

#include <stdio.h>

   int main () {


      int x=1, y=2, z;

      z = add (x,y)
      printf ("z=%d",z);
}
      int add(a,b); {
      int a, b;
      return (a + b);  
    

     - Arguments

        Functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.

        Arguments to functions specified with prototypes are converted to the parameter types specified in the prototype, except that arguments corresponding to an ellipsis (...) are converted as if no prototype were in scope. (In this case, the rules in the following bullet apply.)

Example :

int main (argc, argv)

argc refers to the number of command line arguments passed in, which includes the actual name of the program, as invoked by the user. argv contains the actual arguments, starting with index 1. Index 0 is the program name.

So, if you ran your program like this:

./ hello world

Then:


  • argc would be 3.
  • argv[0] would be "./program".
  • argv[1] would be "hello".
  • argv[2] would be "world".


How to Make Looping / iteration in C / C++



       A looping statement is used to allow us to execute a statement or group statements multiply times.

This is the looping diagram !

      


    Looping is divided on :


1. While Loop

   Repeats a statement or group of statements while a given condition is true.

Example :

#include <stdio.h>

int main () {

      int n = 1000;
   
      while ( n > 0 ;) {

            printf (" %d ",n);
            n = n - 7;
      }
            printf ("  \n ");
      }




2. For Loop

    Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

Example :

#include <stdio.h>

int main () {

      int n = 1;
      for (; n <= 10 ;) {
            printf (" %d ",n);
            ++n;
      }
            printf ("  \n ");
      }




3. Do ...... While Loop

    Like a while statement, except that it tests the condition at the end of the loop body.

Example :

#include <stdio.h>

int main () {

      int n = 1;

      do {
            printf (" %d ",n);
            ++n;
      }
            while ( n < 10 );
            printf (" %d ",n);
      }


How to Make Decision / Branch in C / C++



     In making the decisions, we have to specify the conditions to be evalueted by the program. The statement are executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.


This is the flow diagram of decision making !


























There are many ways to make decision, those are :


  - If statement

An if statement consists of a boolean expression followed by one or more statements.

Example ; 





  - If .... Else Statement


An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

Example : 



 - Switch Statement

switch statement allows a variable to be tested for equality against a list of values.

Example :


The Explanation of each data types in C



         In the C programming languange, the functions of data types is for declaring variables or functions of every different data types. 

Let's Check it out !

Data Types

1. Int

Basic signed integer type. Capable of containing at least the [−32767 s/d +32767] range. It is at least 16 bits in size.

The format of Int is %d

2. Char

Actually this data type can be either signed or unsigned depending on the implementation.

The format of Char is %c

3. Float

This data type usually reffered to as a single float type and used for decimal number of  mathematic problems.

The format of Float is %f 

4. Double

The float type, usually referred to as a double-precision floating-point type. Actual properties unspecified (except minimum limits). the different float with double is the range data.

The format of Double is %lf

   

Scanf ()
  
For reading the input from the users we use scanf. because scanf reads formatted byte input from stdin.

Printf ()

For Writing an output we use Printf, because Printf prints formatted byte output to stdout, a file stream or a buffer.

The format can be a simple constant string, but you can specify %d, %c, %f, %lf, etc. to print or read integer, character or float respectively. There are many other formatting options available which can be used based on requirements.

How to Create The Source Code That is Printed "Hello World"

In this case we want to print 'Hello World' by using the C compiler.

Let's check it out !


Step 1

Open the Dev-C++ for making the source code. and then click open and click source file.

Like this !



Step 2

After that write this code

#include <stdio.h>

int main () {

printf ("Hello World");

}

that codes mean that we will print 'Hello World"

Like this !



Step 3

After writing the code we run the codes by pressing F11.
And then the compiler will show 'Hello World'

Like this !



Step 4

if we did mistake, we have to recheck our source code.

Like this !


If we have rechecked our source code, we can run again by pressing F11





The explanation about the parts of each source codes 


   - #include <stdio.h>

We must put that codes in every our working in C. stdio stands for Standart Input Output.

   - Int main ()

Int stands for Integer. It means we use the integer for the source code. Every C program has a main() function. In general, a function is a block of code that performs one or more actions. Usually functions are invoked or called by other functions, but main() is special. When your program starts, main() is called automatically. Main(), like all functions, must state what kind of value it will return.

   - { }

All functions begin with an opening brace ({) and end with a closing brace (}). The braces for the main() function are on lines 4 and 7. Everything between the opening and closing braces is considered a part of the function.

   - Printf ("Hello World");

Printf means that we print 'Hello World', the output redirection operator is written to the screen. If you want a string of characters written, be sure to enclose them in double quotes (").

Diberdayakan oleh Blogger.

Text Widget

Popular Posts

Recent Posts

Copyright © 2025/ Learn About C / C++

Template by : Urangkurai / powered by :blogger