Home > Mobile >  How can I set the c variable to that if entered then it should print "hello world 3" or if
How can I set the c variable to that if entered then it should print "hello world 3" or if

Time:03-08

This is a program to take the input at runtime from the user and print hello world depending on the arguments entered. The user can print 2 hello world. However the third hello world is conditional depending if the c value is entered or not.

#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>


int main(int argc, char *argv[])
{
 unsigned int a, b, c;


        a = strtoul(argv[1], 0, 0);
        b = strtoul(argv[2], 0, 0); 
        c = strtoul(argv[3], 0, 0); 

        int *p= NULL;//initialize the pointer as null.

        printf("\n first no %d \n ", a);
        printf("\n second no %d \n ", b);

        if ( c == *p)
        {
                    printf("\n third no %d \n ", c);
        }

    return 0;
}
  1. Suppose I run the program as ./hello 1 2 -> This would print "hello world 1" "hello world 2".
  2. And if I run the program as ./hello 1 2 3 -> This would print "hello world 1" "hello world 2" "hello world 3".
  3. How can I correct my program to get the desired effect?

CodePudding user response:

The first parameter argc of the main function represents the number of arguments passed to the program, so you can check the value of argc to determine the behavior of your program.

(For instance, if you run the program as ./hello 2 7 1 8, then the value of argc will be 5.)

#include <stdio.h>

int main(int argc, char *argv[])
{
    for (int i = 1; i < argc;   i)
    {
        printf("hello world %s\n", argv[i]);
    }
    return 0;
}
  • Related