C programming introduction

Thread Starter

anukalp

Joined Jul 28, 2018
158
Hello ACC Members

My name is a anukalp gandhi. I am 2nd year student of electronics. I have read some old forum posts. Experts suggest that we should have a good knowledge of c programming before starting programming of the microcontroller. I still feel that I am not good at c programming. I have thought that I will not start programming of microcontroller until I become good at c programming.

I have some books and I'm also reading some online tutorials. After reading, I try to make my own programs. Sometimes I get successful and sometimes I fail

Question : What is array in c.

Answer : An array is used to store a set of data elements with the same data type.

For example, if we want to store six integers, we write in C:

Code:
int numbers[6] = { 0, 2, 1, 0, 1, 5 };
For example, if we want to store five characters, we write in C:

Code:
char letters[5] = { 'H', 'e', 'l', 'l', 'o' };
For example, if we want to store five strings, we write in C:

Code:
char strings[5] = { "Red", "Orange", "Yellow", "Green", "Blue" };
integer size
Code:
/* size of int depend on hardware consider it is 2 bytes  so one integer take 2 bytes memory space*/

/* in the example of array there are six integer variable. Each take 2 bytes memory space */

int point[6]={ 0, 0, 1,  0, 0, 0};  /* It store six integer */
character size
Code:
 char drive[5] = { 'C', 'D', 'E', 'F', 'G' }; / it store five character, */
/* single character take one byte memory space so there total five. Each five character take one byte memory space */
Question : What happen if we use array and what happen if we don’t use array

Answer : if I want to store two or three numbers I’ll write in c
int x = 2, y =4, z = 9

But what happen if I want to store large numbers ie 100 variables.

I can do it this in two way
  1. I have to declare and initialize 100 variable but I don’t think this is good way so I have another way array
  2. I’ll use array to store 100 variable it’s good way because I don’t need to declare and initialize every time so I have to do only declare and initialize array to store 100 integer
Code:
Int number[100] = {  5 , 5, 8 … up to N};
I think the array is used for this reason I want to know if I have made a mistake in understanding, please let me know
 

qrb14143

Joined Mar 6, 2017
112
At a glance, the array is convenient because it allows you to store multiple values neatly in a container of sorts. You can then perform actions on the whole array or perform actions on a single array element. It also makes it easy to perform repeated actions to a number of elements using loops. For example:
Code:
int weights[5]={ 45, 67,  89, 77, 98};

for(int i = 0; i < 5; i++)
{
printf("The weight is %d\n", weights[i]);
}
It's been a while since I wrote any C code so hopefully my syntax is correct. Hope this clarifies slightly why it is often useful to store multiple values in an array rather than creating multiple variables.
Those who are more in the know will be able to advise on the implications for memory allocation and suchlike.
 

WBahn

Joined Mar 31, 2012
30,075
Hello ACC Members

My name is a anukalp gandhi. I am 2nd year student of electronics. I have read some old forum posts. Experts suggest that we should have a good knowledge of c programming before starting programming of the microcontroller. I still feel that I am not good at c programming. I have thought that I will not start programming of microcontroller until I become good at c programming.
In general, it is good to have a good grasp of programming logic which is, more than anything, about good algorithmic thinking -- being able to break a problem down into clearly defined decisions that need to be made and simple tasks that need to be performed in order to solve the problem. Developing good programming skills in C is a good framework in which to do this, particularly if you want to apply it to microcontroller programming, but it is not an absolute prerequisite -- many people use microcontroller programming as their vehicle to learn programming and algorithmic thinking. You just need to start small and go slower if you go this route, but it works quite well as it gives you a solid, physical context to work within.

For example, if we want to store five characters, we write in C:

Code:
char letters[5] = { 'H', 'e', 'l', 'l', 'o' };
For example, if we want to store five strings, we write in C:

Code:
char strings[5] = { "Red", "Orange", "Yellow", "Green", "Blue" };
This last one is incorrect. Look at both of these and you will see that letters and strings are both the same type of variable, namely an array of values of type char.

A string in C is an array of char values that happens to be NUL-terminated, meaning that the last value is a zero (which has the escape code '\0'). So the string "Hello!" could be initialized as

Code:
char string[7] = {'H', 'e', 'l', 'l', 'o', '!', '\0'};
In order to do what you are doing with your colors example, you need to store an array of pointers to those strings.

Code:
char *strings[5] = { "Red", "Orange", "Yellow", "Green", "Blue" };
Each of the strings is stored somewhere in memory as a NUL-terminated array of char values. What gets stored in the strings array are the addresses of the first byte in each of those arrays.

Pointers are a more advanced topic that you probably want to put off for a while.

I think the array is used for this reason I want to know if I have made a mistake in understanding, please let me know
Not so much a mistake, but probably a bit too narrow of a new.

Arrays are particularly useful when we have a collection of values of the same type that we want to programmatically access (meaning that our program can calculate which value to access at run time instead of it being hard coded.

Imagine if you had five values stored in five different variables, x0, x1, x2, x3, and x4. Now you ask the user which value (numbered 0 through 4) they would like to double and they enter 3. Write the program to do that. Now store those same five values in an array and write the same program.
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
Imagine if you had five values stored in five different variables, x0, x1, x2, x3, and x4. Now you ask the user which value (numbered 0 through 4) they would like to double and they enter 3. Write the program to do that. Now store those same five values in an array and write the same program.
Thank you very much sir, Is this both programs that you want me to do

Program without array

Code:
#include <stdio.h>

#define double 2

int main ()

{
    int x0 = 0, x1 = 1, x2 = 2, x3 = 3, x4 = 4;
 
    int value ;
 
    printf ("Promote user to Enter Value : ");
 
    scanf("%d", &value);
 
    value = value * double;
 
    printf("Double value : %d", value);
 
    return 0;
 
}
Program with Array

Code:
#include<stdio.h>

#define double  2

int main ()
{
    int value,  i = 0;
 
    int number[5] = { 0, 1, 2, 3, 4 };
 
 
    printf("Promote user to Enter value  : " );
 
    scanf("%d",&number[i]);
 
    value = number[i]* double;
 
    printf("Double value : %d", value);

    return 0;

}
 
Last edited:

WBahn

Joined Mar 31, 2012
30,075
Thank you very much sir, Is this both programs that you want me to do

Program without array

Code:
#include <stdio.h>

#define double 2

int main ()

{
    int x0 = 0, x1 = 1, x2 = 2, x3 = 3, x4 = 4;

    int value ;

    printf ("Promote user to Enter Value : ");

    scanf("%d", &value);

    value = value * double;

    printf("Double value : %d", value);

    return 0;

}
Program with Array

Code:
#include<stdio.h>

#define double  2

int main ()
{
    int value,  i = 0;

    int number[5] = { 0, 1, 2, 3, 4 };


    printf("Promote user to Enter value  : " );

    scanf("%d",&number[i]);

    value = number[i]* double;

    printf("Double value : %d", value);

    return 0;

}
No. You just have five values. Those five values are either stored in five separate variable or they are stored in a five-element array.

You ask the user which of those five values they want to double and you then double that value.

Perhaps this might make it more clear using the context of an entire program.

1) Write a program that asks the user for five integer values.
2) Print them out as a comma-separated list of values on one line.
3) Print out the sum of the five values on the next line.
4) Ask the user which value they want to double, with 1 being the first value entered and 5 being the last value entered.
5) Print out the five values again.
6) Print out the sum of the five values on the next line.

So you might have something like this:

Enter value #1: 42
Enter value #2: 93
Enter value #3: 17
Enter value #4: 80
Enter value #5: 71

Values: 42, 93, 17, 80, 71
Sum: 303

Which value do you wish to double (Enter 1 - 5): 3

Values: 42, 93, 17, 80, 71
Sum: 320

Write this program twice. First using five distinct variables and the second using an array with five elements.
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
assume I have three numbers a = 4, b = 6, c = 2

This program exactly does what you said

Code:
#include<stdio.h>

int main()

{
    int a = 4, b = 6, c = 2;
  
    int user_address;
  
      
    int addressa =  6422300, addressb = 6422296,  addressc =  6422292;
  
   
  
    printf("\n address of a : %d ", addressa);
  
    printf("\n address of b : %d ", addressb);
  
    printf("\n address of c : %d ", addressc);
  
 
    printf ("\n Promote user to Enter Value : ");
  
    scanf("\n %d", &user_address);
  
  
if (user_address == addressa)
    {
        a = a * 2;
      
       printf(" double value of a %d", a);
    }

if (user_address == addressb)
    {
        b = b * 2;
      
       printf(" double value of b %d", b);
    }
  
if (user_address == addressc)
    {
        c = c * 2;
      
       printf(" double value of c %d", c);
    }
  

    return 0;
}

address of a : 6422300
address of b : 6422296
address of c : 6422292
Promote user to Enter Value : 6422292
double value of c 4

address of a : 6422300
address of b : 6422296
address of c : 6422292
Promote user to Enter Value : 6422296
double value of b 12

address of a : 6422300
address of b : 6422296
address of c : 6422292
Promote user to Enter Value : 6422300
double value of a 8
 

WBahn

Joined Mar 31, 2012
30,075
Why should the user enter arbitrary numbers that you have arbitrarily assigned and that don't even have any relationship to the address of the associated variables in order to tell you which value they want to double?

When you ask them which value they want to double, then indicate it using a simple number. The natural approach is for them to enter a 1 if they want to double the first number, a 2 if they want to double the second number, and so on. In my first suggested exercise (which I think is the one you are trying to write) I had them enter 0 for the first number in order to make it easier to map to the array.
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
Why should the user enter arbitrary numbers that you have arbitrarily assigned and that don't even have any relationship to the address of the associated variables in order to tell you which value they want to double?

When you ask them which value they want to double, then indicate it using a simple number. The natural approach is for them to enter a 1 if they want to double the first number, a 2 if they want to double the second number, and so on. In my first suggested exercise (which I think is the one you are trying to write) I had them enter 0 for the first number in order to make it easier to map to the array.
If this is the case then I would be do it in following manner
Code:
#include<stdio.h>

int main ()
{
    int a = 42, b = 93, c = 17, d = 80, e = 71;
    
    int number;
     
   printf("Promote user to Enter number  : " );
   
   scanf("%d",&number);
  
    if (number ==0)
    {
        a = 42 * 2;
     
        printf("Double value : %d", a);
    }
 
     if (number == 1)
    {
        b = 93 * 2;
     
        printf("Double value : %d", b);
    }
 
     if (number ==2)
    {
        c = 17 * 2;
     
        printf("Double value : %d", c);
     
    }
 
     if (number == 3)
    {
        d = 80 * 2;
     
        printf("Double value : %d", d);
    }
 
     if (number == 4)
    {
        e = 71 * 2;
     
        printf("Double value : %d", e);
    }
    return 0;
}
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
Same program with array

Code:
#include<stdio.h>
int main ()
{
    int array[5] = { 42, 93, 17, 80, 71 };
  
    int number;
   
     printf("Promote user to Enter number  : " );
    
     scanf("%d",&number);
  
    if (number ==0)
    {
      
        printf("Double value : %d", array[0] * 2);
    }
  
     if (number == 1)
    {
        printf("Double value : %d", array[1] * 2);
    }
  
     if (number ==2)
    {
        printf("Double value : %d", array[2] * 2);
      
    }
  
     if (number == 3)
    {
        printf("Double value : %d", array[3] * 2);
    }
  
     if (number == 4)
    {
  
        printf("Double value : %d", array[4] * 2);
    }
    return 0;
}
Promote user to Enter number : 4

Double value : 142
 

WBahn

Joined Mar 31, 2012
30,075
As a minor point, I think you are confusing "promote" with "prompt". Also, when your prompt someone for something, you don't use the word itself.

If I were instructed to prompt being coming in the for their name and hometown, I would just say, "What's your name?" followed by "What's your hometown?"

Moving on, hopefully you are about to have an "Aha!" moment regarding arrays.

Let's take your array-based program:

Code:
#include<stdio.h>
int main ()
{
    int array[5] = { 42, 93, 17, 80, 71 };
 
    int number;
  
     printf("Promote user to Enter number  : " );
   
     scanf("%d",&number);
 
    if (number ==0)
    {
     
        printf("Double value : %d", array[0] * 2);
    }
 
     if (number == 1)
    {
        printf("Double value : %d", array[1] * 2);
    }
 
     if (number ==2)
    {
        printf("Double value : %d", array[2] * 2);
     
    }
 
     if (number == 3)
    {
        printf("Double value : %d", array[3] * 2);
    }
 
     if (number == 4)
    {
 
        printf("Double value : %d", array[4] * 2);
    }
    return 0;
}
and leverage the ability to use a computed index to drastically simplify it without changing it's behavior at all:

Code:
#include<stdio.h>
int main ()
{
    int array[5] = { 42, 93, 17, 80, 71 };

    int number;
  
     printf("Promote user to Enter number  : " );
     scanf("%d",&number);

    if ( (0 <= number) && (number < 5) )
        printf("Double value : %d", array[number] * 2);

    return 0;
}
These two programs behave identically.

Some other useful things we can do to further bullet-proof the code is to make it so that if we change the number of elements in the initial array definition the code will automatically adapt accordingly.

Code:
#include<stdio.h>
int main ()
{
    int array[] = { 42, 93, 17, 80, 71 };

    int number;
  
     printf("Promote user to Enter number  : " );
     scanf("%d",&number);

    if ( (0 <= number) && (number < sizeof(array)/sizeof(array[0])) )
        printf("Double value : %d", array[number] * 2);

    return 0;
}
When you leave out the size of the dimension from an array definition, the compiler automatically sizes it to match the length of the initialization list.

The macro sizeof() returns the number of bytes needed to store what the argument refers to. So sizeof(array) returns the number of bytes needed to store the entire array while sizeof(array[0]) returns the number of bytes needed to store the first element of the array. The quotient of the two is how many elements are in the array. With this version of the code, I can add more data to the array trivially easily:

Code:
#include<stdio.h>
int main ()
{
    int array[] = { 42, 93, 17, 80, 71, 13, 81, 27, 69, 34, 91, 51, 25, 19, 33, 68, 36 };

    int number;
  
     printf("Promote user to Enter number  : " );
     scanf("%d",&number);

    if ( (0 <= number) && (number < sizeof(array)/sizeof(array[0])) )
        printf("Double value : %d", array[number] * 2);

    return 0;
}
Consider the amount of effort (and the opportunity for mistakes) if you had tried to extend the non-array-based program (or even your original array-based program).
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
Consider the amount of effort (and the opportunity for mistakes) if you had tried to extend the non-array-based program (or even your original array-based program).
There is a lot of difference between my program and your program. Your program is much better than my program.

After seeing both programs, I can understand I could improve my program. My program also completes the requirement but it could be made even better as you did

I want to extend program, How to extend program and what can be done with this
 

WBahn

Joined Mar 31, 2012
30,075
There is a lot of difference between my program and your program. Your program is much better than my program.

After seeing both programs, I can understand I could improve my program. My program also completes the requirement but it could be made even better as you did

I want to extend program, How to extend program and what can be done with this
We learn to write good programs by writing lots of bad programs (and dealing with their consequences). At first we make improvements by seeing how other people write similar programs (we actually never stop learning by this approach) and later we have enough experience to learn directly from our own poorly written code (and we never stop writing bad code, particularly when we are trying to figure out a viable way just to solve a problem).

You can extend this program in a number of ways. The first might simply be to solve the problem posed in post #5. Once you have that, you can extend it by asking the user first how many values they want to work with and dynamically allocating the array. This will involve pointers and dynamic memory allocation, so you might want to hold off on that enhancement for a while. Instead, you might read a relatively large amount of data from a file. Perhaps write a program that generates a thousand random integers and writes them to a file and then another program that reads the data from the file into an array and sorts it.
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
You can extend this program in a number of ways. The first might simply be to solve the problem posed in post #5. Once you have that, you can extend it by asking the user first how many values they want to work with and dynamically allocating the array. T.


Perhaps this might make it more clear using the context of an entire program.

1) Write a program that asks the user for five integer values.
2) Print them out as a comma-separated list of values on one line.
3) Print out the sum of the five values on the next line.
4) Ask the user which value they want to double, with 1 being the first value entered and 5 being the last value entered.
5) Print out the five values again.
6) Print out the sum of the five values on the next line.

So you might have something like this:

Enter value #1: 42
Enter value #2: 93
Enter value #3: 17
Enter value #4: 80
Enter value #5: 71

Values: 42, 93, 17, 80, 71
Sum: 303
1) Write a program that asks the user for five integer values

Here is program that can store five integer value
C:
#include<stdio.h>
int main ()
{
  int i, array[10], Size = 5;
 
   
  for (i = 0; i < Size; i++)
  {
   printf("Enter element : " );
  
   /*get number from user */
   scanf("%d", &array[i]);
  }

  return 0;
}
Enter element : 5
Enter element : 4
Enter element : 7
Enter element : 9
Enter element : 2

Even I can make it better

C:
#include<stdio.h>
int main ()
{
  int i, array[20], Size;

  printf("Array Size :  " );
 
/*get Size from user */
  scanf ("%d", &Size ); 
 
  for (i = 0; i < Size; i++)
  {
    printf("Enter element : " );
  
     /*get number from user */
    scanf("%d", &array[i]);
  }

  return 0;
}
1) Write a program that asks the user for five integer values.
2) Print them out as a comma-separated list of values on one line

I'm confused in second line. I don't understand how to print them out as a comma-separated list of values on one line

I can do it in separates lines as did it in second program.

How would you print array value entered by user on one line
 

WBahn

Joined Mar 31, 2012
30,075
Even I can make it better

C:
#include<stdio.h>
int main ()
{
  int i, array[20], Size;

  printf("Array Size :  " );

/*get Size from user */
  scanf ("%d", &Size );

  for (i = 0; i < Size; i++)
  {
    printf("Enter element : " );
 
     /*get number from user */
    scanf("%d", &array[i]);
  }

  return 0;
}
This is a good time to start thinking about input validation.

What if the user enters for the size 32? Or -7?

Think about what will happen as your program runs from there. Hint -- one input will not cause any errors but will not produce the expected results, while the other input can cause all kinds of problems. Which is which?

Whenever you get input that you don't control (you can't control what the user will type at a prompt), you should validate the input to ensure that it is acceptable. If it isn't, then do something reasonable. What is "reasonable" depends on the application. You might inform the user about what is wrong and ask them to input new values, or you might just print an error message and exit the program (known as "dying gracefully").

1) Write a program that asks the user for five integer values.
2) Print them out as a comma-separated list of values on one line

I'm confused in second line. I don't understand how to print them out as a comma-separated list of values on one line

I can do it in separates lines as did it in second program.

How would you print array value entered by user on one line
Consider the difference in the following code snippets.

Code:
int x = 15;
int y = 20;

printf("x and y:\n");
printf("%i\n", x);
printf("%i\n", y);
printf("Done.\n");
and

Code:
int x = 15;
int y = 20;

printf("x and y:");
printf("%i", x);
printf("%i", y);
printf("Done.\n");
See if you can now modify it so that it prints out

x and y: 15, 20
Done.
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
What if the user enters for the size 32? Or -7?
This is quick idea.
Code:
#include<stdio.h>
int main ()
{
  int i, array[20], Size;
  printf("Array Size :  " );
/*get Size from user */
  scanf ("%d", &Size );


  if ( Size > 0 && Size < 20)
  {
     for (i = 0; i < Size; i++)
     {
        printf("Enter element : " );
         /*get number from user */
         scanf("%d", &array[i]);
     }
  }
  else
  {
      printf("Array size  is not acceptable");
  }
  return 0;
}
Array Size : 32
Array size is not acceptable

Array Size : -7
Array size is not acceptable

I will make better program then this
 

WBahn

Joined Mar 31, 2012
30,075
An array size of 0 is, technically, acceptable. It just means that the user isn't going to enter any data for the array and your code will work fine since it will fail the for() loop test immediately since 0 < 0 is false. Depending on the application, this might be a perfectly reasonable way of the user telling the program that there simply isn't any data to put in the array. Your code should allow this and it currently doesn't.

An array size of 20 is completely acceptable and your code should allow that and it currently doesn't.

In general, whenever you use an inequality, you should get in the happen of carefully considering what should happen in the case of equality and then decide whether to use a strict or non-strict inequality accordingly. This WILL save you a LOT of grief down the road.

Notice that while both 32 and -7 are not acceptable sizes, there is a very real difference in behavior if they aren't validated. In the case of -7, the for() loop test fails immediately and no data gets stored. Hence nothing bad happens (at least yet -- what happens down the road in later code might be a different matter). But in the case of 32, the loop will run 32 times taking data from the user and putting it at the corresponding memory location as if the array had 32 elements. But it only has 20. What happens to the rest? It gets written into memory that does not belong to the array -- and that probably DOES belong to something else. This is known as an array-bounds error and results in a buffer overflow. This is a serious logic error and invokes what is known as "undefined behavior". It can result in data getting corrupted, incorrect results, programs crashing, computers crashing, and far worse. It is a common source of security vulnerabilities in software and, in systems interfaced to the real world, can and have caused expensive and even fatal system failures. Since your goal is to work with embedded systems, it is something you want to take particular care about.
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
Consider the difference in the following code snippets.
You're statement doesn't match with example

1) Write a program that asks the user for five integer values.
2) Print them out as a comma-separated list of values on one line
The second line is confusing me

Here is program that can print the array value on one line

Code:
#include<stdio.h>

int main()
{
   int array[5] = { 5, 6, 7, 8, 9};

   int i;

   for(i = 0; i < 5; i++)
  
      printf("%d ", array[i]);
 
   return 0;

}
5 6 7 8 9

if I understand you're example correctly you're saying get the value from user and store it on one line that I don't understand how to do it.

you're saying like this

5
6
7
8
9

5 6 7 8 9
 
Last edited:

WBahn

Joined Mar 31, 2012
30,075
You're statement doesn't match with example
In what way? I'm not a mind reader. Please explain.

The second line is confusing me
The example output illustrated what was meant.

Comma-separate list of values on a single line:

Values: 42, 93, 17, 80, 71

Here is program that can print the array value on one line

Code:
#include<stdio.h>

int main()
{
   int array[5] = { 5, 6, 7, 8, 9};

   int i;

   for(i = 0; i < 5; i++)
   
      printf("%d ", array[i]);
  
   return 0;

}
5 6 7 8 9
That's close. Now see if you can get a comma between them so that it looks like this:

5, 6, 7, 8, 9

This is actually not quite as trivial as it might appear at first -- notice that there are five numbers that get printed but only four commas. There are several ways to deal with this, some more clever than others.

if I understand example correctly you're saying get the value from user and store it on one line that I don't understand how to do it.
I never said anything about storing it on one line -- the whole point is to store them in an array. I said, "Print them out as a comma-separated list of values on one line."
 

Thread Starter

anukalp

Joined Jul 28, 2018
158
That's close. Now see if you can get a comma between them so that it looks like this:

5, 6, 7, 8, 9
"
This program print array value with five comma
Code:
#include<stdio.h>
int main()
{
   int array[5] = { 5, 6, 7, 8, 9};
   int i;
   for(i = 0; i < 5; i++)
      printf("%d, ", array[i]);
   return 0;
}
5, 6, 7, 8, 9,

How to remove the last comma ?
 

WBahn

Joined Mar 31, 2012
30,075
This program print array value with five comma
Code:
#include<stdio.h>
int main()
{
   int array[5] = { 5, 6, 7, 8, 9};
   int i;
   for(i = 0; i < 5; i++)
      printf("%d, ", array[i]);
   return 0;
}
5, 6, 7, 8, 9,

How to remove the last comma ?
That's the tricky part, now isn't it.

I'm gonna let you ponder that for a while. Remember, writing programs is about solving problems and we only get good at solving problems by solving LOTS of problems, both big and small.

Here's a couple thoughts to help guide you. Most of the time in your loop you need to print one value and one comma. That's easy. What may not be obvious is that you can print the comma either before the number or after the number. You are doing it the former way (which is the obvious way -- usually a reasonable place to start) and so you need to find a way to detect that you are printing out the last value and not print a comma in that case. Can you see how to rewrite your printf() statement so that it prints the comma before the number so that, except for the beginning and end of the line that is printed out, it looks the same as what you have now. If so, then your problem has been changed to detecting that you are printing the first value and not printing a comma in that case. Which is easier to detect, that you are printing the first value or the last value?
 
Top